Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

5 роки тому
5 роки тому
4 роки тому
5 роки тому
10 місяці тому
10 місяці тому
4 роки тому
4 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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 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\ProductOrder\ProductOrder;
  49. use domain\Payment\Payment;
  50. use kartik\mpdf\Pdf;
  51. use domain\Product\Product\Product;
  52. use yii;
  53. use yii\base\UserException;
  54. use yii\filters\AccessControl;
  55. use yii\helpers\Html;
  56. use yii\web\NotFoundHttpException;
  57. class DocumentController extends BackendController
  58. {
  59. public function behaviors()
  60. {
  61. return [
  62. 'access' => [
  63. 'class' => AccessControl::class,
  64. 'rules' => [
  65. [
  66. 'allow' => true,
  67. 'roles' => ['@'],
  68. 'matchCallback' => function ($rule, $action) {
  69. return $this->getUserModule()
  70. ->getAuthorizationChecker()
  71. ->isGrantedAsProducer($this->getUserCurrent());
  72. }
  73. ]
  74. ],
  75. ],
  76. ];
  77. }
  78. public function actionGeneratePdfValidatedDocuments()
  79. {
  80. set_time_limit(0);
  81. $validatedDocumentsArray = array_merge(
  82. Quotation::find()->where(['status' => Document::STATUS_VALID])->all(),
  83. DeliveryNote::find()->where(['status' => Document::STATUS_VALID])->all(),
  84. Invoice::find()->where(['status' => Document::STATUS_VALID])->all()
  85. );
  86. foreach ($validatedDocumentsArray as $document) {
  87. if (!file_exists($document->getFilenameComplete())) {
  88. $document->generatePdf(Pdf::DEST_FILE);
  89. }
  90. }
  91. }
  92. public function actionCreate()
  93. {
  94. $documentModule = $this->getDocumentModule();
  95. $class = $this->getClass();
  96. $class = 'domain\\Document\\'.$class.'\\'.$class;
  97. $model = new $class();
  98. $documentModule->initTaxCalculationMethod($model);
  99. if ($model->load(\Yii::$app->request->post())) {
  100. $model->id_producer = GlobalParam::getCurrentProducerId();
  101. if ($model->save()) {
  102. $this->processInvoiceViaDeliveryNotes($model);
  103. $this->processInvoiceViaOrders($model);
  104. $this->setFlash('success', $this->getFlashMessage('create', $model));
  105. return $this->redirect(['/' . $this->getControllerUrl() . '/update', 'id' => $model->id]);
  106. } else {
  107. $this->setFlash('error', 'Un problème est survenu lors de la création du document.');
  108. }
  109. }
  110. return $this->render('/document/create', [
  111. 'title' => $this->getTitle('Ajouter'),
  112. 'typeDocument' => $this->getDocumentType(),
  113. 'model' => $model,
  114. ]);
  115. }
  116. public function processInvoiceViaDeliveryNotes($model)
  117. {
  118. $orderModule = $this->getOrderModule();
  119. $documentModule = $this->getDocumentModule();
  120. $deliveryNoteModule = $this->getDeliveryNoteModule();
  121. if ($documentModule->getClass($model) == 'Invoice') {
  122. if ($model->deliveryNotes && is_array($model->deliveryNotes) && count($model->deliveryNotes)) {
  123. foreach ($model->deliveryNotes as $key => $idDeliveryNote) {
  124. $deliveryNote = $deliveryNoteModule->findOneDeliveryNoteById($idDeliveryNote);
  125. $orderModule->assignAllOrdersInvoiceByDeliveryNote($model, $deliveryNote);
  126. }
  127. }
  128. }
  129. }
  130. public function processInvoiceViaOrders($model)
  131. {
  132. $orderModule = $this->getOrderModule();
  133. $documentModule = $this->getDocumentModule();
  134. if ($documentModule->getClass($model) == 'Invoice') {
  135. if ($model->ordersOnCreate && is_array($model->ordersOnCreate) && count($model->ordersOnCreate)) {
  136. foreach ($model->ordersOnCreate as $key => $idOrder) {
  137. $order = $orderModule->findOneOrderById($idOrder);
  138. $orderModule->updateOrderInvoice($order, $model);
  139. }
  140. }
  141. }
  142. }
  143. public function actionUpdate($id)
  144. {
  145. $documentModule = $this->getDocumentModule();
  146. $paymentManager = $this->getPaymentModule();
  147. $document = $this->findModel($id);
  148. if (!$document) {
  149. throw new yii\web\NotFoundHttpException('Le document n\'a pas été trouvé.');
  150. }
  151. if ($document && $document->load(\Yii::$app->request->post()) && $document->save()) {
  152. $this->setFlash('success', $this->getFlashMessage('update', $document));
  153. }
  154. $payment = null;
  155. if($documentModule->isDocumentInvoice($document) && $documentModule->isStatusValid($document)) {
  156. $payment = $paymentManager->instanciatePayment(
  157. Payment::TYPE_PAYMENT,
  158. number_format($documentModule->getAmountWithTax($document, Order::INVOICE_AMOUNT_TOTAL), 2),
  159. $this->getProducerCurrent(),
  160. null,
  161. null,
  162. MeanPayment::TRANSFER,
  163. null,
  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. $documentModule = $this->getDocumentModule();
  193. $model = $this->findModel($id);
  194. if ($documentModule->isStatusValid($model)) {
  195. throw new UserException('Vous ne pouvez pas supprimer un document validé.');
  196. }
  197. $documentModule->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. $documentModule = $this->getDocumentModule();
  225. $productOrderModule = $this->getProductOrderModule();
  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 ($documentModule->getProductsOrders($document, true) as $productOrderArray) {
  269. foreach ($productOrderArray as $productOrder) {
  270. $price = $productOrder->getPrice();
  271. if ($documentModule->isInvoicePrice($document) && $productOrder->getInvoicePrice()) {
  272. $price = $productOrder->getInvoicePrice();
  273. }
  274. $typeTotal = $documentModule->isInvoicePrice($document) ? Order::INVOICE_AMOUNT_TOTAL : Order::AMOUNT_TOTAL;
  275. $priceTotal = $productOrderModule->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 ($documentModule->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. $documentModule = $this->getDocumentModule();
  339. $document = $this->findModel($id);
  340. return $documentModule->downloadPdf($document);
  341. }
  342. public function actionRegenerate($id)
  343. {
  344. $documentModule = $this->getDocumentModule();
  345. $document = $this->findModel($id);
  346. $documentModule->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. $documentModule = $this->getDocumentModule();
  353. $document = $this->findModel($id);
  354. if ($documentModule->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. $documentModule = $this->getDocumentModule();
  369. $orderModule = $this->getOrderModule();
  370. $producerModule = $this->getProducerModule();
  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 ($documentModule->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(!$producerModule->getConfig('option_invoice_only_based_on_delivery_notes')) {
  410. $json['orders_create_array'] = $this->initOrdersArray($orderModule->findOrdersByUserNotInvoiced($user));
  411. $json['orders_update_array'] = $document ? $this->initOrdersArray($orderModule->findOrdersByUserAndInvoice($user, $document)) : [];
  412. }
  413. }
  414. if ($classDocument == 'DeliveryNote') {
  415. $json['orders_create_array'] = $this->initOrdersArray($orderModule->findOrdersByUserNotLinkedDeliveryNote($user));
  416. $json['orders_update_array'] = $document ? $this->initOrdersArray($orderModule->findOrdersByUserAndDeliveryNote($user, $document)) : [];
  417. }
  418. return $json;
  419. }
  420. }
  421. return ['return' => 'error'];
  422. }
  423. public function initOrdersArray(array $ordersArray)
  424. {
  425. $orderModule = $this->getOrderModule();
  426. $ordersReturnArray = [];
  427. foreach($ordersArray as &$order) {
  428. $orderModule->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' => $orderModule->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. $deliveryNoteModule = $this->getDeliveryNoteModule();
  458. $deliveryNoteData = array_merge(
  459. $deliveryNote->getAttributes(),
  460. [
  461. 'url' => $this->getUrlManagerBackend()->createUrl(['delivery-note/update', 'id' => $deliveryNote->id]),
  462. 'total' => $deliveryNoteModule->getAmountWithTax($deliveryNote, Order::INVOICE_AMOUNT_TOTAL)
  463. ]
  464. );
  465. if (($isCreate && !$deliveryNoteModule->isInvoiced($deliveryNote)) || !$isCreate) {
  466. return $deliveryNoteData;
  467. }
  468. return false;
  469. }
  470. public function actionValidate($id, $backUpdateForm = false)
  471. {
  472. $documentModule = $this->getDocumentModule();
  473. $classDocument = $this->getClass();
  474. if ($id > 0 && $documentModule->isValidClass($classDocument)) {
  475. $document = $this->findModel($id);
  476. if ($document) {
  477. $documentModule->getManager()->validateDocument($document);
  478. // @TODO : gérer via un événement
  479. $documentModule->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. $orderModule = $this->getOrderModule();
  495. $productModule = $this->getProductModule();
  496. $documentModule = $this->getDocumentModule();
  497. $deliveryNoteModule = $this->getDeliveryNoteModule();
  498. $userProducerModule = $this->getUserProducerModule();
  499. $pointSaleModule = $this->getPointSaleModule();
  500. if ($idDocument > 0 && $documentModule->isValidClass($classDocument)) {
  501. $document = $this->findModel($idDocument, $classDocument);
  502. if ($document) {
  503. $ordersArray = [];
  504. $productsArray = $productModule->findProducts(false);
  505. foreach ($document->orders as $order) {
  506. $orderModule->initOrder($order);
  507. $productsOrderArray = [];
  508. foreach ($order->productOrder as $productOrder) {
  509. $productsOrderArray[$productOrder->id] = array_merge($productOrder->getAttributes(), [
  510. 'url_product' => $this->getUrlManagerBackend()->createUrl(['product/update', 'id' => $productOrder->id_product]),
  511. 'url_order' => $this->getUrlManagerBackend()->createUrl(['distribution/index', 'idOrderUpdate' => $productOrder->id_order])
  512. ]);
  513. }
  514. $ordersArray[$order->id] = array_merge(
  515. $order->getAttributes(),
  516. [
  517. 'username' => $orderModule->getOrderUsername($order),
  518. 'distribution_date' => isset($order->distribution) ? date(
  519. 'd/m/Y',
  520. strtotime(
  521. $order->distribution->date
  522. )
  523. ) : null,
  524. 'point_sale_name' => isset($order->pointSale) ? $order->pointSale->name : null,
  525. 'productOrder' => $productsOrderArray,
  526. ]
  527. );
  528. }
  529. $userProducer = $userProducerModule->findOneUserProducer($document->user);
  530. $pointSale = $pointSaleModule->findOnePointSaleByIdUser($document->user->id);
  531. $productsArray = yii\helpers\ArrayHelper::map(
  532. $productsArray,
  533. 'order',
  534. function ($product) use ($document, $userProducer, $pointSale, $productModule) {
  535. return array_merge($product->getAttributes(), [
  536. 'unit_coefficient' => $productModule->getSolver()->getUnitCoefficient($product),
  537. 'prices' => $productModule->getPriceArray($product, $userProducer->user, $pointSale),
  538. 'wording_unit' => $product->wording_unit,
  539. 'tax_rate' => $product->taxRate->value
  540. ]);
  541. }
  542. );
  543. return [
  544. 'return' => 'success',
  545. 'tax_rate_producer' => GlobalParam::getCurrentProducer()->taxRate->value,
  546. 'document' => array_merge($document->getAttributes(), [
  547. 'html_label' => $documentModule->getHtmlLabel($document),
  548. 'class' => $documentModule->getClass($document)
  549. ]),
  550. 'id_user' => $document->user->id,
  551. 'products' => $productsArray,
  552. 'orders' => $ordersArray,
  553. 'total' => ($documentModule->getClass($document) == 'Invoice' || $documentModule->getClass($document) == 'DeliveryNote') ? $documentModule->getAmount(
  554. $document,
  555. Order::INVOICE_AMOUNT_TOTAL
  556. ) : $documentModule->getAmount($document, Order::AMOUNT_TOTAL),
  557. 'total_with_tax' => ($documentModule->getClass($document) == 'Invoice' || $documentModule->getClass($document) == 'DeliveryNote') ? $documentModule->getAmountWithTax(
  558. $document,
  559. Order::INVOICE_AMOUNT_TOTAL
  560. ) : $documentModule->getAmountWithTax($document, Order::AMOUNT_TOTAL),
  561. 'invoice_url' => ($documentModule->getClass($document) == 'DeliveryNote' && $deliveryNoteModule->getInvoice($document)) ? $this->getUrlManagerBackend()->createUrl(['invoice/update', 'id' => $deliveryNoteModule->getInvoice($document)->id]) : null
  562. ];
  563. }
  564. }
  565. return ['return' => 'error'];
  566. }
  567. public function actionAjaxAddProduct($idDocument, $classDocument, $idProduct, $quantity, $price)
  568. {
  569. $documentModule = $this->getDocumentModule();
  570. $productModule = $this->getProductModule();
  571. if ($documentModule->isValidClass($classDocument)) {
  572. $document = $this->findModel($idDocument, $classDocument);
  573. $classDocumentComplete = $documentModule->getClass($document, true);
  574. $product = $productModule->findOneProductById($idProduct);
  575. if ($document && $product) {
  576. if (count($document->orders) == 0) {
  577. $order = new Order;
  578. $order->id_user = $document->id_user;
  579. $order->id_point_sale = null;
  580. $order->id_distribution = null;
  581. $order->status = 'tmp-order';
  582. $order->origin = Order::ORIGIN_ADMIN;
  583. $order->date = date('Y-m-d H:i:s');
  584. $fieldIdDocument = 'id_' . $classDocumentComplete::tableName();
  585. $order->$fieldIdDocument = $document->id;
  586. $order->save();
  587. } else {
  588. $order = $document->orders[0];
  589. }
  590. if ($order) {
  591. $productOrder = new ProductOrder();
  592. $productOrder->id_order = $order->id;
  593. $productOrder->id_product = $idProduct;
  594. $quantity = $quantity / Product::$unitsArray[$product->unit]['coefficient'];
  595. $productOrder->quantity = $quantity;
  596. $productOrder->price = (float)$price;
  597. $productOrder->unit = $product->unit;
  598. $productOrder->step = $product->step;
  599. $productOrder->id_tax_rate = $product->taxRate->id;
  600. $productOrder->save();
  601. return Ajax::responseSuccess('Produit ajouté');
  602. }
  603. }
  604. }
  605. return Ajax::responseError('Une erreur est survenue lors de la suppression du produit.');
  606. }
  607. public function actionAjaxDeleteProductOrder($idProductOrder)
  608. {
  609. $productOrderModule = $this->getProductOrderModule();
  610. $productOrder = $productOrderModule->findOneProductOrderById($idProductOrder);
  611. if ($productOrder) {
  612. $productOrderModule->delete($productOrder);
  613. return Ajax::responseSuccess('Produit supprimé');
  614. }
  615. return Ajax::responseError('Une erreur est survenue lors de la suppression du produit.');
  616. }
  617. public function actionAjaxAddOrder($idDocument, $classDocument, $idOrder)
  618. {
  619. $documentModule = $this->getDocumentModule();
  620. $orderModule = $this->getOrderModule();
  621. $document = $documentModule->findOneDocumentByIdAndClass($idDocument, $classDocument);
  622. $order = $orderModule->findOneOrderById($idOrder);
  623. if ($document && $documentModule->isStatusDraft($document) && $order) {
  624. $orderModule->updateOrderDocument($order, $document);
  625. return Ajax::responseSuccess("Commande ajoutée à la facture.");
  626. }
  627. else {
  628. return Ajax::responseError("Une erreur est survenue lors de l'ajout de la commande.");
  629. }
  630. }
  631. public function actionAjaxDeleteOrder($idDocument, $classDocument, $idOrder)
  632. {
  633. $documentModule = $this->getDocumentModule();
  634. $orderModule = $this->getOrderModule();
  635. $document = $documentModule->findOneDocumentByIdAndClass($idDocument, $classDocument);
  636. $order = $orderModule->findOneOrderById($idOrder);
  637. if ($document && $documentModule->isStatusDraft($document)) {
  638. if($documentModule->isDocumentDeliveryNote($document)) {
  639. $orderModule->updateOrderDeliveryNote($order, null);
  640. }
  641. elseif($documentModule->isDocumentInvoice($document)) {
  642. $orderModule->updateOrderInvoice($order, null);
  643. }
  644. return Ajax::responseSuccess('Commande supprimée de la facture.');
  645. }
  646. else {
  647. return Ajax::responseError('Une erreur est survenue lors de la suppression de la commande.');
  648. }
  649. }
  650. public function actionAjaxIgnoreOrderWhenInvoicing($idDocument, $classDocument, $idOrder)
  651. {
  652. $documentModule = $this->getDocumentModule();
  653. $orderModule = $this->getOrderModule();
  654. $document = $documentModule->findOneDocumentByIdAndClass($idDocument, $classDocument);
  655. $order = $orderModule->findOneOrderById($idOrder);
  656. if ($document && $documentModule->isStatusDraft($document) && $order) {
  657. $orderModule->updateOrderIgnoreWhenInvoicing($order, true);
  658. return Ajax::responseSuccess("La commande sera maintenant ignorée au moment de la facturation.");
  659. }
  660. else {
  661. return Ajax::responseError("Une erreur est survenue.");
  662. }
  663. }
  664. public function actionAjaxUpdateProductOrderInvoicePrice($idProductOrder, $invoicePrice)
  665. {
  666. $productOrderModule = $this->getProductOrderModule();
  667. $productOrder = $productOrderModule->getRepository()->findOneProductOrderById((int) $idProductOrder);
  668. if($productOrder) {
  669. $productOrderModule->getBuilder()->updateProductOrderInvoicePriceByValue($productOrder, (float) $invoicePrice);
  670. return Ajax::responseSuccess("Prix mis à jour", [
  671. 'invoice_price' => $productOrder->invoice_price
  672. ]);
  673. }
  674. return Ajax::responseError("Une erreur est survenue.");
  675. }
  676. public function getClass()
  677. {
  678. $class = get_class($this);
  679. $class = str_replace('Controller', '', $class);
  680. $class = str_replace('backend\controllers\\', '', $class);
  681. return $class;
  682. }
  683. public function getDocumentType()
  684. {
  685. $class = $this->getClass();
  686. if ($class == 'Invoice') {
  687. $documentType = 'Facture';
  688. } elseif ($class == 'DeliveryNote') {
  689. $documentType = 'Bon de livraison';
  690. } elseif ($class == 'Quotation') {
  691. $documentType = 'Devis';
  692. }
  693. if (isset($documentType)) {
  694. return $documentType;
  695. }
  696. return '';
  697. }
  698. public function getFlashMessage(string $type, $model)
  699. {
  700. $class = $this->getClass();
  701. $message = $this->getDocumentType();
  702. $message .= ' <strong>' . Html::encode($model->name) . '</strong> ';
  703. if ($type == 'create') {
  704. $message .= 'ajouté';
  705. } elseif ($type == 'update') {
  706. $message .= 'modifié';
  707. } elseif ($type == 'delete') {
  708. $message .= 'supprimé';
  709. } elseif ($type == 'validate') {
  710. $message .= 'validé';
  711. } elseif ($type == 'send') {
  712. $message .= 'envoyé';
  713. }
  714. if ($class == 'Invoice') {
  715. $message .= 'e';
  716. }
  717. return $message;
  718. }
  719. protected function getTitle($prepend)
  720. {
  721. $class = $this->getClass();
  722. switch ($class) {
  723. case 'Invoice' :
  724. $title = $prepend . ' une facture';
  725. break;
  726. case 'DeliveryNote' :
  727. $title = $prepend . ' un bon de livraison';
  728. break;
  729. case 'Quotation' :
  730. $title = $prepend . ' un devis';
  731. break;
  732. }
  733. return $title;
  734. }
  735. public function getControllerUrl()
  736. {
  737. $path = strtolower($this->getClass());
  738. $path = str_replace('deliverynote', 'delivery-note', $path);
  739. return $path;
  740. }
  741. /**
  742. * Recherche un Document en fonction de son ID.
  743. *
  744. * @param integer $id
  745. * @return Document
  746. * @throws NotFoundHttpException si le modèle n'est pas trouvé
  747. */
  748. protected function findModel($idDocument, $classDocument = null)
  749. {
  750. $documentModule = $this->getDocumentModule();
  751. $model = $documentModule->findOneDocumentByIdAndClass($idDocument, $classDocument ?? $this->getClass());
  752. if ($model) {
  753. return $model;
  754. } else {
  755. throw new NotFoundHttpException('The requested page does not exist.');
  756. }
  757. }
  758. }