/** * Function that adds a bill to the system. * * @return Response */ public function addBill() { // Validate Input. $validator = Validator::make(Input::all(), array('billNumber' => 'required', 'billProvider' => 'required', 'billValue' => 'required', 'billCredit' => 'required', 'billProducts' => 'required', 'billDiscount' => 'required')); if ($validator->fails()) { return response()->json(['error' => $validator->messages()]); } // Validate file input. /*$validator = Validator::make(Request::all(), array( 'billImage' => 'required|mimes:jpeg,jpg,png|max:2000' ) ); if($validator->fails()) { return response()->json(['error' => $validator->messages()]); }*/ // Check that user is part of authorized staff. if (Auth::user()->Type != 1) { // If they are unauthorized no point in returning anything. return response()->json(array()); } // Calculate the discount percentage. $discount = 1 - Input::get('billDiscount') / (Input::get('billDiscount') + Input::get('billValue')); // Let's check that the bill Number is unique for this provider. $bill = ProviderBill::where('BillNumber', '=', Input::get('billNumber'))->where('ProviderId', '=', Input::get('billProvider'))->first(); if ($bill) { // Inform user bill already exists. return response()->json(['error' => 'Una factura con el mismo numero y para el mismo proveedor ya existe en el sistema!']); } // Get the branch of the current worker. $worker = Worker::find(Auth::user()->TypeId); $branchId = $worker->BranchId; // Create Bill it can either be 1 - pending payment or 2 paid. $state = Input::get('billCredit') == 'true' ? 1 : 2; // If we have already paid it upfront mark is as paid. if ($state == 2) { // Make transaction for user's cashbox. $userId = Auth::user()->Id; $cashbox = Cashbox::where('UserId', '=', $userId)->where('Close', '=', NULL)->first(); if (!$cashbox) { return response()->json(['error' => 'No hay una caja abierta!']); } $bill = ProviderBill::create(array('Date' => date('Y-m-d'), 'BillNumber' => Input::get('billNumber'), 'Value' => Input::get('billValue'), 'Credit' => Input::get('billCredit') == 'true' ? true : false, 'State' => $state, 'ProviderId' => Input::get('billProvider'), 'BranchId' => $branchId, 'Discount' => Input::get('billDiscount'))); // Prepare reason for transaction. $provider = Provider::find(Input::get('billProvider')); $reason = "Pago a {$provider->Name} por Factura Numero: " . Input::get('billNumber'); // Transaction types 1 : Sale. 2 : Payment. 3 : Withdrawal. 4 : Deposit. $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 2, 'Amount' => Input::get('billValue'), 'Reason' => $reason)); $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => $transaction->Id, 'Date' => date('Y-m-d'), 'Payment' => Input::get('billValue'), 'Debt' => 0)); } else { $bill = ProviderBill::create(array('Date' => date('Y-m-d'), 'BillNumber' => Input::get('billNumber'), 'Value' => Input::get('billValue'), 'Credit' => Input::get('billCredit') == 'true' ? true : false, 'State' => $state, 'ProviderId' => Input::get('billProvider'), 'BranchId' => $branchId, 'Discount' => Input::get('billDiscount'))); $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => 0, 'Date' => date('Y-m-d'), 'Payment' => 0, 'Debt' => Input::get('billValue'))); } // Now add items that came with bill to stock. $notified = false; $billProducts = json_decode(Input::get('billProducts')); foreach ($billProducts as $product => $data) { // First get the item in question from stock. $item = Stock::where('Code', '=', $product)->where('BranchId', '=', $branchId)->where('ProviderId', '=', Input::get('billProvider'))->first(); // Now check if the price was changed. if ($item->Cost != $data->cost && !$notified) { // Prepare to notify admins. // Admins are UserLevel 1 $admins = User::where('UserLevel', '=', 1)->get(); // Now send notifications to admins. foreach ($admins as $admin) { $provider = Provider::find(Input::get('billProvider')); $worker = Worker::find(Auth::user()->TypeId); $reason = "Hubo cambio de precio en al menos un producto en la factura: " . Input::get('billNumber') . " de el Proveedor {$provider->Name}. " . "La factura fue agregada por {$worker->Name}."; Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/provider/' . $provider->Id . '/viewBill/' . Input::get('billNumber'), 'Seen' => false)); } $notified = true; } // Now add it to the breakdown of the bill. ProviderBillBreakdown::create(array('ProviderBillId' => $bill->Id, 'Code' => $product, 'Quantity' => $data->quantity, 'OldCost' => $item->Cost, 'CurrentCost' => $data->cost)); // Get the average cost of the stock. $quantity = $item->Quantity; $totalAverage = $item->AverageCost * $quantity; $totalCurrent = $data->quantity * $data->cost * $discount; // Calculate new average value. $newAverage = ($totalAverage + $totalCurrent) / ($quantity + $data->quantity); // Update the stock. $item->AverageCost = $newAverage; $item->Quantity += $data->quantity; $item->save(); // Now update all costs of all products with this code and provider. $items = Stock::where('Code', '=', $product)->where('ProviderId', '=', Input::get('billProvider'))->get(); foreach ($items as $i) { $i->Cost = $data->cost; $i->save(); } } /*$disk = Storage::disk('local'); // Check if directory for this Provider exists. $directory = Input::get('billProvider').'/'; if(!$disk->exists($directory)) { // Create directory for this provider. $disk->makeDirectory($directory); } $file = Request::file('billImage'); $extension = $file->getClientOriginalExtension(); // Now move the save the file to directory. $disk->put($directory.$bill->Id.'.'.$extension, file_get_contents($file)); */ // Return suggestions. return response()->json(['success' => 'Factura agregada exitosamente al sistema!']); }