Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

896 rindas
34KB

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