示例#1
0
 /**
  * Create new purchase
  *
  * After submitting form from previous page (@see self::newAction()), user will hit
  * this page via ajax request. All inputs are validate here, if it is valid, insert
  * the data into database.
  *
  * If the purchase status is `delivered` and user check the `update_stock_level` checkbox,
  * increase the stock in the selected warehouse as well based on the item quantity that
  * have just purchased.
  *
  * @return \Zend\Http\Response|\Zend\Stdlib\Message
  */
 public function createAction()
 {
     $this->ensure('post');
     $input = $this->autoFilledInputFilter(PurchaseInput::class);
     if ($input->isValid()) {
         $data = $input->getValues();
         $purchase = $this->mapper(Purchase::class)->create($data + ['creator' => $this->user()]);
         $supplierName = $data['supplier_name'];
         if (trim($supplierName)) {
             $supplier = $this->em()->getRepository(Supplier::class)->findOneBy(['name' => $supplierName]);
             if (!$supplier) {
                 $supplier = new Supplier();
                 $supplier->setName($supplierName);
                 $this->em()->persist($supplier);
             }
             $purchase->setSupplier($supplier);
         }
         $this->insertRawItems($purchase, $data['raw_items']);
         $this->commit();
         $this->getEventManager()->trigger('items_inserted', $this, $data);
         // increase stock in warehouse
         if ($this->getRequestPost('update_stock_level') && $data['status'] == Purchase::STATUS_DELIVERED) {
             $this->getStockService()->increaseStock($purchase, $this->user(), $data['raw_items']);
         }
         // log all changes
         $this->getLogService()->logCreatePurchase($this->user(), $purchase, $data);
         return $this->jsonOk([], 201);
     }
     return $this->jsonError($input->getMessages(), 400);
 }