You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DocumentController.php 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace backend\controllers;
  38. use common\helpers\CSV;
  39. use common\helpers\Price;
  40. use common\models\DeliveryNote;
  41. use common\models\Invoice;
  42. use common\models\PointSale;
  43. use common\models\Product;
  44. use common\models\Quotation;
  45. use common\models\User;
  46. use common\models\Document;
  47. use common\helpers\GlobalParam;
  48. use common\models\Order;
  49. use common\models\UserProducer;
  50. use kartik\mpdf\Pdf;
  51. use yii\base\UserException;
  52. use yii;
  53. class DocumentController extends BackendController
  54. {
  55. public function behaviors()
  56. {
  57. return [
  58. 'verbs' => [
  59. 'class' => VerbFilter::className(),
  60. 'actions' => [
  61. ],
  62. ],
  63. 'access' => [
  64. 'class' => AccessControl::className(),
  65. 'rules' => [
  66. [
  67. 'allow' => true,
  68. 'roles' => ['@'],
  69. 'matchCallback' => function ($rule, $action) {
  70. return User::hasAccessBackend();
  71. }
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionGeneratePdfValidatedDocuments()
  78. {
  79. set_time_limit(0);
  80. $validatedDocumentsArray = array_merge(
  81. Quotation::find()->where(['status' => Document::STATUS_VALID])->all(),
  82. DeliveryNote::find()->where(['status' => Document::STATUS_VALID])->all(),
  83. Invoice::find()->where(['status' => Document::STATUS_VALID])->all()
  84. );
  85. foreach($validatedDocumentsArray as $document) {
  86. if(!file_exists($document->getFilenameComplete())) {
  87. $document->generatePdf(Pdf::DEST_FILE);
  88. }
  89. }
  90. }
  91. public function actionCreate()
  92. {
  93. $class = $this->getClass();
  94. $model = new $class();
  95. $model->initTaxCalculationMethod();
  96. if ($model->load(Yii::$app->request->post())) {
  97. $model->id_producer = GlobalParam::getCurrentProducerId();
  98. if ($model->save()) {
  99. $this->processInvoiceViaDeliveryNotes($model);
  100. Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('create', $model));
  101. return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]);
  102. } else {
  103. Yii::$app->getSession()->setFlash('error', 'Un problème est survenu lors de la création du document.');
  104. }
  105. }
  106. return $this->render('/document/create', [
  107. 'title' => $this->getTitle('Ajouter'),
  108. 'typeDocument' => $this->getDocumentType(),
  109. 'model' => $model,
  110. ]);
  111. }
  112. public function processInvoiceViaDeliveryNotes($model)
  113. {
  114. if ($model->getClass() == 'Invoice') {
  115. if ($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) {
  116. foreach ($model->deliveryNotes as $key => $idDeliveryNote) {
  117. Order::updateAll([
  118. 'id_invoice' => $model->id
  119. ], [
  120. 'id_delivery_note' => $idDeliveryNote
  121. ]);
  122. }
  123. }
  124. }
  125. }
  126. /**
  127. * Modifie un modèle Produit existant.
  128. * Si la modification réussit, le navigateur est redirigé vers la page 'index'.
  129. *
  130. * @param integer $id
  131. * @return mixed
  132. */
  133. public function actionUpdate($id)
  134. {
  135. $model = $this->findModel($id);
  136. if (!$model) {
  137. throw new NotFoundHttpException('Le document n\'a pas été trouvé.');
  138. }
  139. if ($model && $model->load(Yii::$app->request->post()) && $model->save()) {
  140. Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('update', $model));
  141. }
  142. return $this->render('/document/update', [
  143. 'title' => $this->getTitle('Modifier'),
  144. 'typeDocument' => $this->getDocumentType(),
  145. 'model' => $model,
  146. ]);
  147. }
  148. public function actionDelete($id)
  149. {
  150. $model = $this->findModel($id);
  151. if ($model->isStatusValid()) {
  152. throw new UserException('Vous ne pouvez pas supprimer un document validé.');
  153. }
  154. $model->delete();
  155. if ($this->getClass() == 'DeliveryNote') {
  156. Order::updateAll([
  157. 'order.id_delivery_note' => null
  158. ], [
  159. 'order.id_delivery_note' => $id
  160. ]);
  161. }
  162. if ($this->getClass() == 'Quotation') {
  163. Order::updateAll([
  164. 'order.id_quotation' => null
  165. ], [
  166. 'order.id_quotation' => $id
  167. ]);
  168. }
  169. if ($this->getClass() == 'Invoice') {
  170. Order::updateAll([
  171. 'order.id_invoice' => null
  172. ], [
  173. 'order.id_invoice' => $id
  174. ]);
  175. }
  176. Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('delete', $model));
  177. $this->redirect([$this->getControllerUrl() . '/index']);
  178. }
  179. public function actionExportCsvEvoliz($id)
  180. {
  181. $datas = [];
  182. $document = $this->findModel($id);
  183. // données
  184. $datas[] = [
  185. 'N° facture externe *',
  186. 'Date facture *',
  187. 'Client',
  188. 'Code client *',
  189. 'Total TVA',
  190. 'Total HT',
  191. 'Total TTC',
  192. 'Total réglé',
  193. 'Etat',
  194. 'Date Etat',
  195. 'Date de création',
  196. 'Objet',
  197. 'Date d\'échéance',
  198. 'Date d\'exécution',
  199. 'Taux de pénalité',
  200. 'Frais de recouvrement',
  201. 'Taux d\'escompte',
  202. 'Conditions de règlement *',
  203. 'Mode de paiement',
  204. 'Remise globale',
  205. 'Acompte',
  206. 'Nombre de relance',
  207. 'Commentaires',
  208. 'N° facture',
  209. 'Annulé',
  210. 'Catalogue',
  211. 'Réf.',
  212. 'Désignation *',
  213. 'Qté *',
  214. 'Unité',
  215. 'PU HT *',
  216. 'Remise',
  217. 'TVA',
  218. 'Total TVA',
  219. 'Total HT',
  220. 'Classification vente',
  221. 'Code Classification vente',
  222. ];
  223. foreach($document->getProductsOrders() as $productOrderArray) {
  224. foreach($productOrderArray as $productOrder) {
  225. $price = $productOrder->getPrice() ;
  226. if($document->isInvoicePrice() && $productOrder->getInvoicePrice()) {
  227. $price = $productOrder->getInvoicePrice() ;
  228. }
  229. $typeTotal = $document->isInvoicePrice() ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL;
  230. $priceTotal = $productOrder->getPriceByTypeTotal($typeTotal) * $productOrder->quantity;
  231. $tva = Price::getVat(
  232. $priceTotal,
  233. $productOrder->taxRate->value,
  234. $document->tax_calculation_method
  235. );
  236. $datas[] = [
  237. $document->reference, // N° facture externe *
  238. date('d/m/Y', strtotime($document->date)), // Date facture *
  239. '', // Client
  240. $document->user->evoliz_code, // Code client *
  241. '', // Total TVA
  242. '', // Total HT
  243. '', // Total TTC
  244. '', // Total réglé
  245. '', // Etat
  246. '', // Date Etat
  247. '', // Date de création
  248. $document->name, // Objet
  249. '', // Date d'échéance
  250. '', // Date d'exécution
  251. '', // Taux de pénalité
  252. '', // Frais de recouvrement
  253. '', // Taux d\'escompte
  254. 'A réception', // Conditions de règlement *
  255. '', // Mode de paiement
  256. '', // Remise globale
  257. '', // Acompte
  258. '', // Nombre de relance
  259. '', // Commentaires
  260. '', // N° facture
  261. '', // Annulé
  262. 'Non', // Catalogue
  263. '', // Réf.
  264. $productOrder->product->name, // Désignation *
  265. $productOrder->quantity, // Qté *
  266. '', // Product::strUnit($productOrder->unit, 'wording'), // Unité
  267. $price, // PU HT *
  268. '', // Remise
  269. $productOrder->taxRate->value * 100, // TVA
  270. $tva, // Total TVA
  271. $priceTotal, // Total HT
  272. '', // Classification vente
  273. '01', // Code Classification vente
  274. ];
  275. }
  276. }
  277. // nom fichier
  278. $reference = $document->id;
  279. if($document->reference && strlen($document->reference)) {
  280. $reference = $document->reference;
  281. }
  282. // status
  283. $status = '';
  284. if($document->isStatusDraft()) {
  285. $status = 'brouillon_';
  286. }
  287. CSV::downloadSendHeaders(strtolower($this->getDocumentType()).'_' . $status . $reference . '.csv');
  288. echo CSV::array2csv($datas);
  289. die();
  290. }
  291. public function actionDownload($id)
  292. {
  293. $document = $this->findModel($id);
  294. return $document->downloadPdf();
  295. }
  296. public function actionRegenerate($id)
  297. {
  298. $document = $this->findModel($id);
  299. $document->downloadPdf(true);
  300. Yii::$app->getSession()->setFlash('success', 'Le document PDF a bien été regénéré.');
  301. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  302. }
  303. public function actionSend($id, $backUpdateForm = false)
  304. {
  305. $document = $this->findModel($id);
  306. if ($document->send()) {
  307. $document->is_sent = true;
  308. $document->save();
  309. Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('send', $document));
  310. } else {
  311. Yii::$app->getSession()->setFlash('danger', $this->getFlashMessage('send', $document));
  312. }
  313. if($backUpdateForm) {
  314. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  315. }
  316. else {
  317. return $this->redirect([$this->getControllerUrl() . '/index']);
  318. }
  319. }
  320. public function actionAjaxUserInfos($typeAction, $idUser, $classDocument, $idDocument = false)
  321. {
  322. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  323. if ($idUser > 0) {
  324. $user = User::searchOne([
  325. 'id' => $idUser
  326. ]);
  327. if ($user) {
  328. $document = null;
  329. if (Document::isValidClass($classDocument)) {
  330. $document = $classDocument::searchOne([
  331. 'id' => $idDocument,
  332. 'id_user' => $idUser
  333. ]);
  334. }
  335. if ($document && $document->id_user == $user->id) {
  336. $address = $document->address;
  337. } else {
  338. $address = $user->getFullAddress();
  339. }
  340. $json = [
  341. 'return' => 'success',
  342. 'address' => $address
  343. ];
  344. if ($classDocument == 'Invoice') {
  345. $options = [
  346. 'orderby' => 'distribution.date ASC',
  347. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  348. ];
  349. $deliveryNotesCreateArray = DeliveryNote::searchAll([
  350. 'id_user' => $user->id,
  351. 'status' => Document::STATUS_VALID
  352. ], $options);
  353. $deliveryNotesUpdateArray = DeliveryNote::searchAll([
  354. 'id_user' => $user->id,
  355. 'status' => Document::STATUS_VALID,
  356. 'order.id_invoice' => $idDocument
  357. ], $options);
  358. $json['delivery_note_create_array'] = $this->initDeliveryNoteArray('create', $deliveryNotesCreateArray);
  359. $json['delivery_note_update_array'] = $this->initDeliveryNoteArray('update', $deliveryNotesUpdateArray);
  360. }
  361. return $json;
  362. }
  363. }
  364. return ['return' => 'error'];
  365. }
  366. public function initDeliveryNoteArray($type, $deliveryNoteArrayResults)
  367. {
  368. $deliveryNoteArray = [];
  369. $isCreate = false;
  370. if($type == 'create') {
  371. $isCreate = true;
  372. }
  373. if($deliveryNoteArrayResults) {
  374. foreach ($deliveryNoteArrayResults as $deliveryNote) {
  375. $deliveryNoteData = $this->addDeliveryNoteToArray($deliveryNote, $isCreate);
  376. if($deliveryNoteData) {
  377. $deliveryNoteArray[] = $deliveryNoteData;
  378. }
  379. }
  380. }
  381. return $deliveryNoteArray;
  382. }
  383. public function addDeliveryNoteToArray($deliveryNote, $isCreate = true)
  384. {
  385. $deliveryNoteData = array_merge(
  386. $deliveryNote->getAttributes(),
  387. [
  388. 'url' => Yii::$app->urlManager->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
  389. 'total' => $deliveryNote->getAmountWithTax(Order::INVOICE_AMOUNT_TOTAL)
  390. ]
  391. );
  392. if (($isCreate && !$deliveryNote->isInvoiced()) || !$isCreate) {
  393. return $deliveryNoteData;
  394. }
  395. return false;
  396. }
  397. public function actionValidate($id, $backUpdateForm = false)
  398. {
  399. $classDocument = $this->getClass();
  400. if ($id > 0 && Document::isValidClass($classDocument)) {
  401. $document = $classDocument::searchOne([
  402. 'id' => $id
  403. ]);
  404. if ($document) {
  405. $document->changeStatus(Document::STATUS_VALID);
  406. $document->save();
  407. // génération PDF
  408. $document->generatePdf(Pdf::DEST_FILE);
  409. Yii::$app->getSession()->setFlash('success', $this->getFlashMessage('validate', $document));
  410. if($backUpdateForm) {
  411. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  412. }
  413. else {
  414. return $this->redirect([$this->getControllerUrl() . '/index']);
  415. }
  416. }
  417. }
  418. Yii::$app->getSession()->setFlash('danger', 'Une erreur est survenue lors de la validation du document.');
  419. return $this->redirect([$this->getControllerUrl() . '/index']);
  420. }
  421. public function actionAjaxValidateDocument($idDocument, $classDocument)
  422. {
  423. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  424. if ($idDocument > 0 && Document::isValidClass($classDocument)) {
  425. $document = $classDocument::searchOne([
  426. 'id' => $idDocument
  427. ]);
  428. if ($document) {
  429. $document->changeStatus(Document::STATUS_VALID);
  430. $document->save();
  431. return [
  432. 'return' => 'success',
  433. 'alert' => [
  434. 'type' => 'success',
  435. 'message' => 'Document validé'
  436. ]
  437. ];
  438. }
  439. }
  440. return [
  441. 'return' => 'error',
  442. 'alert' => [
  443. 'type' => 'danger',
  444. 'message' => 'Une erreur est survenue lors de la validation du document.'
  445. ]
  446. ];
  447. }
  448. public function actionAjaxInit($idDocument, $classDocument)
  449. {
  450. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  451. if ($idDocument > 0 && Document::isValidClass($classDocument)) {
  452. $document = $classDocument::searchOne([
  453. 'id' => $idDocument
  454. ]);
  455. if ($document) {
  456. $productsArray = Product::searchAll([], [
  457. 'orderby' => 'product.order ASC'
  458. ]);
  459. $ordersArray = [];
  460. foreach ($document->orders as $order) {
  461. $order->init();
  462. $productsOrderArray = [];
  463. foreach ($order->productOrder as $productOrder) {
  464. $productsOrderArray[$productOrder->id] = array_merge($productOrder->getAttributes(), [
  465. 'url_order' => Yii::$app->urlManager->createUrl(['distribution/index', 'idOrderUpdate' => $productOrder->id_order])
  466. ]);
  467. }
  468. $ordersArray[$order->id] = array_merge(
  469. $order->getAttributes(),
  470. [
  471. 'username' => $order->getUsername(),
  472. 'distribution_date' => isset($order->distribution) ? date(
  473. 'd/m/Y',
  474. strtotime(
  475. $order->distribution->date
  476. )
  477. ) : null,
  478. 'point_sale_name' => isset($order->pointSale) ? $order->pointSale->name : null,
  479. 'productOrder' => $productsOrderArray,
  480. ]
  481. );
  482. }
  483. $userProducer = UserProducer::searchOne([
  484. 'id_user' => $document->user->id,
  485. 'id_producer' => GlobalParam::getCurrentProducerId()
  486. ]);
  487. $pointSale = PointSale::searchOne([
  488. 'id_user' => $document->user->id
  489. ]);
  490. $productsArray = yii\helpers\ArrayHelper::map(
  491. $productsArray,
  492. 'order',
  493. function ($product) use ($document, $userProducer, $pointSale) {
  494. return array_merge($product->getAttributes(), [
  495. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  496. 'prices' => $product->getPriceArray($userProducer->user, $pointSale),
  497. 'wording_unit' => $product->wording_unit,
  498. 'tax_rate' => $product->taxRate->value
  499. ]);
  500. }
  501. );
  502. return [
  503. 'return' => 'success',
  504. 'tax_rate_producer' => GlobalParam::getCurrentProducer()->taxRate->value,
  505. 'document' => array_merge($document->getAttributes(), [
  506. 'html_label' => $document->getHtmlLabel(),
  507. 'class' => $document->getClass()
  508. ]),
  509. 'id_user' => $document->user->id,
  510. 'products' => $productsArray,
  511. 'orders' => $ordersArray,
  512. 'total' => ($document->getClass() == 'Invoice' || $document->getClass(
  513. ) == 'DeliveryNote') ? $document->getAmount(
  514. Order::INVOICE_AMOUNT_TOTAL
  515. ) : $document->getAmount(Order::AMOUNT_TOTAL),
  516. 'total_with_tax' => ($document->getClass() == 'Invoice' || $document->getClass(
  517. ) == 'DeliveryNote') ? $document->getAmountWithTax(
  518. Order::INVOICE_AMOUNT_TOTAL
  519. ) : $document->getAmountWithTax(Order::AMOUNT_TOTAL),
  520. 'invoice_url' => ($document->getClass() == 'DeliveryNote' && $document->getInvoice()) ? Yii::$app->urlManager->createUrl(['invoice/update', 'id' => $document->getInvoice()->id]) : null
  521. ];
  522. }
  523. }
  524. return ['return' => 'error'];
  525. }
  526. public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price)
  527. {
  528. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  529. if (Document::isValidClass($classDocument)) {
  530. $document = $classDocument::searchOne([
  531. 'id' => $idDocument
  532. ]);
  533. $product = Product::searchOne([
  534. 'id' => $idProduct
  535. ]);
  536. if ($document && $product) {
  537. if (count($document->orders) == 0) {
  538. $order = new Order;
  539. $order->id_user = $document->id_user;
  540. $order->id_point_sale = null;
  541. $order->id_distribution = null;
  542. $order->status = 'tmp-order';
  543. $order->origin = Order::ORIGIN_ADMIN;
  544. $order->date = date('Y-m-d H:i:s');
  545. $fieldIdDocument = 'id_' . $classDocument::tableName();
  546. $order->$fieldIdDocument = $document->id;
  547. $order->save();
  548. } else {
  549. $order = $document->orders[0];
  550. }
  551. if ($order) {
  552. $productOrder = new ProductOrder;
  553. $productOrder->id_order = $order->id;
  554. $productOrder->id_product = $idProduct;
  555. $quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
  556. $productOrder->quantity = $quantity;
  557. $productOrder->price = (float)$price;
  558. $productOrder->unit = $product->unit;
  559. $productOrder->step = $product->step;
  560. $productOrder->id_tax_rate = $product->taxRate->id;
  561. $productOrder->save();
  562. return [
  563. 'return' => 'success',
  564. 'alert' => [
  565. 'type' => 'success',
  566. 'message' => 'Produit ajouté'
  567. ]
  568. ];
  569. }
  570. }
  571. }
  572. return [
  573. 'return' => 'error',
  574. 'alert' => [
  575. 'type' => 'danger',
  576. 'message' => 'Une erreur est survenue lors de la suppression du produit.'
  577. ]
  578. ];
  579. }
  580. public function actionAjaxDeleteProductOrder($idProductOrder)
  581. {
  582. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  583. $productOrder = ProductOrder::searchOne([
  584. 'id' => $idProductOrder
  585. ]);
  586. if ($productOrder) {
  587. $productOrder->delete();
  588. return [
  589. 'return' => 'success',
  590. 'alert' => [
  591. 'type' => 'danger',
  592. 'message' => 'Produit supprimé'
  593. ]
  594. ];
  595. }
  596. return [
  597. 'return' => 'error',
  598. 'alert' => [
  599. 'type' => 'danger',
  600. 'message' => 'Une erreur est survenue lors de la suppression du produit.'
  601. ]
  602. ];
  603. }
  604. public function getClass()
  605. {
  606. $class = get_class($this);
  607. $class = str_replace('Controller', '', $class);
  608. $class = str_replace('backend\controllers\\', '', $class);
  609. return $class;
  610. }
  611. public function getDocumentType()
  612. {
  613. $class = $this->getClass();
  614. if ($class == 'Invoice') {
  615. $documentType = 'Facture';
  616. } elseif ($class == 'DeliveryNote') {
  617. $documentType = 'Bon de livraison';
  618. } elseif ($class == 'Quotation') {
  619. $documentType = 'Devis';
  620. }
  621. if (isset($documentType)) {
  622. return $documentType;
  623. }
  624. return '';
  625. }
  626. public function getFlashMessage($type = 'create', $model)
  627. {
  628. $class = $this->getClass();
  629. $message = $this->getDocumentType();
  630. $message .= ' <strong>' . Html::encode($model->name) . '</strong> ';
  631. if ($type == 'create') {
  632. $message .= 'ajouté';
  633. } elseif ($type == 'update') {
  634. $message .= 'modifié';
  635. } elseif ($type == 'delete') {
  636. $message .= 'supprimé';
  637. } elseif ($type == 'validate') {
  638. $message .= 'validé';
  639. } elseif ($type == 'send') {
  640. $message .= 'envoyé';
  641. }
  642. if ($class == 'Invoice') {
  643. $message .= 'e';
  644. }
  645. return $message;
  646. }
  647. protected function getTitle($prepend)
  648. {
  649. $class = $this->getClass();
  650. switch ($class) {
  651. case 'Invoice' :
  652. $title = $prepend . ' une facture';
  653. break;
  654. case 'DeliveryNote' :
  655. $title = $prepend . ' un bon de livraison';
  656. break;
  657. case 'Quotation' :
  658. $title = $prepend . ' un devis';
  659. break;
  660. }
  661. return $title;
  662. }
  663. public function getControllerUrl()
  664. {
  665. $path = strtolower($this->getClass());
  666. $path = str_replace('deliverynote', 'delivery-note', $path);
  667. return $path;
  668. }
  669. /**
  670. * Recherche un Document en fonction de son ID.
  671. *
  672. * @param integer $id
  673. * @return Document
  674. * @throws NotFoundHttpException si le modèle n'est pas trouvé
  675. */
  676. protected function findModel($id)
  677. {
  678. $class = $this->getClass();
  679. $model = $class::searchOne([
  680. 'id' => $id
  681. ], [
  682. 'orderby' => 'teshtygjhtyt'
  683. ]);
  684. if ($model) {
  685. return $model;
  686. } else {
  687. throw new NotFoundHttpException('The requested page does not exist.');
  688. }
  689. }
  690. }