/** * Function that creates a new item for specified order. * * @return Response */ public function createItem() { // Validate Input. $validator = Validator::make(Input::all(), array('workerId' => 'required', 'grip' => 'required', 'code' => 'required', 'orderId' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'All fields are required!']); } // 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()); } // Check that we still have to produce this kind of item. $production = Production::where('Code', '=', Input::get('code'))->where('OrderId', '=', Input::get('orderId'))->get(); $productionCount = 0; foreach ($production as $produced) { $productionCount++; } $breakdown = OrderBreakdown::where('OrderId', '=', Input::get('orderId'))->where('Code', '=', Input::get('code'))->first(); // If we have already made all the items of this type for this order inform user. if ($productionCount == $breakdown->Quantity) { return response()->json(['error' => 'Ya no es necesario crear mas ataudes de este tipo para esta orden!']); } // Check that we aren't producing more items with grips than necessary. $gripCount = 0; foreach ($production as $produced) { if ($produced->Grip) { $gripCount++; } } // If we have already created enough items of this type with grips for this order inform user. if ($gripCount == $breakdown->Grips) { return response()->json(['error' => 'Ya no es necesario crear mas ataudes de este tipo con agarraderos para esta orden!']); } // Now check that we aren't creating items without grips when there are only items with grips left to be created. if ($productionCount - $gripCount >= $breakdown->Quantity - $breakdown->Grips && Input::get('grip') == 'false') { return response()->json(['error' => 'Solo hace falta crear ataudes de este tipo con agarraderos para esta orden!']); } $grip = Input::get('grip') == 'true' ? true : false; // Get branchId. $branchId = Worker::find(Auth::user()->TypeId)->BranchId; // Now if all checks have been passed go ahead and create new item. $item = Production::create(array('OrderId' => Input::get('orderId'), 'Code' => Input::get('code'), 'Stage' => 1, 'Grip' => $grip, 'BranchId' => $branchId)); // Now create the production stage and assign it to appropriate worker. ProductionStage::create(array('ProductionId' => $item->Id, 'Stage' => 1, 'WorkerId' => Input::get('workerId'), 'Materials' => '{}', 'Date' => date('Y-m-d H:i:s'))); // Prepare response. $response = array(); $response['productionId'] = $item->Id; return response()->json($response); }