|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554 |
- <?php
-
-
-
- namespace backend\controllers;
-
- use common\models\DeliveryNote;
- use common\models\Product;
- use common\models\User;
- use common\models\Document;
- use common\helpers\GlobalParam;
- use common\models\Order;
- use yii\base\UserException;
- use yii;
-
- class DocumentController extends BackendController
- {
- public function behaviors()
- {
- return [
- 'verbs' => [
- 'class' => VerbFilter::className(),
- 'actions' => [
- ],
- ],
- 'access' => [
- 'class' => AccessControl::className(),
- 'rules' => [
- [
- 'allow' => true,
- 'roles' => ['@'],
- 'matchCallback' => function ($rule, $action) {
- return User::hasAccessBackend();
- }
- ]
- ],
- ],
- ];
- }
-
- public function actionCreate()
- {
- $class = $this->getClass();
- $model = new $class();
-
- if ($model->load(Yii::$app->request->post())) {
-
- $model->id_producer = GlobalParam::getCurrentProducerId();
-
- if ($model->save()) {
-
- $this->processInvoiceViaDeliveryNotes($model) ;
-
- Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('create', $model));
- return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]);
- } else {
- Yii::$app->getSession()->setFlash('error', 'Un problème est survenu lors de la création du document.');
- }
- }
-
- return $this->render('/document/create', [
- 'title' => $this->getTitle('Ajouter'),
- 'typeDocument' => $this->getDocumentType(),
- 'model' => $model,
- ]);
- }
-
- public function processInvoiceViaDeliveryNotes($model)
- {
- if($model->getClass() == 'Invoice') {
- if($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) {
- foreach($model->deliveryNotes as $key => $idDeliveryNote) {
- Order::updateAll([
- 'id_invoice' => $model->id
- ], [
- 'id_delivery_note' => $idDeliveryNote
- ]) ;
- }
- }
- }
- }
-
-
-
- public function actionUpdate($id)
- {
- $model = $this->findModel($id);
-
- if(!$model) {
- throw new NotFoundHttpException('Le document n\'a pas été trouvé.');
- }
-
- if ($model->isStatusValid()) {
- return $this->redirect(['download', 'id' => $id]) ;
- }
-
- if ($model && $model->load(Yii::$app->request->post()) && $model->save()) {
- Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('update', $model));
- }
-
- return $this->render('/document/update', [
- 'title' => $this->getTitle('Modifier'),
- 'typeDocument' => $this->getDocumentType(),
- 'model' => $model,
- ]);
- }
-
- public function actionDelete($id)
- {
- $model = $this->findModel($id);
-
- if ($model->isStatusValid()) {
- throw new UserException('Vous ne pouvez pas supprimer un document validé.');
- }
-
- $model->delete();
-
- Order::updateAll([
- 'order.id_delivery_note' => null
- ], [
- 'order.id_delivery_note' => $id
- ]);
-
- Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('delete', $model));
- $this->redirect([$this->getControllerUrl().'/index']);
- }
-
- public function actionDownload($id)
- {
- $document = $this->findModel($id);
- return $document->generatePdf(Pdf::DEST_BROWSER) ;
- }
-
- public function actionSend($id)
- {
- $document = $this->findModel($id) ;
- if($document->send()) {
- Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('send', $document));
- }
- else {
- Yii::$app->getSession()->setFlash('danger', $this->getFlashMessage('send', $document));
- }
- $this->redirect([$this->getControllerUrl().'/index']);
- }
-
- public function actionAjaxUserInfos($typeAction, $idUser, $classDocument, $idDocument = false)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- if ($idUser > 0) {
- $user = User::searchOne([
- 'id' => $idUser
- ]);
-
- if ($user) {
-
- $document = null ;
- if(Document::isValidClass($classDocument)) {
- $document = $classDocument::searchOne([
- 'id' => $idDocument,
- 'id_user' => $idUser
- ]) ;
- }
-
- if($document && $document->id_user == $user->id) {
- $address = $document->address ;
- }
- else {
- $address = $user->getFullAddress() ;
- }
-
- $json = [
- 'return' => 'success',
- 'address' => $address
- ];
-
- if($classDocument == 'Invoice') {
- if($typeAction == 'create') {
- $deliveryNotesArray = DeliveryNote::searchAll([
- 'id_user' => $user->id,
- 'status' => Document::STATUS_VALID
- ]) ;
- }
- elseif($typeAction == 'update' && $idDocument > 0) {
- $deliveryNotesArray = DeliveryNote::searchAll([
- 'id_user' => $user->id,
- 'status' => Document::STATUS_VALID,
- 'order.id_invoice' => $idDocument
- ]) ;
- }
-
- if(isset($deliveryNotesArray)) {
- $json['delivery_notes'] = [] ;
-
- foreach($deliveryNotesArray as $deliveryNote) {
- $json['delivery_notes'][] = array_merge(
- $deliveryNote->getAttributes(),
- [
- 'total' => $deliveryNote->getAmountWithTax()
- ]
- ) ;
- }
- }
- }
-
- return $json ;
- }
- }
-
- return ['return' => 'error'];
- }
-
- public function actionValidate($id)
- {
- $classDocument = $this->getClass();
-
- if ($id > 0 && Document::isValidClass($classDocument)) {
- $document = $classDocument::searchOne([
- 'id' => $id
- ]);
-
- if ($document) {
- $document->changeStatus(Document::STATUS_VALID);
- $document->save();
- Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('validate', $document));
- return $this->redirect([$this->getControllerUrl().'/index']);
- }
- }
-
- Yii::$app->getSession()->setFlash('danger', 'Une erreur est survenue lors de la validation du document.');
- return $this->redirect([$this->getControllerUrl().'/index']);
- }
-
- public function actionAjaxValidateDocument($idDocument, $classDocument)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- if ($idDocument > 0 && Document::isValidClass($classDocument)) {
- $document = $classDocument::searchOne([
- 'id' => $idDocument
- ]);
-
- if ($document) {
- $document->changeStatus(Document::STATUS_VALID);
- $document->save();
- return [
- 'return' => 'success',
- 'alert' => [
- 'type' => 'success',
- 'message' => 'Document validé'
- ]
- ];
- }
- }
-
- return [
- 'return' => 'error',
- 'alert' => [
- 'type' => 'danger',
- 'message' => 'Une erreur est survenue lors de la validation du document.'
- ]
- ];
- }
-
- public function actionAjaxInit($idDocument, $classDocument)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- if ($idDocument > 0 && Document::isValidClass($classDocument)) {
-
- $document = $classDocument::searchOne([
- 'id' => $idDocument
- ]);
-
- if ($document) {
-
- $productsArray = Product::searchAll();
-
- $ordersArray = [];
- foreach ($document->orders as $order) {
- $order->init();
- $productsOrderArray = [];
- foreach ($order->productOrder as $productOrder) {
- $productsOrderArray[$productOrder->id] = $productOrder->getAttributes();
- }
- $ordersArray[$order->id] = array_merge(
- $order->getAttributes(),
- [
- 'username' => $order->getUsername(),
- 'distribution_date' => isset($order->distribution) ? date('d/m/Y', strtotime($order->distribution->date)) : null,
- 'point_sale_name' => isset($order->pointSale) ? $order->pointSale->name : null,
- 'productOrder' => $productsOrderArray,
- ]
- );
- }
-
- return [
- 'return' => 'success',
- 'tax_rate_producer' => GlobalParam::getCurrentProducer()->taxRate->value,
- 'document' => array_merge($document->getAttributes(), [
- 'html_label' => $document->getHtmlLabel(),
- 'class' => $document->getClass()
- ]),
- 'id_user' => $document->user->id,
- 'products' => ArrayHelper::map($productsArray, 'id', function ($product) {
- return array_merge($product->getAttributes(), [
- 'price_with_tax' => $product->price_with_tax,
- 'wording_unit' => $product->wording_unit,
- 'tax_rate' => $product->taxRate->value
- ]);
- }),
- 'orders' => $ordersArray,
- 'total' => $document->getAmount(Order::AMOUNT_TOTAL),
- 'total_with_tax' => $document->getAmountWithTax(Order::AMOUNT_TOTAL),
- ];
- }
- }
-
- return ['return' => 'error'];
- }
-
- public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price)
- {
-
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- if (Document::isValidClass($classDocument)) {
- $document = $classDocument::searchOne([
- 'id' => $idDocument
- ]);
- $product = Product::searchOne([
- 'id' => $idProduct
- ]);
-
- if ($document && $product) {
- if (count($document->orders) == 0) {
- $order = new Order;
- $order->id_user = $document->id_user;
- $order->id_point_sale = null;
- $order->id_distribution = null;
- $order->status = 'tmp-order' ;
- $order->origin = Order::ORIGIN_ADMIN;
- $order->date = date('Y-m-d H:i:s');
- $fieldIdDocument = 'id_' . $classDocument::tableName();
- $order->$fieldIdDocument = $document->id;
- $order->save();
- } else {
- $order = $document->orders[0];
- }
-
- if ($order) {
-
- $productOrder = new ProductOrder;
- $productOrder->id_order = $order->id;
- $productOrder->id_product = $idProduct;
- $quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
- $productOrder->quantity = $quantity;
- $productOrder->price = (float)$price;
- $productOrder->unit = $product->unit;
- $productOrder->step = $product->step;
- $productOrder->id_tax_rate = $product->taxRate->id ;
- $productOrder->save();
-
- return [
- 'return' => 'success',
- 'alert' => [
- 'type' => 'success',
- 'message' => 'Produit ajouté'
- ]
- ];
- }
- }
-
- }
-
- return [
- 'return' => 'error',
- 'alert' => [
- 'type' => 'danger',
- 'message' => 'Une erreur est survenue lors de la suppression du produit.'
- ]
- ];
- }
-
- public function actionAjaxDeleteProductOrder($idProductOrder)
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
-
- $productOrder = ProductOrder::searchOne([
- 'id' => $idProductOrder
- ]);
-
- if ($productOrder) {
- $productOrder->delete();
-
- return [
- 'return' => 'success',
- 'alert' => [
- 'type' => 'danger',
- 'message' => 'Produit supprimé'
- ]
- ];
- }
-
- return [
- 'return' => 'error',
- 'alert' => [
- 'type' => 'danger',
- 'message' => 'Une erreur est survenue lors de la suppression du produit.'
- ]
- ];
- }
-
- public function getClass()
- {
- $class = get_class($this);
- $class = str_replace('Controller', '', $class);
- $class = str_replace('backend\controllers\\', '', $class);
- return $class;
- }
-
- public function getDocumentType()
- {
- $class = $this->getClass();
-
- if ($class == 'Invoice') {
- $documentType = 'Facture';
- } elseif ($class == 'DeliveryNote') {
- $documentType = 'Bon de livraison';
- } elseif ($class == 'Quotation') {
- $documentType = 'Devis';
- }
-
- if (isset($documentType)) {
- return $documentType;
- }
-
- return '';
- }
-
- public function getFlashMessage($type = 'create', $model)
- {
- $class = $this->getClass();
-
- $message = $this->getDocumentType();
- $message .= ' <strong>' . Html::encode($model->name) . '</strong> ';
-
- if ($type == 'create') {
- $message .= 'ajouté';
- } elseif ($type == 'update') {
- $message .= 'modifié';
- } elseif ($type == 'delete') {
- $message .= 'supprimé';
- } elseif ($type == 'validate') {
- $message .= 'validé';
- } elseif ($type == 'send') {
- $message .= 'envoyé';
- }
-
- if ($class == 'Invoice') {
- $message .= 'e';
- }
-
- return $message;
- }
-
- protected function getTitle($prepend)
- {
- $class = $this->getClass();
-
- switch ($class) {
- case 'Invoice' :
- $title = $prepend . ' une facture';
- break;
- case 'DeliveryNote' :
- $title = $prepend . ' un bon de livraison';
- break;
- case 'Quotation' :
- $title = $prepend . ' un devis';
- break;
- }
-
- return $title;
- }
-
- public function getControllerUrl()
- {
- $path = strtolower($this->getClass());
- $path = str_replace('deliverynote', 'delivery-note', $path);
- return $path;
- }
-
-
-
- protected function findModel($id)
- {
- $class = $this->getClass();
-
- $model = $class::searchOne([
- 'id' => $id
- ]);
-
- if ($model) {
- return $model;
- } else {
- throw new NotFoundHttpException('The requested page does not exist.');
- }
- }
-
- }
|