/** * Remove the specified resource from storage. * * @param Product $product * @param Stock $stock * @return \Illuminate\Http\Response */ public function destroy(Product $product, Stock $stock) { $product = DB::transaction(function () use($product, $stock) { $stock->delete(); $product->updateStock(); return $product; }); return redirect()->route('product.show', $product); }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if (Auth::user()->rol->permisos->contains(6)) { $validator = Validator::make($request->all(), ['nombre' => 'required|unique:productos,nombre', 'precio' => 'required|numeric', 'stock' => 'required|integer', 'imagen' => 'required|image']); $validator->after(function ($validator) use($request) { if ($this->VerificarDimensionImagen($request->file('imagen'))) { $validator->errors()->add('field', 'La imagen debe ser de 500px X 500px.'); } }); if ($validator->fails()) { return back()->withErrors($validator); } $input = $request->except('stock'); $nProducto = Producto::create($input); $nProducto->imagen = $this->GuardarImagen($request); $nStock = Stock::create(); $nStock->id_producto = $nProducto->id; $nStock->cantidad = (int) $request->stock; $nProducto->save(); $nStock->save(); Session::flash('mensaje', 'Nuevo Producto guardado!!!'); return redirect()->route('admin.producto.index'); } else { return abort(401); } }
public static function getLastOrderDateForStockByBranch($stock_id, $branch_id) { $stock = Stock::findOrFail($stock_id); if ($stock->stockOrders()->where('branch_id', $branch_id)->count() > 0) { return $stock->stockOrders()->where('branch_id', $branch_id)->orderBy('created_at', 'desc')->first()->created_at->format('d/m/Y'); } else { return 'N/A'; } }
function getCost($service) { $branchId = Worker::find(Auth::user()->TypeId)->BranchId; $materials = json_decode($service->Materials); $total = 0; foreach ($materials as $material => $quantity) { $product = Stock::where('Code', '=', $material)->where('BranchId', '=', $branchId)->first(); $total += $product->AverageCost * $quantity; } return $total; }
function getName($code, $branch) { // Try getting a normal product for this code $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $branch)->first(); if (!$product) { // If we failed try getting a service. $service = Service::where('Code', '=', $code)->where('BranchId', '=', $branch)->first(); return $service->Description; } return $product->Description; }
public function edit($id) { $branch = array(Auth::user()->branch); if (Auth::user()->role === 'superadmin') { $stock = Stock::findOrFail($id); $product_detail = \DB::select('SELECT s.id, s.cid, s.pid, c.`c_name`, p.`p_name`, p.`buying_price`, p.`selling_price`, s.`quantity`, s.`branch` FROM `stock` s, `product` p, `product_category` c WHERE s.`pid`=p.`pid` AND s.`cid`=c.`cid` AND s.id=' . "'" . $id . "'" . ''); $branch = \DB::table('branch')->whereNotIn('branch_name', $branch)->lists('branch_name', 'branch_name'); return view('stock_transfer.edit', ['stock' => $stock, 'product_detail' => $product_detail, 'branch' => $branch]); } else { return redirect('auth/login'); } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $product = Product::create(Form_Request::all()); $stock = array('product_id' => $product->id, 'tanker_id' => 1, 'quantity' => 0); Stock::create($stock); $redirect = Redirect::back(); if ($product != null) { return $redirect->with('message', 'Successfully saved!'); } else { return $redirect->withInput()->withErrors(['error_message']); } }
/** * Get cash */ public function cash() { $startingCash = config('default.starting_cash'); $stockCost = Stock::dateRangeTo($this->to)->sum('cost'); $amountLoaned = abs(Payment::dateRangeTo($this->to)->where('amount', '<', 0)->sum('amount')); $amountPaid = Payment::dateRangeTo($this->to)->where('amount', '>', 0)->sum('amount'); $cashSales = Sale::dateRangeTo($this->to)->where('user_id', null)->get(); $totalCashSales = 0; foreach ($cashSales as $cashSale) { $totalCashSales += $cashSale->total; } $initialBalances = User::dateRangeTo($this->to)->sum('initial_balance'); $paymentsToBank = Bank::dateRangeTo($this->to)->sum('amount'); return $startingCash + $amountPaid + $totalCashSales + $initialBalances - $stockCost - $amountLoaned - $paymentsToBank; }
public function doOrderStockItem(Request $request) { $stock_item = Stock::findOrFail($request->input('item_id')); $password = $request->input('password'); $mode = $request->input('mode'); if (!Hash::check($password, Auth::user()->password) && $mode == 'save') { return redirect()->back()->with('stock-order-add-password-error', true); } else { $stock_item->addOrder(['mode' => $mode, 'amount' => (int) $request->input('amount'), 'branch_id' => $request->input('branch_id'), 'urgent' => $request->input('urgent'), 'required_date' => $request->input('required_date'), 'send_reminder' => $request->input('send_reminder'), 'reminder_days' => $request->input('reminder_days'), 'comments' => $request->input('comments')]); if ($mode == 'save') { return redirect()->back()->with('stock-order-added', true); } else { return redirect()->back()->with('stock-order-saved-for-later', true); } } }
break; case 10: $creditSales += $transaction->Amount; $sales += $transaction->Amount; break; } } $sold = array(); // Get only sales transactions. foreach (CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->where('Type', '=', 1)->get() as $transaction) { foreach (Sale::where('TransactionId', '=', $transaction->Id)->get() as $sale) { // Go through sale breackdown. foreach (SaleBreakdown::where('SaleId', '=', $sale->Id)->get() as $salebreakdown) { // Extract Product or Service. // TODO: Get only stock from user's branch. $product = Stock::where('Code', '=', $salebreakdown->Code)->first(); if ($product) { // Check if we have already sold this product. if (array_key_exists($product->Code, $sold)) { $sold[$salebreakdown->Code]['Quantity'] += $salebreakdown->Quantity; } else { $sold[$salebreakdown->Code] = array('Description' => $product->Description, 'Quantity' => $salebreakdown->Quantity); } } else { $service = Service::where('Code', '=', $salebreakdown->Code)->first(); if ($service) { // Check if we have already sold this service. if (array_key_exists($service->Code, $sold)) { $sold[$salebreakdown->Code]['Quantity'] += $salebreakdown->Quantity; } else { $sold[$salebreakdown->Code] = array('Description' => $service->Description, 'Quantity' => $salebreakdown->Quantity);
/** * Function that creates a new product. * * @return Response */ public function createProduct() { // Validate Input. $validator = Validator::make(Input::all(), array('code' => 'required', 'description' => 'required', 'cost' => 'required', 'price' => 'required', 'minimum' => 'required', 'providerId' => 'required')); $response = array(); if ($validator->fails()) { $response['state'] = 'Error'; $response['error'] = 'Informacion incompleta!'; return response()->json($response); } // 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()); } // Get the worker. $worker = Worker::find(Auth::user()->TypeId); // Verify that a product with code doesn't already exist. $product = Stock::where('Code', '=', Input::get('code'))->where('BranchId', '=', $worker->BranchId)->first(); if ($product) { $response['state'] = 'Error'; $response['error'] = 'Ya existe un producto con el codigo especificado!'; return response()->json($response); } // Create the product. Stock::create(array('Code' => Input::get('code'), 'Description' => Input::get('description'), 'Cost' => Input::get('cost'), 'Price' => Input::get('price'), 'Minimum' => Input::get('minimum'), 'ProviderId' => Input::get('providerId'), 'BranchId' => $worker->BranchId, 'AverageCost' => Input::get('cost'), 'Quantity' => 0)); // Prepare to notify admins. // Admins are UserLevel 1 $admins = User::where('UserLevel', '=', 1)->get(); // Now send notifications to admins. foreach ($admins as $admin) { $reason = "Se ha creado un nuevo producto: " . Input::get('description') . " El producto fue creado por {$worker->Name}."; Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/product/' . Input::get('code') . '/branchId/' . $worker->BranchId, 'Seen' => false)); } $response['state'] = 'Success'; // Return result. return response()->json($response); }
public function getDelete($id) { $stock = Stock::find($id); $stockCount = StockCount::where('product_id', '=', $stock->product_id)->where('stock_info_id', '=', $stock->stock_info_id)->get(); if ($stock->entry_type == 'StockIn') { $stockCount[0]->product_quantity = $stockCount[0]->product_quantity - $stock->product_quantity; $stockCount[0]->save(); } elseif ($stock->entry_type == 'StockOut') { $stockCount[0]->product_quantity = $stockCount[0]->product_quantity + $stock->product_quantity; $stockCount[0]->save(); } elseif ($stock->entry_type == 'Transfer') { $stockCount[0]->product_quantity = $stockCount[0]->product_quantity + $stock->product_quantity; $stockCount[0]->save(); $stockCountTo = StockCount::where('product_id', '=', $stock->product_id)->where('stock_info_id', '=', $stock->to_stock_info_id)->get(); $stockCountTo[0]->product_quantity = $stockCountTo[0]->product_quantity - $stock->product_quantity; $stockCountTo[0]->save(); } $stock->delete(); Session::flash('message', 'Stock has been Successfully Deleted.'); return Redirect::to('stocks/index'); }
/** * Execute the console command. * * @return mixed */ public function handle() { // Get all workers that haven't been fired. $workers = Worker::where('Fired', '=', false)->get(); foreach ($workers as $worker) { // First let's check if it has a long term loan active. $currentMonth = date('Y-m'); if ($worker->Loan > 0) { // Let's check if we have gotten this months loan payment. $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 2)->get(); if (count($loans) == 0) { // Charge worker for loan. $charge = $worker->Loan / $worker->Months; $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 2, 'WorkerId' => $worker->Id)); $worker->Loan -= $charge; $worker->Months--; $worker->save(); } } // Now let's check if we have gotten this month's insurance fee. $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 3)->get(); if (count($loans) == 0) { // Charge worker for loan. $charge = $worker->Insurance - $worker->Patron; if ($charge > 0) { $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 3, 'WorkerId' => $worker->Id)); } } // Get workers days. $days = WorkerSalary::where('SystemProcess', '=', false)->where('WorkerId', '=', $worker->Id)->get(); // Now let's check if we need to add a bonus to the worker. if ($worker->BonusPercentage > 0) { switch ($worker->BonusSource) { case 'production': foreach ($days as $day) { if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) { // If worker is on general production then let's get what was produced and the price of what was produced. $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->get(); $totalProduced = 0; $pIds = array(); foreach ($produced as $p) { // Check if we have already checked this product. if (!in_array($p->ProductionId, $pIds)) { array_push($pIds, $p->ProductionId); // Check if product is finished. $product = Production::find($p->ProductionId); if ($product->Stage == $product->maxStage()) { $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first(); $totalProduced += $finalProduct->Price; } } } $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100); } // Add insurance Patron Value for the day. // TODO: I should check how many days are in this month, $day->Insurance = $worker->Patron / 30; $day->save(); } break; case 'productionsingle': foreach ($days as $day) { if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) { // If worker is on single production then let's get what he produced and the price of what was produced. $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->where('WorkerId', '=', $worker->Id)->get(); $totalProduced = 0; $pIds = array(); foreach ($produced as $p) { // Check if we have already checked this product. if (!in_array($p->ProductionId, $pIds)) { array_push($pIds, $p->ProductionId); // Check if product is finished. $product = Production::find($p->ProductionId); if ($product->Stage == $product->maxStage()) { $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first(); $totalProduced += $finalProduct->Price; } } } $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100); } // Add insurance Patron Value for the day. // TODO: I should check how many days are in this month, $day->Insurance = $worker->Patron / 30; $day->save(); } break; case 'sales': foreach ($days as $day) { if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) { // If worker is on general sales then let's get all sales. $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('BranchId', '=', $worker->BranchId)->get(); $totalSales = 0; foreach ($sales as $sale) { $totalSales += $sale->Value; } $day->Bonus += $totalSales * ($worker->BonusPercentage / 100); } // Add insurance Patron Value for the day. // TODO: I should check how many days are in this month, $day->Insurance = $worker->Patron / 30; $day->save(); } break; case 'salessingle': foreach ($days as $day) { if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) { // If worker is on general sales then let's get all sales. $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('WorkerId', '=', $worker->Id)->get(); $totalSales = 0; foreach ($sales as $sale) { $totalSales += $sale->Value; } $day->Bonus += $totalSales * ($worker->BonusPercentage / 100); } // Add insurance Patron Value for the day. // TODO: I should check how many days are in this month, $day->Insurance = $worker->Patron / 30; $day->save(); } break; } } } // Get all days that have not been processed and set them as being processed. $allDays = WorkerSalary::where('SystemProcess', '=', false)->get(); foreach ($allDays as $day) { $day->SystemProcess = true; $day->save(); } }
function getName($code, $branchId) { // Get product. $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $branchId)->first(); return $product->Description; }
/** * Get the total expenses * */ public function expenses() { return Stock::sum('cost'); }
public function resetStock() { $stock = Stock::where('product_id', $this->product_id)->where('location_id', $this->location_id)->first(['id', 'qty']); if ($stock != null) { $stock->qty += $this->qty; Log::debug('Requesition: reset item qty: success', ['product_id' => $this->product_id, 'location_id' => $this->location_id, 'qty_return' => $this->qty, 'qty_total' => $stock->qty]); return $stock->save(); } Log::debug('Requesition: reset item qty: error', ['product_id' => $this->product_id, 'location_id' => $this->location_id, 'qty_return' => $this->qty, 'qty_total' => $stock->qty]); return false; }
public function getProduct() { // Validate Input. $validator = Validator::make(Input::all(), array('product' => 'required', 'usingCode' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'Informacion incompleta!']); } // 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(['state' => 'Unauthorized']); } // Get the product. $product; if (Input::get('usingCode') == 'true') { $branchId = Worker::find(Auth::user()->TypeId)->BranchId; $product = Stock::where('Code', '=', Input::get('product'))->where('BranchId', '=', $branchId)->first(); } else { $product = Stock::find(Input::get('product')); } if (!$product) { $response['state'] = 'Error'; $response['error'] = 'No existe un producto con este codigo!'; return response()->json($response); } // Return provider info. $response['state'] = 'Success'; $response['product'] = $product; return response()->json($response); }
public function show($id) { $stock = Stock::findOrFail($id); return view('stock.show', compact('stock')); }
<div class="widget-header"> <i class="icon-shopping-cart"></i> <h3>Materiales Ocupados</h3> </div> <!-- /widget-header --> <div class="widget-content table-responsive table-compras"> <table class="table table-striped table-bordered"> <thead> <tr> <th>Material</th> <th>Cantidad Usado</th> </tr> </thead> <tbody> @foreach(json_decode($stage->Materials) as $code => $quantity) <?php $s = Stock::where('Code', '=', $code)->where('BranchId', '=', $worker->BranchId)->first(); ?> <tr><td>{{ $s->Description }}</td><td>{{ $quantity }}</td></tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> <div class="span6"> <div class="row-fluid form-horizontal"> <div class="control-group span8"> <label class="control-label">Trabajador Asignado:</label> <div class="controls">
/** * Function that generates order. * * @return Response */ public function aiOrder() { // Get all branches. $branches = Branch::all(); // Get all providers. $providers = Provider::where('AIManaged', '=', true)->get(); // Prepare order array. $order = array(); // Loop through providers. foreach ($providers as $provider) { $order[$provider->Id] = array(); // Get all products. $products = Stock::where('Provider', '=', $provider)->get(); foreach ($products as $product) { $order[$provider->Id][$product->Code][$provider->BranchId] = array('Code' => $product->Code, 'Description' => $product->Description, 'Exist' => $product->Quantity, 'Cost' => $product->Cost, 'Minimum' => $product->Minimum, 'Order' => 0, 'Average' => 0, 'Sold' => 0); } // Get all the products sold in selected sample range. $today = date('Y-m-d H:i:s'); switch ($provider->SampleRange) { case '1week': $startDate = date('Y-m-d H:i:s', strtotime($today) - 604800); $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 7; } break; case '2week': $startDate = date('Y-m-d H:i:s', strtotime($today) - 1209600); $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 14; } break; case '1month': $startDate = date('Y-m-d H:i:s', strtotime($today) - 2419200); $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 30; } break; case '3month': $startDate = date('Y-m-d H:i:s', strtotime($today) - 7257600); $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 90; } break; case '1year': $startDate = date('Y-m-d H:i:s', strtotime($today) - 29030400); $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get(); foreach ($sales as $sale) { $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Sold'] += $item->Quantity; } } } // Now calculate average of each product. foreach ($order as $index => $product) { $order[$index]['Average'] = $product['Sold'] / 365; } break; } } // Now calculate amount to order based on average, existence, minimum and order range. switch (Input::get('orderRange')) { case '3day': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 3; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = round($estimatedOrder); } break; case '1week': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 7; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = round($estimatedOrder); } break; case '2week': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 14; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = round($estimatedOrder); } break; case '1month': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 30; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = round($estimatedOrder); } break; case '3month': foreach ($order as $index => $product) { $estimatedOrder = $product['Average'] * 90; // Order should be at least twice minimum required with existence influded. if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) { $estimatedOrder = $product['Minimum'] * 2; } $order[$index]['Order'] = round($estimatedOrder); } break; } // Check if we have recently made an order for this provider to fix order. $aiOrders = AIOrder::where('GenerationDate', '>', date('Y-m-d H:i:s', strtotime($today) - 259200))->where('Received', '=', false)->get(); foreach ($aiOrders as $o) { // Get breakdown and remove quantity from order. $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $o->Id)->get(); foreach ($breakdown as $item) { if (array_key_exists($item->Code, $order)) { $order[$item->Code]['Order'] -= $item->Quantity; } } } $order = AIOrder::findOrFail(1); $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $order->Id)->get(); // Ship order... Mail::send('emails.ai.makeOrder', ['order' => $order, 'breakdown' => $breakdown], function ($message) { $message->to('*****@*****.**'); $message->subject('Orden de Compra'); }); $response['state'] = 'Success'; $response['message'] = 'Servicio eliminado exitosamente!'; return response()->json($response); }
public function acceptOrder(Request $request) { $clientStock = ClientStock::find($request['orderId']); $stock = Stock::find($clientStock->stockId); $login = Login::where('remember_token', '=', $request->header('token'))->where('login_from', '=', $request->ip())->join('members', 'members.id', '=', 'logins.member_id')->where('logins.status', '=', '1')->first(); $stock->quantity = AddProduct::where('stockId', $stock->id)->where('added', 1)->sum('quantity') - AddProduct::where('stockId', $stock->id)->where('added', 0)->sum('quantity'); if ($stock->quantity < $clientStock->amount) { $returnData = array('status' => 'ok', 'code' => '422', 'clientStock' => $clientStock, 'message' => 'Insufficient Stock'); return Response::json($returnData, 422); } if ($request['status'] == 1) { $clientStock->acceptedBy = $login->member_id; $clientStock->status = 1; $clientStock->save(); $addProduct = new AddProduct(); $addProduct->stockId = $clientStock->stockId; $addProduct->quantity = $clientStock->amount; $addProduct->addedBy = $login->member_id; $addProduct->added = 0; $addProduct->ticket = $clientStock->ticket; $addProduct->save(); $returnData = array('status' => 'ok', 'code' => '200', 'clientStock' => $clientStock, 'addProduct' => $addProduct); return Response::json($returnData, 200); } if ($request['status'] == 0) { $clientStock->acceptedBy = $login->member_id; $clientStock->status = 3; $clientStock->save(); $account = new Account(); $account->ticket = $clientStock->ticket; $account->amount = $clientStock->commission + $clientStock->margin; $account->type = 1; $account->addedBy = $login->member_id; $account->memberId = $clientStock->memberId; $account->save(); $returnData = array('status' => 'ok', 'code' => '200', 'clientStock' => $clientStock, 'account' => $account); return Response::json($returnData, 200); } }
public function postUpdateStock($id) { $ruless = array('product_id' => 'required', 'branch_id' => 'required', 'product_quantity' => 'required', 'entry_type' => 'required'); $validate = Validator::make(Input::all(), $ruless); if ($validate->fails()) { return Redirect::to('stocks/edit', $id)->withErrors($validate); } else { $stock = Stock::find($id); $this->updateStockData($stock); return Redirect::to('stocks/index'); } }
/** * Function that submits stocktake. * * @return Response */ public function submitStockTake() { // Validate Input. $validator = Validator::make(Input::all(), array('stockItems' => 'required')); $response = array(); if ($validator->fails()) { $response['state'] = 'Error'; $response['error'] = 'Es necesario escribir el codigo del producto'; return response()->json($response); } // Check that user is part of authorized staff. if (Auth::user()->Type != 1) { $response['state'] = 'No Autorizado'; $response['error'] = 'Usuario no autorizado!'; return response()->json($response); } // Get the branch of the current worker. $branchId = Worker::find(Auth::user()->TypeId)->BranchId; // Create Stocktake. $stocktake = StockTake::create(array('Created' => date('Y-m-d H:i:s'), 'BranchId' => $branchId)); // Now insert the breakdown of the stock. foreach (Input::get('stockItems') as $item) { // Get product. $product = Stock::find($item['id']); // Insert breakdown. StockTakeBreakdown::create(array('StockTakeId' => $stocktake->Id, 'Code' => $product->Code, 'SystemQuantity' => $product->Quantity, 'Counted' => $item['quantity'], 'Difference' => $item['quantity'] - $product->Quantity, 'State' => 0, 'ExtraData' => '')); } $response['state'] = 'Success'; $response['message'] = 'Toma de inventario agregado exitosamente!'; return response()->json($response); }
/** * Function that gets reservation information. * * @return Response */ public function getReservationData() { // Validate Input. $validator = Validator::make(Input::all(), array('id' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'No se recibieron los datos necesarios!']); } // Check that user is part of authorized staff. if (Auth::user()->Type != 1) { $response['state'] = 'No Autorizado'; $response['error'] = 'Usuario no autorizado!'; return response()->json($response); } // Get user branch. $worker = Worker::find(Auth::user()->TypeId); $userBranch = $worker->BranchId; // Get the reservation. $reservation = Reservation::find(Input::get('id')); // Get the breakdown of the reservation. $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $reservation->Id)->get(); $reservationItems = array(); foreach ($reservationBreakdown as $breakdown) { // Try getting the product. $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first(); if (!$product) { // If it's not a product it's a service. $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first(); array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'description' => $service->Description, 'price' => $service->Price)); } else { array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'note' => $product->Description, 'price' => $product->Price)); } } // Get the client's or institution's information. $client; if ($reservation->CreditorId != 0) { if ($reservation->CreditorType != 1) { $temp = Institution::find($reservation->CreditorId); $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->RUC); } else { $temp = Client::find($reservation->CreditorId); $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->Id); } } else { $client = array('Name' => 'No asignado', 'Address' => 'No asignado', 'Id' => 'No asignado'); } // Get configuration info. $config = Configuration::find(0); // Now prepare all the information to be returned to user. $response['state'] = 'Success'; $response['clientInfo'] = $client; $response['reservationInfo'] = array('Date' => date('Y-m-d', strtotime($reservation->Created)), 'Life' => $config->ReservationLife, 'ReservationId' => $reservation->Id, 'SubTotal' => $reservation->Value, 'Discount' => $reservation->Discount, 'Tax' => $reservation->Tax, 'Deposit' => $reservation->Deposit, 'Total' => $reservation->Value + $reservation->Tax - $reservation->Discount); $response['reservationItems'] = $reservationItems; // Return response. return response()->json($response); }
/** * Display a stockItems for user. *@param $recipient * @param $level * @return Response */ public function stock_items($recipient, $level) { // return Stock::where('recipient_id',Auth::user()->recipient_id)->get(); if ($level == '1') { $dispatch = Stock::where('recipient_id', $recipient)->get(); } elseif ($level == '2') { $orgunit = Recipient::find($recipient); $arr = [0, $recipient]; array_push($arr, $recipient); foreach ($orgunit->childrens as $val) { array_push($arr, $val->id); } $dispatch = DB::table('stock')->whereIn('recipient_id', $arr)->get(); } elseif ($level == '3') { $orgunit = Recipient::find($recipient); $arr = [0]; array_push($arr, $recipient); foreach ($orgunit->childrens as $val) { array_push($arr, $val->id); $orgunit1 = Recipient::find($val->id); foreach ($orgunit1->childrens as $val) { array_push($arr, $val->id); } } $dispatch = DB::table('stock')->whereIn('recipient_id', $arr)->get(); } else { Stock::where('recipient_id', Auth::user()->recipient_id)->get(); } return $dispatch; }
private function returnItems($items, $lastitem) { // Get user branch. $userBranch = Worker::find(Auth::user()->TypeId)->BranchId; // Loop through all items. foreach ($items as $code => $info) { if ($code == $lastitem) { return; } // Check if it is a product. $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first(); if (!$product) { // Check if it is a service. $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first(); if (!$service) { $response['state'] = 'Error'; $response['error'] = 'No se reconocio uno de los productos o servicios!'; return response()->json($response); } // Return materials. $materials = json_decode($service->Materials); foreach ($materials as $materialCode => $quantity) { $stock = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first(); $stock->Quantity += $quantity * $info->quantity; $stock->save(); } // TODO: Check if any special functions need to be executed. } else { // Return products. $product->Quantity += $info->quantity; $product->save(); } } }
<!-- /widget-header --> <div class="widget-content table-responsive table-compras"> <table class="table table-striped table-bordered"> <thead> <tr> <th>Codigo</th> <th>Descripcion</th> <th>Cantidad</th> <th>Costo</th> <th>Total</th> </tr> </thead> <tbody> @foreach($billBreakdown as $breakdown) <?php $s = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $worker->BranchId)->first(); $total += $breakdown->Quantity * $s->Cost; ?> <tr><td>{{ $s->Code }}</td><td>{{ $s->Description }}</td><td>{{ $breakdown->Quantity }}</td><td>{{ $s->Cost }}</td><td>{{ $breakdown->Quantity*$s->Cost }}</td></tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> <div class="span6"> <div class="row-fluid form-horizontal"> <div class="control-group span8"> <label class="control-label">Total:</label>
public function addStock() { $items = $this->receiveItems; foreach ($items as $item) { if ($item->status == ReceiveItem::SUCCESS) { $stock = Stock::where('product_id', $item->product_id)->where('location_id', $item->location_id)->first(); $stock->qty = $stock->qty + $item->qty; Log::info('add-stock: receive item', ['stock' => "product_id: {$stock->product_id}, location_id:{$stock->location_id}", 'product_id' => $item->product_id, 'location_id' => $item->location_id, 'stockNow' => $stock->qty, 'stockAdd' => $item->qty]); $stock->save(); } } }
public function getSale($invoice_id) { $saleDetails = SAleDetail::where('invoice_id', '=', $invoice_id)->get(); $sale = Sale::where('invoice_id', '=', $invoice_id)->get(); foreach ($saleDetails as $saleDetail) { $stock = new Stock(); $stock->branch_id = $saleDetail->branch_id; $stock->product_id = $saleDetail->product_id; $stock->product_type = $saleDetail->product_type; $stock->product_quantity = $saleDetail->quantity; $stock->entry_type = "StockOut"; $stock->remarks = $saleDetail->remarks; $stock->user_id = Session::get('user_id'); $stock->stock_info_id = $saleDetail->stock_info_id; $stock->status = "Activate"; $stockCount = StockCount::where('product_id', '=', $saleDetail->product_id)->where('stock_info_id', '=', $saleDetail->stock_info_id)->get(); if (!empty($stockCount[0])) { if ($stockCount[0]->product_quantity >= $saleDetail->quantity) { $stockCount[0]->product_quantity = $stockCount[0]->product_quantity - $saleDetail->quantity; $stock->save(); $stockCount[0]->save(); $sale[0]->is_sale = 1; $sale[0]->save(); Session::flash('message', 'Stock has been Successfully Balanced.'); } else { Session::flash('message', 'You Dont have enough products in Stock'); } } else { Session::flash('message', 'You Dont have This products in This Stock'); } } return Redirect::to('sales/index'); }
/** * Function that gets order Information. * * @return Response */ public function getStageInfo() { // Validate Input. $validator = Validator::make(Input::all(), array('code' => 'required', 'stage' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'El codigo del ataud es necesario!']); } // 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()); } // Get Item in question. $item = Production::find(Input::get('code')); if (!$item) { return response()->json(['error' => 'No existe un ataud con este codigo!']); } // Make sure item has finished production. $maxStage = $item->maxStage(); if ($item->Stage <= $maxStage) { return response()->json(['error' => 'Este ataud no ha salido del proceso de produccion!']); } // Now get the stages, workers and materials used. $usedMaterials = array(); $stages = $item->stages; foreach ($stages as $stage) { $materials = json_decode($stage->Materials, true); if ($stage->Stage == Input::get('stage')) { foreach ($materials as $material => $quantity) { $description = Stock::where('Code', '=', $material)->where('BranchId', '=', 2)->first()->Description; $usedMaterials[$material]['description'] = $description; $usedMaterials[$material]['quantity'] = $quantity; } } } // Return information. $response['materials'] = $usedMaterials; return response()->json($response); }