Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

DocumentController.php 34KB

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