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.

875 lines
33KB

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