Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

793 lines
29KB

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