You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

528 lines
17KB

  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 common\models;
  38. use common\helpers\GlobalParam;
  39. use kartik\mpdf\Pdf;
  40. use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
  41. use yii\base\ErrorException;
  42. class Document extends ActiveRecordCommon
  43. {
  44. const STATUS_DRAFT = 'draft';
  45. const STATUS_VALID = 'valid';
  46. const TAX_CALCULATION_METHOD_SUM_OF_ROUNDINGS = 'sum-roundings';
  47. const TAX_CALCULATION_METHOD_ROUNDING_OF_THE_SUM = 'rounding-sum';
  48. const TAX_CALCULATION_METHOD_DEFAULT = self::TAX_CALCULATION_METHOD_ROUNDING_OF_THE_SUM;
  49. public static $taxCalculationMethodArray = [
  50. self::TAX_CALCULATION_METHOD_ROUNDING_OF_THE_SUM => 'Arrondi de la somme des lignes',
  51. self::TAX_CALCULATION_METHOD_SUM_OF_ROUNDINGS => 'Somme des arrondis de chaque ligne'
  52. ];
  53. /**
  54. * @inheritdoc
  55. */
  56. public function rules()
  57. {
  58. return [
  59. [['name', 'id_user'], 'required'],
  60. [['date'], 'safe'],
  61. [['comment', 'address', 'tax_calculation_method'], 'string'],
  62. [['id_user', 'id_producer'], 'integer'],
  63. [['is_sent'], 'boolean'],
  64. [['name', 'reference', 'status'], 'string', 'max' => 255],
  65. [['deliveryNotes'], 'safe']
  66. ];
  67. }
  68. /**
  69. * @inheritdoc
  70. */
  71. public function attributeLabels()
  72. {
  73. return [
  74. 'id' => 'ID',
  75. 'name' => 'Nom',
  76. 'reference' => 'Référence',
  77. 'date' => 'Date',
  78. 'comment' => 'Commentaire',
  79. 'id_user' => 'Utilisateur',
  80. 'address' => 'Adresse',
  81. 'id_producer' => 'Producteur',
  82. 'status' => 'Statut',
  83. 'tax_calculation_method' => 'Méthode de calcul de la TVA',
  84. 'is_sent' => 'Envoyé'
  85. ];
  86. }
  87. /*
  88. * Relations
  89. */
  90. public function getUser()
  91. {
  92. return $this->hasOne(User::className(), ['id' => 'id_user']);
  93. }
  94. public function getProducer()
  95. {
  96. return $this->hasOne(Producer::className(), ['id' => 'id_producer']);
  97. }
  98. public function relationOrders($fieldIdDocument)
  99. {
  100. $defaultOptionsSearch = Order::defaultOptionsSearch();
  101. return $this->hasMany(Order::className(), [$fieldIdDocument => 'id'])
  102. ->with($defaultOptionsSearch['with'])
  103. ->joinWith($defaultOptionsSearch['join_with'])
  104. ->orderBy('distribution.date ASC');
  105. }
  106. /*
  107. * Méthodes
  108. */
  109. public function getAmount($type = Order::AMOUNT_TOTAL, $format = false)
  110. {
  111. return $this->_getAmountGeneric($type, false, $format);
  112. }
  113. public function getAmountWithTax($type = Order::AMOUNT_TOTAL, $format = false)
  114. {
  115. return $this->_getAmountGeneric($type, true, $format);
  116. }
  117. protected function _getAmountGeneric($type = Order::AMOUNT_TOTAL, $withTax = true, $format = false)
  118. {
  119. $amount = 0;
  120. $totalVat = 0;
  121. $ordersArray = $this->orders;
  122. // Méthode de calcul via les commandes liées
  123. /*foreach ($ordersArray as $order) {
  124. $order->init($this->tax_calculation_method);
  125. $amount += $order->getAmount($type);
  126. $totalVat += $order->getTotalVat($type);
  127. }*/
  128. // Méthode de calcul via getProductOrders()
  129. foreach ($this->getProductsOrders() as $productOrderArray) {
  130. foreach ($productOrderArray as $productOrder) {
  131. $priceLine = $productOrder->getPriceByTypeTotal($type) * $productOrder->quantity;
  132. $amount += $priceLine;
  133. $totalVat += Price::getVat($priceLine, $productOrder->taxRate->value, $this->tax_calculation_method);
  134. }
  135. }
  136. if ($this->isTaxCalculationMethodRoundingOfTheSum()) {
  137. $totalVat = Price::round($totalVat);
  138. }
  139. if ($withTax) {
  140. $amount += $totalVat;
  141. }
  142. if ($format) {
  143. return Price::format($amount);
  144. } else {
  145. return $amount;
  146. }
  147. }
  148. public function getTotalVatArray($typeTotal)
  149. {
  150. $totalVatArray = [];
  151. // Méthode de calcul via les commandes liées
  152. /*$ordersArray = $this->orders;
  153. foreach ($ordersArray as $order) {
  154. $order->init($this->tax_calculation_method);
  155. $fieldNameVat = $order->getFieldNameAmount($typeTotal, 'vat');
  156. foreach ($order->$fieldNameVat as $idTaxRate => $vat) {
  157. if (!isset($totalVatArray[$idTaxRate])) {
  158. $totalVatArray[$idTaxRate] = 0;
  159. }
  160. $totalVatArray[$idTaxRate] += $vat;
  161. }
  162. }*/
  163. // Méthode de calcul via getProductOrders()
  164. foreach ($this->getProductsOrders() as $productOrderArray) {
  165. foreach ($productOrderArray as $productOrder) {
  166. $idTaxRate = $productOrder->taxRate->id;
  167. if (!isset($totalVatArray[$idTaxRate])) {
  168. $totalVatArray[$idTaxRate] = 0;
  169. }
  170. $totalVatArray[$idTaxRate] += Price::getVat(
  171. $productOrder->getPriceByTypeTotal($typeTotal) * $productOrder->quantity,
  172. $productOrder->taxRate->value,
  173. $this->tax_calculation_method
  174. );
  175. }
  176. }
  177. return $totalVatArray;
  178. }
  179. public function getPointSale()
  180. {
  181. if (isset($this->orders) && isset($this->orders[0])) {
  182. return $this->orders[0]->pointSale;
  183. } else {
  184. return '';
  185. }
  186. }
  187. public function getDistribution()
  188. {
  189. if (isset($this->orders) && isset($this->orders[0])) {
  190. return $this->orders[0]->distribution;
  191. } else {
  192. return '';
  193. }
  194. }
  195. public function getClass()
  196. {
  197. return str_replace('common\models\\', '', get_class($this));
  198. }
  199. public function getType()
  200. {
  201. $class = $this->getClass();
  202. if ($class == 'Invoice') {
  203. $documentType = 'Facture';
  204. } elseif ($class == 'DeliveryNote') {
  205. $documentType = 'Bon de livraison';
  206. } elseif ($class == 'Quotation') {
  207. $documentType = 'Devis';
  208. }
  209. if (isset($documentType)) {
  210. return $documentType;
  211. }
  212. return '';
  213. }
  214. public static function isValidClass($typeDocument)
  215. {
  216. return in_array($typeDocument, ['Invoice', 'DeliveryNote', 'Quotation']);
  217. }
  218. public function generateReference()
  219. {
  220. $class = $this->getClass();
  221. $classLower = strtolower($class);
  222. if ($classLower == 'deliverynote') {
  223. $classLower = 'delivery_note';
  224. }
  225. $prefix = Producer::getConfig('document_' . $classLower . '_prefix');
  226. $oneDocumentExist = $class::searchOne(['status' => Document::STATUS_VALID], ['orderby' => 'reference DESC']);
  227. if ($oneDocumentExist) {
  228. $reference = $oneDocumentExist->reference;
  229. $pattern = '#([A-Z]+)?([0-9]+)#';
  230. preg_match($pattern, $reference, $matches, PREG_OFFSET_CAPTURE);
  231. $sizeNumReference = strlen($matches[2][0]);
  232. $numReference = ((int)$matches[2][0]) + 1;
  233. $numReference = str_pad($numReference, $sizeNumReference, '0', STR_PAD_LEFT);
  234. return $prefix . $numReference;
  235. } else {
  236. $firstReference = Producer::getConfig('document_' . $classLower . '_first_reference');
  237. if (strlen($firstReference) > 0) {
  238. return $firstReference;
  239. } else {
  240. return $prefix . '00001';
  241. }
  242. }
  243. }
  244. public function downloadPdf($regenerate = false)
  245. {
  246. $filenameComplete = $this->getFilenameComplete();
  247. if (!file_exists($filenameComplete) || $this->isStatusDraft() || $regenerate) {
  248. $this->generatePdf(Pdf::DEST_FILE);
  249. }
  250. if (file_exists($filenameComplete)) {
  251. return Yii::$app->response->sendFile($filenameComplete, $this->getFilename(), ['inline' => true]);
  252. } else {
  253. throw new ErrorException('File ' . $filenameComplete . ' not found');
  254. }
  255. }
  256. public function generatePdf($destination)
  257. {
  258. $producer = $this->producer;
  259. $content = Yii::$app->controller->renderPartial('/document/download', [
  260. 'producer' => $producer,
  261. 'document' => $this
  262. ]);
  263. $contentFooter = '<div id="footer">';
  264. $contentFooter .= '<div class="infos-bottom">' . Html::encode($producer->document_infos_bottom) . '</div>';
  265. if ($this->isStatusValid() || $this->isStatusDraft()) {
  266. $contentFooter .= '<div class="reference-document">';
  267. if ($this->isStatusValid()) {
  268. $contentFooter .= $this->getType() . ' N°' . $this->reference;
  269. }
  270. if ($this->isStatusDraft()) {
  271. $contentFooter .= $this->getType() . ' non validé';
  272. if ($this->getType() == 'Facture') {
  273. $contentFooter .= 'e';
  274. }
  275. }
  276. $contentFooter .= '</div>';
  277. }
  278. $contentFooter .= '</div>';
  279. $marginBottom = 10;
  280. if (strlen(Producer::getConfig('document_infos_bottom')) > 0) {
  281. $marginBottom = 40;
  282. }
  283. $this->initDirectoryPdf();
  284. $pdf = new Pdf([
  285. 'mode' => Pdf::MODE_UTF8,
  286. 'format' => Pdf::FORMAT_A4,
  287. 'orientation' => Pdf::ORIENT_PORTRAIT,
  288. 'destination' => $destination,
  289. 'content' => $content,
  290. 'filename' => $this->getFilenameComplete(),
  291. 'cssFile' => Yii::getAlias('@webroot/css/document/download.css'),
  292. 'marginBottom' => $marginBottom,
  293. 'methods' => [
  294. 'SetHTMLFooter' => $contentFooter
  295. ]
  296. ]);
  297. return $pdf->render();
  298. }
  299. public function send()
  300. {
  301. if (isset($this->user) && strlen($this->user->email) > 0) {
  302. $producer = GlobalParam::getCurrentProducer();
  303. $subjectEmail = $this->getType();
  304. if ($this->isStatusValid()) {
  305. $subjectEmail .= ' N°' . $this->reference;
  306. }
  307. $email = Yii::$app->mailer->compose(
  308. [
  309. 'html' => 'sendDocument-html',
  310. 'text' => 'sendDocument-text'
  311. ], [
  312. 'document' => $this,
  313. ])
  314. ->setTo($this->user->email)
  315. ->setFrom([$producer->getEmailOpendistrib() => $producer->name])
  316. ->setSubject('[' . $producer->name . '] ' . $subjectEmail);
  317. $this->generatePdf(Pdf::DEST_FILE);
  318. $email->attach($this->getFilenameComplete());
  319. return $email->send();
  320. }
  321. return false;
  322. }
  323. public function changeStatus($status)
  324. {
  325. if ($status == Document::STATUS_VALID) {
  326. $this->status = $status;
  327. $this->reference = $this->generateReference();
  328. }
  329. }
  330. public function getStatusWording()
  331. {
  332. return ($this->status == self::STATUS_DRAFT) ? 'Brouillon' : 'Validé';
  333. }
  334. public function getStatusCssClass()
  335. {
  336. return ($this->status == self::STATUS_DRAFT) ? 'default' : 'success';
  337. }
  338. public function getHtmlLabel()
  339. {
  340. $label = $this->getStatusWording();
  341. $classLabel = $this->getStatusCssClass();
  342. return '<span class="label label-' . $classLabel . '">' . $label . '</span>';
  343. }
  344. public function isStatus($status)
  345. {
  346. return $this->status == $status;
  347. }
  348. public function isStatusDraft()
  349. {
  350. return $this->isStatus(self::STATUS_DRAFT);
  351. }
  352. public function isStatusValid()
  353. {
  354. return $this->isStatus(self::STATUS_VALID);
  355. }
  356. public function getProductsOrders()
  357. {
  358. $productsOrdersArray = [];
  359. $ordersArray = $this->orders;
  360. if ($ordersArray && count($ordersArray)) {
  361. foreach ($ordersArray as $order) {
  362. foreach ($order->productOrder as $productOrder) {
  363. if ($productOrder->product) {
  364. $indexProductOrder = $productOrder->product->order;
  365. $newProductOrder = clone $productOrder;
  366. if (!isset($productsOrdersArray[$indexProductOrder])) {
  367. $productsOrdersArray[$indexProductOrder] = [$newProductOrder];
  368. } else {
  369. $productOrderMatch = false;
  370. foreach ($productsOrdersArray[$indexProductOrder] as &$theProductOrder) {
  371. if ($theProductOrder->unit == $productOrder->unit
  372. && $theProductOrder->price == $productOrder->price
  373. && $theProductOrder->invoice_price == $productOrder->invoice_price) {
  374. $theProductOrder->quantity += $productOrder->quantity;
  375. $productOrderMatch = true;
  376. }
  377. }
  378. if (!$productOrderMatch) {
  379. $productsOrdersArray[$indexProductOrder][] = $newProductOrder;
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. // tri des orderProduct par product.order
  387. ksort($productsOrdersArray);
  388. return $productsOrdersArray;
  389. }
  390. public function isDisplayOrders()
  391. {
  392. $displayOrders = ($this->getClass() == 'Invoice') ?
  393. Producer::getConfig('document_display_orders_invoice') :
  394. Producer::getConfig('document_display_orders_delivery_note');
  395. return $displayOrders;
  396. }
  397. public function getAliasDirectoryBase()
  398. {
  399. return '@app/web/pdf/' . $this->id_producer . '/';
  400. }
  401. public function initDirectoryPdf()
  402. {
  403. $aliasDirectoryBase = $this->getAliasDirectoryBase();
  404. $directoryPdf = Yii::getAlias($aliasDirectoryBase);
  405. if (!file_exists($directoryPdf)) {
  406. mkdir($directoryPdf, 0755);
  407. }
  408. }
  409. public function getFilename()
  410. {
  411. $filename = $this->getType() . '-';
  412. if ($this->isStatusValid()) {
  413. $filename .= $this->reference;
  414. } elseif ($this->isStatusDraft()) {
  415. $filename .= 'Brouillon-' . $this->id;
  416. }
  417. $filename .= '.pdf';
  418. return $filename;
  419. }
  420. public function getFilenameComplete()
  421. {
  422. return Yii::getAlias($this->getAliasDirectoryBase() . $this->getFilename());
  423. }
  424. public function isInvoicePrice()
  425. {
  426. return $this->getClass() == 'Invoice' || $this->getClass() == 'DeliveryNote';
  427. }
  428. public function isTaxCalculationMethodSumOfRoundings()
  429. {
  430. return $this->tax_calculation_method == self::TAX_CALCULATION_METHOD_SUM_OF_ROUNDINGS;
  431. }
  432. public function isTaxCalculationMethodRoundingOfTheSum()
  433. {
  434. return $this->tax_calculation_method == self::TAX_CALCULATION_METHOD_ROUNDING_OF_THE_SUM;
  435. }
  436. public function initTaxCalculationMethod()
  437. {
  438. $producerTaxCalculationMethod = Producer::getConfig('option_tax_calculation_method');
  439. if ($producerTaxCalculationMethod) {
  440. $this->tax_calculation_method = $producerTaxCalculationMethod;
  441. } else {
  442. $this->tax_calculation_method = self::TAX_CALCULATION_METHOD_DEFAULT;
  443. }
  444. }
  445. }