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.

884 lines
34KB

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