Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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