Example #1
0
 /**
  *
  * @param  array                           $data
  * @param  \biz\core\accounting\models\Invoice $model
  * @return biz\core\accounting\models\Invoice
  * @throws UserException
  */
 public function createFromPurchase($data, $model = null)
 {
     $ids = (array) $data['id_purchase'];
     $vendors = Purchase::find()->select('id_supplier')->distinct()->column();
     if (count($vendors) !== 1) {
         throw new UserException('Vendor harus sama');
     }
     // invoice for GR
     $received = GoodsMovement::find()->select('id_movement')->where(['type_reff' => GoodsMovement::TYPE_PURCHASE, 'reff_id' => $ids])->column();
     $invoiced = InvoiceDtl::find()->select('reff_id')->where(['type_reff' => InvoiceDtl::TYPE_PURCHASE_GR, 'reff_id' => $received])->column();
     $new = array_diff($received, $invoiced);
     $values = GoodsMovement::find()->select(['hdr.id_movement', 'jml' => 'sum(dtl.qty*dtl.trans_value)'])->from(GoodsMovement::tableName() . ' hdr')->joinWith(['goodsMovementDtls' => function ($q) {
         $q->from(GoodsMovementDtl::tableName() . ' dtl');
     }])->andWhere(['hdr.type_reff' => GoodsMovement::TYPE_PURCHASE, 'hdr.reff_id' => $new])->groupBy('hdr.id_movement')->indexBy('id_movement')->asArray()->all();
     unset($data['id_purchase']);
     $data['id_vendor'] = reset($vendors);
     $data['invoice_type'] = MInvoice::TYPE_IN;
     $details = [];
     foreach ($new as $id) {
         $details[] = ['type_reff' => InvoiceDtl::TYPE_PURCHASE_GR, 'reff_id' => $id, 'trans_value' => $values[$id]['jml']];
     }
     // Invoice for Global discount
     // get complete received purchase that invoiced yet :D
     $completed = Purchase::find()->select(['id_purchase', 'discount'])->andWhere(['status' => Purchase::STATUS_RECEIVED, 'id_purchase' => $ids])->andWhere(['<>', 'discount', null])->asArray()->indexBy('id_purchase')->all();
     $invoiced = InvoiceDtl::find()->select('reff_id')->where(['type_reff' => InvoiceDtl::TYPE_PURCHASE_DISCOUNT, 'reff_id' => array_keys($completed)])->column();
     $new = array_diff(array_keys($completed), $invoiced);
     foreach ($new as $id) {
         $details[] = ['type_reff' => InvoiceDtl::TYPE_PURCHASE_DISCOUNT, 'reff_id' => $id, 'trans_value' => -$completed['discount']];
     }
     $data['details'] = $details;
     $model = $this->create($data, $model);
     $model = $this->post('', [], $model);
     return $model;
 }