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.

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