/** * @inheritdoc */ public function rules() { return [[['product_id', 'uom_id', 'qty', 'price'], 'required'], [['sales_id', 'product_id', 'uom_id'], 'integer'], [['cogs'], 'default', 'value' => function () { $cogs = Cogs::findOne($this->product_id); return $cogs ? $cogs->cogs : null; }], [['cogs'], 'required'], [['qty', 'price', 'cogs', 'discount', 'total_release'], 'number']]; }
/** * Finds the Cogs model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Cogs the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Cogs::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
protected function updateCogs($params) { $cogs = Cogs::findOne(['product_id' => $params['id']]); if (!$cogs) { $cogs = new Cogs(['product_id' => $params['id'], 'cogs' => 0.0]); } $current_stock = ProductStock::find()->where(['product_id' => $params['id']])->sum('qty'); if ($current_stock != 0) { $cogs->cogs += $params['qty'] * ($params['cogs'] - $cogs->cogs) / $current_stock; } else { $cogs->cogs = 0; } return $cogs->save(false); }