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

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