Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

804 lines
30KB

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