/** * @return \yii\db\ActiveQuery */ public function getInvoiceDtls() { return $this->hasMany(InvoiceDtl::className(), ['invoice_id' => 'id']); }
/** * @param array $data * @param \biz\core\accounting\models\Invoice $model * @return \biz\core\accounting\models\Invoice * @throws UserException */ public function createFromSales($data, $model = null) { $ids = (array) $data['id_sales']; $vendors = Sales::find()->select('id_customer')->distinct()->column(); if (count($vendors) !== 1) { throw new UserException('Vendor harus sama'); } // invoice for GI $released = GoodsMovement::find()->select('id_movement')->where(['type_reff' => GoodsMovement::TYPE_SALES, 'reff_id' => $ids])->column(); $invoiced = InvoiceDtl::find()->select('reff_id')->where(['type_reff' => InvoiceDtl::TYPE_SALES_GI, 'reff_id' => $released])->column(); $new = array_diff($released, $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'); }])->where(['hdr.type_reff' => GoodsMovement::TYPE_SALES, 'hdr.reff_id' => $new])->groupBy('hdr.id_movement')->indexBy('id_movement')->asArray()->all(); unset($data['id_sales']); $data['id_vendor'] = reset($vendors); $data['invoice_type'] = MInvoice::TYPE_OUT; $details = []; foreach ($new as $id) { $details[] = ['type_reff' => InvoiceDtl::TYPE_SALES_GI, 'reff_id' => $id, 'trans_value' => $values[$id]['jml']]; } // Invoice for discount $completed = Sales::find()->select(['id_sales', 'discount'])->andWhere(['status' => Sales::STATUS_RELEASED, 'id_sales' => $ids])->andWhere(['<>', 'discount', null])->asArray()->indexBy('id_sales')->all(); $invoiced = InvoiceDtl::find()->select('reff_id')->where(['type_reff' => InvoiceDtl::TYPE_SALES_DISCOUNT, 'reff_id' => array_keys($completed)])->column(); $new = array_diff(array_keys($completed), $invoiced); foreach ($new as $id) { $details[] = ['type_reff' => InvoiceDtl::TYPE_SALES_DISCOUNT, 'reff_id' => $id, 'trans_value' => -$completed['discount']]; } $data['details'] = $details; $model = $this->create($data, $model); $model = $this->post('', [], $model); return $model; }