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

880 line
34KB

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