您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

769 行
28KB

  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\Ajax;
  39. use common\helpers\CSV;
  40. use common\helpers\GlobalParam;
  41. use common\helpers\Price;
  42. use common\logic\Document\DeliveryNote\Model\DeliveryNote;
  43. use common\logic\Document\Document\Model\Document;
  44. use common\logic\Document\Invoice\Model\Invoice;
  45. use common\logic\Document\Quotation\Model\Quotation;
  46. use common\logic\Order\Order\Model\Order;
  47. use common\logic\Order\ProductOrder\Model\ProductOrder;
  48. use common\logic\Product\Product\Model\Product;
  49. use kartik\mpdf\Pdf;
  50. use yii\base\UserException;
  51. use yii;
  52. use yii\filters\VerbFilter;
  53. use yii\filters\AccessControl;
  54. use yii\web\NotFoundHttpException;
  55. use yii\helpers\Html;
  56. class DocumentController extends BackendController
  57. {
  58. public function behaviors()
  59. {
  60. return [
  61. 'verbs' => [
  62. 'class' => VerbFilter::class,
  63. 'actions' => [
  64. ],
  65. ],
  66. 'access' => [
  67. 'class' => AccessControl::class,
  68. 'rules' => [
  69. [
  70. 'allow' => true,
  71. 'roles' => ['@'],
  72. 'matchCallback' => function ($rule, $action) {
  73. return $this->getUserManager()->hasAccessBackend();
  74. }
  75. ]
  76. ],
  77. ],
  78. ];
  79. }
  80. public function actionGeneratePdfValidatedDocuments()
  81. {
  82. set_time_limit(0);
  83. $validatedDocumentsArray = array_merge(
  84. Quotation::find()->where(['status' => Document::STATUS_VALID])->all(),
  85. DeliveryNote::find()->where(['status' => Document::STATUS_VALID])->all(),
  86. Invoice::find()->where(['status' => Document::STATUS_VALID])->all()
  87. );
  88. foreach ($validatedDocumentsArray as $document) {
  89. if (!file_exists($document->getFilenameComplete())) {
  90. $document->generatePdf(Pdf::DEST_FILE);
  91. }
  92. }
  93. }
  94. public function actionCreate()
  95. {
  96. $documentManager = $this->getDocumentManager();
  97. $class = $this->getClass();
  98. $class = 'common\\logic\\Document\\'.$class.'\\Model\\'.$class;
  99. $model = new $class();
  100. $documentManager->initTaxCalculationMethod($model);
  101. if ($model->load(\Yii::$app->request->post())) {
  102. $model->id_producer = GlobalParam::getCurrentProducerId();
  103. if ($model->save()) {
  104. $this->processInvoiceViaDeliveryNotes($model);
  105. $this->processInvoiceViaOrders($model);
  106. $this->setFlash('success', $this->getFlashMessage('create', $model));
  107. return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]);
  108. } else {
  109. $this->setFlash('error', 'Un problème est survenu lors de la création du document.');
  110. }
  111. }
  112. return $this->render('/document/create', [
  113. 'title' => $this->getTitle('Ajouter'),
  114. 'typeDocument' => $this->getDocumentType(),
  115. 'model' => $model,
  116. ]);
  117. }
  118. public function processInvoiceViaDeliveryNotes($model)
  119. {
  120. $orderManager = $this->getOrderManager();
  121. $documentManager = $this->getDocumentManager();
  122. $deliveryNoteManager = $this->getDeliveryNoteManager();
  123. if ($documentManager->getClass($model) == 'Invoice') {
  124. if ($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) {
  125. foreach ($model->deliveryNotes as $key => $idDeliveryNote) {
  126. $deliveryNote = $deliveryNoteManager->findOneDeliveryNoteById($idDeliveryNote);
  127. $orderManager->assignAllOrdersInvoiceByDeliveryNote($model, $deliveryNote);
  128. }
  129. }
  130. }
  131. }
  132. public function processInvoiceViaOrders($model)
  133. {
  134. $orderManager = $this->getOrderManager();
  135. $documentManager = $this->getDocumentManager();
  136. if ($documentManager->getClass($model) == 'Invoice') {
  137. if ($model->ordersOnCreate && is_array($model->ordersOnCreate) && count($model->ordersOnCreate)) {
  138. foreach ($model->ordersOnCreate as $key => $idOrder) {
  139. $order = $orderManager->findOneOrderById($idOrder);
  140. $orderManager->updateOrderInvoice($order, $model);
  141. }
  142. }
  143. }
  144. }
  145. public function actionUpdate($id)
  146. {
  147. $model = $this->findModel($id);
  148. if (!$model) {
  149. throw new yii\web\NotFoundHttpException('Le document n\'a pas été trouvé.');
  150. }
  151. if ($model && $model->load(\Yii::$app->request->post()) && $model->save()) {
  152. $this->setFlash('success', $this->getFlashMessage('update', $model));
  153. }
  154. return $this->render('/document/update', [
  155. 'title' => $this->getTitle('Modifier'),
  156. 'typeDocument' => $this->getDocumentType(),
  157. 'model' => $model,
  158. ]);
  159. }
  160. public function actionDelete($id)
  161. {
  162. $documentManager = $this->getDocumentManager();
  163. $model = $this->findModel($id);
  164. if ($documentManager->isStatusValid($model)) {
  165. throw new UserException('Vous ne pouvez pas supprimer un document validé.');
  166. }
  167. $documentManager->delete($model);
  168. if ($this->getClass() == 'DeliveryNote') {
  169. Order::updateAll([
  170. 'order.id_delivery_note' => null
  171. ], [
  172. 'order.id_delivery_note' => $id
  173. ]);
  174. }
  175. if ($this->getClass() == 'Quotation') {
  176. Order::updateAll([
  177. 'order.id_quotation' => null
  178. ], [
  179. 'order.id_quotation' => $id
  180. ]);
  181. }
  182. if ($this->getClass() == 'Invoice') {
  183. Order::updateAll([
  184. 'order.id_invoice' => null
  185. ], [
  186. 'order.id_invoice' => $id
  187. ]);
  188. }
  189. $this->setFlash('success', $this->getFlashMessage('delete', $model));
  190. $this->redirect([$this->getControllerUrl() . '/index']);
  191. }
  192. public function actionExportCsvEvoliz(int $id)
  193. {
  194. $documentManager = $this->getDocumentManager();
  195. $productOrderManager = $this->getProductOrderManager();
  196. $datas = [];
  197. $document = $this->findModel($id);
  198. // données
  199. $datas[] = [
  200. 'N° facture externe *',
  201. 'Date facture *',
  202. 'Client',
  203. 'Code client *',
  204. 'Total TVA',
  205. 'Total HT',
  206. 'Total TTC',
  207. 'Total réglé',
  208. 'Etat',
  209. 'Date Etat',
  210. 'Date de création',
  211. 'Objet',
  212. 'Date d\'échéance',
  213. 'Date d\'exécution',
  214. 'Taux de pénalité',
  215. 'Frais de recouvrement',
  216. 'Taux d\'escompte',
  217. 'Conditions de règlement *',
  218. 'Mode de paiement',
  219. 'Remise globale',
  220. 'Acompte',
  221. 'Nombre de relance',
  222. 'Commentaires',
  223. 'N° facture',
  224. 'Annulé',
  225. 'Catalogue',
  226. 'Réf.',
  227. 'Désignation *',
  228. 'Qté *',
  229. 'Unité',
  230. 'PU HT *',
  231. 'Remise',
  232. 'TVA',
  233. 'Total TVA',
  234. 'Total HT',
  235. 'Classification vente',
  236. 'Code Classification vente',
  237. ];
  238. foreach ($documentManager->getProductsOrders($document) as $productOrderArray) {
  239. foreach ($productOrderArray as $productOrder) {
  240. $price = $productOrder->getPrice();
  241. if ($documentManager->isInvoicePrice($document) && $productOrder->getInvoicePrice()) {
  242. $price = $productOrder->getInvoicePrice();
  243. }
  244. $typeTotal = $documentManager->isInvoicePrice($document) ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL;
  245. $priceTotal = $productOrderManager->getPriceByTypeTotal($productOrder, $typeTotal) * $productOrder->quantity;
  246. $tva = Price::getVat(
  247. $priceTotal,
  248. $productOrder->taxRate->value,
  249. $document->tax_calculation_method
  250. );
  251. $datas[] = [
  252. $document->reference, // N° facture externe *
  253. date('d/m/Y', strtotime($document->date)), // Date facture *
  254. '', // Client
  255. $document->user->evoliz_code, // Code client *
  256. '', // Total TVA
  257. '', // Total HT
  258. '', // Total TTC
  259. '', // Total réglé
  260. '', // Etat
  261. '', // Date Etat
  262. '', // Date de création
  263. $document->name, // Objet
  264. '', // Date d'échéance
  265. '', // Date d'exécution
  266. '', // Taux de pénalité
  267. '', // Frais de recouvrement
  268. '', // Taux d\'escompte
  269. 'A réception', // Conditions de règlement *
  270. '', // Mode de paiement
  271. '', // Remise globale
  272. '', // Acompte
  273. '', // Nombre de relance
  274. '', // Commentaires
  275. '', // N° facture
  276. '', // Annulé
  277. 'Non', // Catalogue
  278. '', // Réf.
  279. $productOrder->product->name, // Désignation *
  280. $productOrder->quantity, // Qté *
  281. '', // Product::strUnit($productOrder->unit, 'wording'), // Unité
  282. $price, // PU HT *
  283. '', // Remise
  284. $productOrder->taxRate->value * 100, // TVA
  285. $tva, // Total TVA
  286. $priceTotal, // Total HT
  287. '', // Classification vente
  288. '01', // Code Classification vente
  289. ];
  290. }
  291. }
  292. // nom fichier
  293. $reference = $document->id;
  294. if ($document->reference && strlen($document->reference)) {
  295. $reference = $document->reference;
  296. }
  297. // status
  298. $status = '';
  299. if ($documentManager->isStatusDraft($document)) {
  300. $status = 'brouillon_';
  301. }
  302. CSV::downloadSendHeaders(strtolower($this->getDocumentType()) . '_' . $status . $reference . '.csv');
  303. echo CSV::array2csv($datas);
  304. die();
  305. }
  306. public function actionDownload($id)
  307. {
  308. $documentManager = $this->getDocumentManager();
  309. $document = $this->findModel($id);
  310. return $documentManager->downloadPdf($document);
  311. }
  312. public function actionRegenerate($id)
  313. {
  314. $documentManager = $this->getDocumentManager();
  315. $document = $this->findModel($id);
  316. $documentManager->downloadPdf($document, true);
  317. $this->setFlash('success', 'Le document PDF a bien été regénéré.');
  318. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  319. }
  320. public function actionSend(int $id, $backUpdateForm = false)
  321. {
  322. $documentManager = $this->getDocumentManager();
  323. $document = $this->findModel($id);
  324. if ($documentManager->sendDocument($document)) {
  325. $this->setFlash('success', $this->getFlashMessage('send', $document));
  326. } else {
  327. $this->setFlash('danger', $this->getFlashMessage('send', $document));
  328. }
  329. if ($backUpdateForm) {
  330. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  331. } else {
  332. return $this->redirect([$this->getControllerUrl() . '/index']);
  333. }
  334. }
  335. public function actionAjaxUserInfos($typeAction, $idUser, $classDocument, $idDocument = false)
  336. {
  337. $userManager = $this->getUserManager();
  338. $documentManager = $this->getDocumentManager();
  339. $orderManager = $this->getOrderManager();
  340. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  341. if ($idUser > 0) {
  342. $user = $userManager->findOneUserById($idUser);
  343. if ($user) {
  344. $document = null;
  345. if ($documentManager->isValidClass($classDocument) && $idDocument) {
  346. $document = $this->findModel($idDocument, $classDocument);
  347. }
  348. if ($document && $document->id_user == $user->id) {
  349. $address = $document->address;
  350. } else {
  351. $address = $userManager->getFullAddress($user);
  352. }
  353. $json = [
  354. 'return' => 'success',
  355. 'address' => $address
  356. ];
  357. if ($classDocument == 'Invoice') {
  358. $options = [
  359. 'orderby' => 'distribution.date ASC',
  360. 'join_with' => ['user AS user_delivery_note', 'orders', 'producer']
  361. ];
  362. $deliveryNotesCreateArray = DeliveryNote::searchAll([
  363. 'id_user' => $user->id,
  364. 'status' => Document::STATUS_VALID,
  365. 'ignore_when_invoicing' => null
  366. ], $options);
  367. $deliveryNotesUpdateArray = DeliveryNote::searchAll([
  368. 'id_user' => $user->id,
  369. 'status' => Document::STATUS_VALID,
  370. 'order.id_invoice' => $idDocument,
  371. 'ignore_when_invoicing' => null
  372. ], $options);
  373. $json['delivery_note_create_array'] = $this->initDeliveryNoteArray('create', $deliveryNotesCreateArray);
  374. $json['delivery_note_update_array'] = $this->initDeliveryNoteArray('update', $deliveryNotesUpdateArray);
  375. $json['orders_create_array'] = $this->initOrdersArray($orderManager->findOrdersByUserNotInvoiced($user));
  376. $json['orders_update_array'] = $document ? $this->initOrdersArray($orderManager->findOrdersByUserAndInvoice($user, $document)) : [];
  377. }
  378. return $json;
  379. }
  380. }
  381. return ['return' => 'error'];
  382. }
  383. public function initOrdersArray(array $ordersArray)
  384. {
  385. $orderManager = $this->getOrderManager();
  386. $ordersReturnArray = [];
  387. foreach($ordersArray as &$order) {
  388. $orderManager->initOrder($order);
  389. $ordersReturnArray[] = [
  390. 'id' => $order->id,
  391. 'date' => $order->distribution->date,
  392. 'name' => date('d/m/Y', strtotime($order->distribution->date)),
  393. 'amount_with_tax' => $orderManager->getOrderAmountWithTax($order, Order::INVOICE_AMOUNT_TOTAL)
  394. ];
  395. }
  396. return $ordersReturnArray;
  397. }
  398. public function initDeliveryNoteArray($type, $deliveryNoteArrayResults)
  399. {
  400. $deliveryNoteArray = [];
  401. $isCreate = false;
  402. if ($type == 'create') {
  403. $isCreate = true;
  404. }
  405. if ($deliveryNoteArrayResults) {
  406. foreach ($deliveryNoteArrayResults as $deliveryNote) {
  407. $deliveryNoteData = $this->addDeliveryNoteToArray($deliveryNote, $isCreate);
  408. if ($deliveryNoteData) {
  409. $deliveryNoteArray[] = $deliveryNoteData;
  410. }
  411. }
  412. }
  413. return $deliveryNoteArray;
  414. }
  415. public function addDeliveryNoteToArray($deliveryNote, $isCreate = true)
  416. {
  417. $deliveryNoteManager = $this->getDeliveryNoteManager();
  418. $deliveryNoteData = array_merge(
  419. $deliveryNote->getAttributes(),
  420. [
  421. 'url' => $this->getUrlManagerBackend()->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
  422. 'total' => $deliveryNoteManager->getAmountWithTax($deliveryNote, Order::INVOICE_AMOUNT_TOTAL)
  423. ]
  424. );
  425. if (($isCreate && !$deliveryNoteManager->isInvoiced($deliveryNote)) || !$isCreate) {
  426. return $deliveryNoteData;
  427. }
  428. return false;
  429. }
  430. public function actionValidate($id, $backUpdateForm = false)
  431. {
  432. $documentManager = $this->getDocumentManager();
  433. $classDocument = $this->getClass();
  434. if ($id > 0 && $documentManager->isValidClass($classDocument)) {
  435. $document = $this->findModel($id);
  436. if ($document) {
  437. $documentManager->validateDocument($document);
  438. // @TODO : gérer via un événement
  439. $documentManager->generatePdf($document, Pdf::DEST_FILE);
  440. $this->setFlash('success', $this->getFlashMessage('validate', $document));
  441. if ($backUpdateForm) {
  442. return $this->redirect([$this->getControllerUrl() . '/update', 'id' => $id]);
  443. } else {
  444. return $this->redirect([$this->getControllerUrl() . '/index']);
  445. }
  446. }
  447. }
  448. $this->setFlash('danger', 'Une erreur est survenue lors de la validation du document.');
  449. return $this->redirect([$this->getControllerUrl() . '/index']);
  450. }
  451. public function actionAjaxInit($idDocument, $classDocument)
  452. {
  453. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  454. $orderManager = $this->getOrderManager();
  455. $productManager = $this->getProductManager();
  456. $documentManager = $this->getDocumentManager();
  457. $deliveryNoteManager = $this->getDeliveryNoteManager();
  458. $userProducerManager = $this->getUserProducerManager();
  459. $pointSaleManager = $this->getPointSaleManager();
  460. if ($idDocument > 0 && $documentManager->isValidClass($classDocument)) {
  461. $document = $this->findModel($idDocument, $classDocument);
  462. if ($document) {
  463. $ordersArray = [];
  464. $productsArray = $productManager->findProducts();
  465. foreach ($document->orders as $order) {
  466. $orderManager->initOrder($order);
  467. $productsOrderArray = [];
  468. foreach ($order->productOrder as $productOrder) {
  469. $productsOrderArray[$productOrder->id] = array_merge($productOrder->getAttributes(), [
  470. 'url_order' => $this->getUrlManagerBackend()->createUrl(['distribution/index', 'idOrderUpdate' => $productOrder->id_order])
  471. ]);
  472. }
  473. $ordersArray[$order->id] = array_merge(
  474. $order->getAttributes(),
  475. [
  476. 'username' => $orderManager->getOrderUsername($order),
  477. 'distribution_date' => isset($order->distribution) ? date(
  478. 'd/m/Y',
  479. strtotime(
  480. $order->distribution->date
  481. )
  482. ) : null,
  483. 'point_sale_name' => isset($order->pointSale) ? $order->pointSale->name : null,
  484. 'productOrder' => $productsOrderArray,
  485. ]
  486. );
  487. }
  488. $userProducer = $userProducerManager->findOneUserProducer($document->user);
  489. $pointSale = $pointSaleManager->findOnePointSaleByIdUser($document->user->id);
  490. $productsArray = yii\helpers\ArrayHelper::map(
  491. $productsArray,
  492. 'order',
  493. function ($product) use ($document, $userProducer, $pointSale, $productManager) {
  494. return array_merge($product->getAttributes(), [
  495. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  496. 'prices' => $productManager->getPriceArray($product, $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' => $documentManager->getHtmlLabel($document),
  507. 'class' => $documentManager->getClass($document)
  508. ]),
  509. 'id_user' => $document->user->id,
  510. 'products' => $productsArray,
  511. 'orders' => $ordersArray,
  512. 'total' => ($documentManager->getClass($document) == 'Invoice' || $documentManager->getClass($document) == 'DeliveryNote') ? $documentManager->getAmount(
  513. $document,
  514. Order::INVOICE_AMOUNT_TOTAL
  515. ) : $documentManager->getAmount($document, Order::AMOUNT_TOTAL),
  516. 'total_with_tax' => ($documentManager->getClass($document) == 'Invoice' || $documentManager->getClass($document) == 'DeliveryNote') ? $documentManager->getAmountWithTax(
  517. $document,
  518. Order::INVOICE_AMOUNT_TOTAL
  519. ) : $documentManager->getAmountWithTax($document, Order::AMOUNT_TOTAL),
  520. 'invoice_url' => ($documentManager->getClass($document) == 'DeliveryNote' && $deliveryNoteManager->getInvoice($document)) ? $this->getUrlManagerBackend()->createUrl(['invoice/update', 'id' => $deliveryNoteManager->getInvoice($document)->id]) : null
  521. ];
  522. }
  523. }
  524. return ['return' => 'error'];
  525. }
  526. public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price)
  527. {
  528. $documentManager = $this->getDocumentManager();
  529. $productManager = $this->getProductManager();
  530. if ($documentManager->isValidClass($classDocument)) {
  531. $document = $this->findModel($idDocument, $classDocument);
  532. $classDocumentComplete = $documentManager->getClass($document, true);
  533. $product = $productManager->findOneProductById($idProduct);
  534. if ($document && $product) {
  535. if (count($document->orders) == 0) {
  536. $order = new Order;
  537. $order->id_user = $document->id_user;
  538. $order->id_point_sale = null;
  539. $order->id_distribution = null;
  540. $order->status = 'tmp-order';
  541. $order->origin = Order::ORIGIN_ADMIN;
  542. $order->date = date('Y-m-d H:i:s');
  543. $fieldIdDocument = 'id_' . $classDocumentComplete::tableName();
  544. $order->$fieldIdDocument = $document->id;
  545. $order->save();
  546. } else {
  547. $order = $document->orders[0];
  548. }
  549. if ($order) {
  550. $productOrder = new ProductOrder();
  551. $productOrder->id_order = $order->id;
  552. $productOrder->id_product = $idProduct;
  553. $quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
  554. $productOrder->quantity = $quantity;
  555. $productOrder->price = (float)$price;
  556. $productOrder->unit = $product->unit;
  557. $productOrder->step = $product->step;
  558. $productOrder->id_tax_rate = $product->taxRate->id;
  559. $productOrder->save();
  560. return Ajax::responseSuccess('Produit ajouté');
  561. }
  562. }
  563. }
  564. return Ajax::responseError('Une erreur est survenue lors de la suppression du produit.');
  565. }
  566. public function actionAjaxDeleteProductOrder($idProductOrder)
  567. {
  568. $productOrderManager = $this->getProductOrderManager();
  569. $productOrder = $productOrderManager->findOneProductOrderById($idProductOrder);
  570. if ($productOrder) {
  571. $productOrderManager->delete($productOrder);
  572. return Ajax::responseSuccess('Produit supprimé');
  573. }
  574. return Ajax::responseError('Une erreur est survenue lors de la suppression du produit.');
  575. }
  576. public function getClass()
  577. {
  578. $class = get_class($this);
  579. $class = str_replace('Controller', '', $class);
  580. $class = str_replace('backend\controllers\\', '', $class);
  581. return $class;
  582. }
  583. public function getDocumentType()
  584. {
  585. $class = $this->getClass();
  586. if ($class == 'Invoice') {
  587. $documentType = 'Facture';
  588. } elseif ($class == 'DeliveryNote') {
  589. $documentType = 'Bon de livraison';
  590. } elseif ($class == 'Quotation') {
  591. $documentType = 'Devis';
  592. }
  593. if (isset($documentType)) {
  594. return $documentType;
  595. }
  596. return '';
  597. }
  598. public function getFlashMessage(string $type, $model)
  599. {
  600. $class = $this->getClass();
  601. $message = $this->getDocumentType();
  602. $message .= ' <strong>' . Html::encode($model->name) . '</strong> ';
  603. if ($type == 'create') {
  604. $message .= 'ajouté';
  605. } elseif ($type == 'update') {
  606. $message .= 'modifié';
  607. } elseif ($type == 'delete') {
  608. $message .= 'supprimé';
  609. } elseif ($type == 'validate') {
  610. $message .= 'validé';
  611. } elseif ($type == 'send') {
  612. $message .= 'envoyé';
  613. }
  614. if ($class == 'Invoice') {
  615. $message .= 'e';
  616. }
  617. return $message;
  618. }
  619. protected function getTitle($prepend)
  620. {
  621. $class = $this->getClass();
  622. switch ($class) {
  623. case 'Invoice' :
  624. $title = $prepend . ' une facture';
  625. break;
  626. case 'DeliveryNote' :
  627. $title = $prepend . ' un bon de livraison';
  628. break;
  629. case 'Quotation' :
  630. $title = $prepend . ' un devis';
  631. break;
  632. }
  633. return $title;
  634. }
  635. public function getControllerUrl()
  636. {
  637. $path = strtolower($this->getClass());
  638. $path = str_replace('deliverynote', 'delivery-note', $path);
  639. return $path;
  640. }
  641. /**
  642. * Recherche un Document en fonction de son ID.
  643. *
  644. * @param integer $id
  645. * @return Document
  646. * @throws NotFoundHttpException si le modèle n'est pas trouvé
  647. */
  648. protected function findModel($idDocument, $classDocument = null)
  649. {
  650. $documentManager = $this->getDocumentManager();
  651. $model = $documentManager->findOneDocumentByIdAndClass($idDocument, $classDocument ?? $this->getClass());
  652. if ($model) {
  653. return $model;
  654. } else {
  655. throw new NotFoundHttpException('The requested page does not exist.');
  656. }
  657. }
  658. }