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ů.

974 lines
35KB

  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 Yii;
  39. use common\components\ActiveRecordCommon;
  40. use common\helpers\Departments;
  41. use yii\helpers\Html;
  42. /**
  43. * This is the model class for table "etablissement".
  44. *
  45. * @property integer $id
  46. * @property string $name
  47. * @property string $siret
  48. * @property string $logo
  49. * @property string $photo
  50. * @property string $description
  51. * @property string $postcode
  52. * @property string $city
  53. * @property float credit_limit_reminder
  54. * @property boolean online_payment
  55. * @property string mentions
  56. * @property string gcs
  57. * @property boolean option_allow_user_gift
  58. * @property string credit_functioning
  59. * @property boolean use_credit_checked_default
  60. * @property float credit_limit
  61. * @property string background_color_logo
  62. *
  63. */
  64. class Producer extends ActiveRecordCommon
  65. {
  66. const CREDIT_FUNCTIONING_MANDATORY = 'mandatory';
  67. const CREDIT_FUNCTIONING_OPTIONAL = 'optional';
  68. const CREDIT_FUNCTIONING_USER = 'user';
  69. const HINT_CREDIT_FUNCTIONING = '<ul>'
  70. . '<li>Optionnelle : l\'utilisateur choisit s\'il utilise son Crédit ou non. Les commandes peuvent être payées ou impayées.</li>'
  71. . '<li>Obligatoire : toutes les commandes de l\'utilisateur son comptabilisées au niveau du Crédit. Toutes les commandes sont payées.</li>'
  72. . '<li>Basée sur l\'utilisateur : Crédit obligatoire si l\'utilisateur a le crédit activé au niveau de son compte, système de Crédit non affiché sinon.</li>'
  73. . '</ul>';
  74. public static $creditFunctioningArray = [
  75. self::CREDIT_FUNCTIONING_MANDATORY => 'Obligatoire',
  76. self::CREDIT_FUNCTIONING_OPTIONAL => 'Optionnelle',
  77. self::CREDIT_FUNCTIONING_USER => 'Basée sur l\'utilisateur',
  78. ];
  79. const BEHAVIOR_DELETE_ORDER_DELETE = 'delete';
  80. const BEHAVIOR_DELETE_ORDER_STATUS = 'status';
  81. const BEHAVIOR_HOME_POINT_SALE_DAY_LIST_WEEK = 'days-of-week';
  82. const BEHAVIOR_HOME_POINT_SALE_DAY_LIST_INCOMING_DISTRIBUTIONS = 'incoming-distributions';
  83. const BEHAVIOR_ORDER_SELECT_DISTRIBUTION_CALENDAR = 'calendar';
  84. const BEHAVIOR_ORDER_SELECT_DISTRIBUTION_LIST = 'list';
  85. const ORDER_REFERENCE_TYPE_NONE = '';
  86. const ORDER_REFERENCE_TYPE_YEARLY = 'yearly';
  87. const ORDER_ENTRY_POINT_DATE = 'date';
  88. const ORDER_ENTRY_POINT_POINT_SALE = 'point-sale';
  89. const BILLING_FREQUENCY_MONTHLY = 'monthly';
  90. const BILLING_FREQUENCY_QUARTERLY = 'quarterly';
  91. const BILLING_FREQUENCY_BIANNUAL = 'biannual';
  92. public static $billingFrequencyArray = [
  93. self::BILLING_FREQUENCY_MONTHLY => 'Mensuelle',
  94. self::BILLING_FREQUENCY_QUARTERLY => 'Trimestrielle',
  95. self::BILLING_FREQUENCY_BIANNUAL => 'Biannuelle',
  96. ];
  97. const BILLING_TYPE_CLASSIC = 'classic';
  98. const BILLING_TYPE_FREE_PRICE = 'free-price';
  99. public static $billingTypeArray = [
  100. self::BILLING_TYPE_CLASSIC => 'Classique',
  101. self::BILLING_TYPE_FREE_PRICE => 'Prix libre',
  102. ];
  103. var $secret_key_payplug;
  104. /**
  105. * @inheritdoc
  106. */
  107. public static function tableName()
  108. {
  109. return 'producer';
  110. }
  111. /**
  112. * @inheritdoc
  113. */
  114. public function rules()
  115. {
  116. return [
  117. [['name', 'type', 'id_tax_rate_default'], 'required'],
  118. [
  119. ['tiller_provider_token', 'tiller_restaurant_token'],
  120. 'required',
  121. 'when' => function ($model) {
  122. return $model->tiller == true;
  123. }
  124. ],
  125. [
  126. [
  127. 'order_delay',
  128. 'order_deadline',
  129. 'order_delay_monday',
  130. 'order_deadline_monday',
  131. 'order_delay_tuesday',
  132. 'order_deadline_tuesday',
  133. 'order_delay_wednesday',
  134. 'order_deadline_wednesday',
  135. 'order_delay_thursday',
  136. 'order_deadline_thursday',
  137. 'order_delay_friday',
  138. 'order_deadline_friday',
  139. 'order_delay_saturday',
  140. 'order_deadline_saturday',
  141. 'order_delay_sunday',
  142. 'order_deadline_sunday',
  143. 'id_tax_rate_default',
  144. 'document_quotation_duration',
  145. 'option_dashboard_number_distributions'
  146. ],
  147. 'integer'
  148. ],
  149. [
  150. [
  151. 'order_deadline',
  152. 'order_deadline_monday',
  153. 'order_deadline_tuesday',
  154. 'order_deadline_wednesday',
  155. 'order_deadline_thursday',
  156. 'order_deadline_friday',
  157. 'order_deadline_saturday',
  158. 'order_deadline_sunday',
  159. ],
  160. 'in',
  161. 'range' => [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
  162. ],
  163. ['order_delay', 'in', 'range' => [1, 2, 3, 4, 5, 6, 7]],
  164. [
  165. 'code',
  166. function ($attribute, $params) {
  167. $code = $this->$attribute;
  168. $producer = Producer::findOne(['code' => $code]);
  169. if ($producer && $producer->id != $this->id) {
  170. $this->addError($attribute, 'Ce code est déjà utilisé par un autre producteur.');
  171. }
  172. }
  173. ],
  174. [
  175. ['document_quotation_prefix', 'document_invoice_prefix', 'document_delivery_note_prefix'],
  176. function ($attribute, $params) {
  177. if (!ctype_upper($this->$attribute)) {
  178. $this->addError($attribute, 'Ne doit contenir que des majuscules');
  179. }
  180. }
  181. ],
  182. [
  183. [
  184. 'description',
  185. 'mentions',
  186. 'gcs',
  187. 'order_infos',
  188. 'slug',
  189. 'secret_key_payplug',
  190. 'background_color_logo',
  191. 'option_behavior_cancel_order',
  192. 'tiller_provider_token',
  193. 'tiller_restaurant_token',
  194. 'status',
  195. 'document_infos_bottom',
  196. 'document_infos_quotation',
  197. 'document_infos_invoice',
  198. 'document_infos_delivery_note',
  199. 'address',
  200. 'behavior_home_point_sale_day_list',
  201. 'behavior_order_select_distribution',
  202. 'option_payment_info',
  203. 'option_order_reference_type',
  204. 'option_order_entry_point',
  205. 'option_stripe_public_key',
  206. 'option_stripe_private_key',
  207. 'option_stripe_endpoint_secret',
  208. 'option_online_payment_type',
  209. 'option_tax_calculation_method'
  210. ],
  211. 'string'
  212. ],
  213. [
  214. [
  215. 'negative_balance',
  216. 'credit',
  217. 'active',
  218. 'online_payment',
  219. 'user_manage_subscription',
  220. 'option_allow_user_gift',
  221. 'use_credit_checked_default',
  222. 'tiller',
  223. 'document_display_orders_invoice',
  224. 'document_display_orders_delivery_note',
  225. 'document_display_prices_delivery_note',
  226. 'document_display_product_description',
  227. 'option_email_confirm',
  228. 'option_email_confirm_producer',
  229. 'option_csv_export_all_products',
  230. 'option_csv_export_by_piece',
  231. 'option_export_display_product_reference',
  232. 'option_allow_order_guest',
  233. 'option_delivery',
  234. 'option_display_export_grid',
  235. 'option_stripe_mode_test',
  236. 'option_notify_producer_order_summary',
  237. 'option_billing_reduction',
  238. 'option_export_evoliz'
  239. ],
  240. 'boolean'
  241. ],
  242. [
  243. [
  244. 'name',
  245. 'siret',
  246. 'logo',
  247. 'photo',
  248. 'postcode',
  249. 'city',
  250. 'code',
  251. 'type',
  252. 'credit_functioning',
  253. 'option_behavior_cancel_order',
  254. 'document_quotation_prefix',
  255. 'document_quotation_first_reference',
  256. 'document_invoice_prefix',
  257. 'document_invoice_first_reference',
  258. 'document_delivery_note_prefix',
  259. 'document_delivery_note_first_reference',
  260. 'option_billing_type',
  261. 'option_billing_frequency',
  262. ],
  263. 'string',
  264. 'max' => 255
  265. ],
  266. [['free_price', 'credit_limit_reminder', 'credit_limit'], 'double'],
  267. [
  268. 'free_price',
  269. 'compare',
  270. 'compareValue' => 0,
  271. 'operator' => '>=',
  272. 'type' => 'number',
  273. 'message' => 'Prix libre doit être supérieur ou égal à 0'
  274. ],
  275. [['option_dashboard_date_start', 'option_dashboard_date_end'], 'safe'],
  276. ];
  277. }
  278. /**
  279. * @inheritdoc
  280. */
  281. public function attributeLabels()
  282. {
  283. return [
  284. 'id' => 'ID',
  285. 'name' => 'Nom',
  286. 'siret' => 'Siret',
  287. 'logo' => 'Logo',
  288. 'photo' => 'Photo',
  289. 'description' => 'Description',
  290. 'postcode' => 'Code postal',
  291. 'city' => 'Ville',
  292. 'code' => 'Code',
  293. 'order_delay' => 'Délai de commande',
  294. 'order_deadline' => 'Heure limite de commande',
  295. 'order_delay_monday' => 'Délai de commande (lundi)',
  296. 'order_deadline_monday' => 'Heure limite de commande (lundi)',
  297. 'order_delay_tuesday' => 'Délai de commande (mardi)',
  298. 'order_deadline_tuesday' => 'Heure limite de commande (mardi)',
  299. 'order_delay_wednesday' => 'Délai de commande (mercredi)',
  300. 'order_deadline_wednesday' => 'Heure limite de commande (mercredi)',
  301. 'order_delay_thursday' => 'Délai de commande (jeudi)',
  302. 'order_deadline_thursday' => 'Heure limite de commande (jeudi)',
  303. 'order_delay_friday' => 'Délai de commande (vendredi)',
  304. 'order_deadline_friday' => 'Heure limite de commande (vendredi)',
  305. 'order_delay_saturday' => 'Délai de commande (samedi)',
  306. 'order_deadline_saturday' => 'Heure limite de commande (samedi)',
  307. 'order_delay_sunday' => 'Délai de commande (dimanche)',
  308. 'order_deadline_sunday' => 'Heure limite de commande (dimanche)',
  309. 'negative_balance' => 'Solde négatif',
  310. 'credit' => 'Crédit pain',
  311. 'active' => 'Actif',
  312. 'date_creation' => 'Date de création',
  313. 'order_infos' => 'Informations',
  314. 'slug' => 'Slug',
  315. 'type' => 'Type de producteur',
  316. 'credit_limit_reminder' => 'Seuil de crédit limite avant relance',
  317. 'online_payment' => 'Activer le paiement en ligne (Stripe)',
  318. 'option_online_payment_type' => 'Type de paiement',
  319. 'option_stripe_mode_test' => 'Mode test',
  320. 'option_stripe_public_key' => 'Clé publique',
  321. 'option_stripe_private_key' => 'Clé secrète',
  322. 'option_stripe_endpoint_secret' => 'Clé secrète (endpoint)',
  323. 'user_manage_subscription' => 'Autoriser les utilisateurs à gérer leurs abonnements',
  324. 'mentions' => 'Mentions légales',
  325. 'gcs' => 'Conditions générales de vente',
  326. 'option_allow_user_gift' => 'Autoriser les utilisateurs à effectuer un don à la plateforme lors de leur commande',
  327. 'credit_functioning' => 'Utilisation du Crédit par l\'utilisateur',
  328. 'credit_limit' => 'Crédit limite',
  329. 'use_credit_checked_default' => 'Cocher par défaut l\'option "Utiliser mon crédit" lors de la commande de l\'utilisateur',
  330. 'background_color_logo' => 'Couleur de fond du logo',
  331. 'option_behavior_cancel_order' => 'Comportement lors de la suppression d\'une commande',
  332. 'tiller' => 'Tiller',
  333. 'tiller_provider_token' => 'Token provider',
  334. 'tiller_restaurant_token' => 'Token restaurant',
  335. 'status' => 'Statut',
  336. 'id_tax_rate_default' => 'Taxe',
  337. 'document_quotation_prefix' => 'Préfixe des devis',
  338. 'document_quotation_first_reference' => 'Première référence des devis',
  339. 'document_quotation_duration' => 'Durée du devis',
  340. 'document_invoice_prefix' => 'Préfixe des factures',
  341. 'document_invoice_first_reference' => 'Première référence des factures',
  342. 'document_delivery_note_prefix' => 'Préfixe des bons de livraison',
  343. 'document_delivery_note_first_reference' => 'Première référence des bons de livraison',
  344. 'document_infos_bottom' => 'Informations affichées en bas des documents',
  345. 'document_infos_quotation' => 'Informations affichées en bas des devis',
  346. 'document_infos_invoice' => 'Informations affichées en bas des factures',
  347. 'document_infos_delivery_note' => 'Informations affichées en bas des bons de livraison',
  348. 'address' => 'Adresse',
  349. 'document_display_orders_invoice' => 'Afficher le détail des commandes dans les factures',
  350. 'document_display_orders_delivery_note' => 'Afficher le détail des commandes dans les bons de livraison',
  351. 'document_display_prices_delivery_note' => 'Afficher le chiffrage dans les bons de livraison',
  352. 'behavior_home_point_sale_day_list' => 'Accueil : affichage des jours de distribution',
  353. 'behavior_order_select_distribution' => 'Sélection de la date de distribution',
  354. 'option_payment_info' => 'Informations liées au paiement',
  355. 'option_email_confirm' => 'Envoyer un email de confirmation au client',
  356. 'option_email_confirm_producer' => 'Envoyer un email de confirmation au producteur',
  357. 'option_dashboard_number_distributions' => 'Nombre de distributions affichées sur le tableau de board',
  358. 'option_dashboard_date_start' => 'Date de début',
  359. 'option_dashboard_date_end' => 'Date de fin',
  360. 'option_csv_export_all_products' => 'Exporter tous les produits dans le fichier récapitulatif (CSV)',
  361. 'option_csv_export_by_piece' => 'Exporter les produits par pièce dans le fichier récapitulatif (CSV)',
  362. 'option_order_reference_type' => 'Type de référence',
  363. 'option_export_display_product_reference' => 'Afficher la référence des produits au moment de l\'export',
  364. 'option_allow_order_guest' => 'Autoriser les visiteurs à passer commande (création de compte à la fin du tunnel)',
  365. 'option_order_entry_point' => 'Point d\'entrée par point de vente ou par date',
  366. 'option_delivery' => 'Proposer la livraison à domicile',
  367. 'option_display_export_grid' => 'Afficher l\'export grille dans les distributions',
  368. 'document_display_product_description' => 'Documents : afficher la description des produits',
  369. 'option_notify_producer_order_summary' => 'Recevoir les récapitulatifs de commande par email',
  370. 'option_billing_type' => 'Type de facturation',
  371. 'option_billing_frequency' => 'Fréquence de facturation',
  372. 'option_billing_reduction' => 'Réduction appliquée au moment de la facturation',
  373. 'option_tax_calculation_method' => 'Méthode de calcul de la TVA',
  374. 'option_export_evoliz' => 'Activer l\'export vers Evoliz'
  375. ];
  376. }
  377. /*
  378. * Relations
  379. */
  380. public function getUserProducer()
  381. {
  382. return $this->hasMany(
  383. UserProducer::className(),
  384. ['id_producer' => 'id']
  385. );
  386. }
  387. public function getUser()
  388. {
  389. return $this->hasMany(User::className(), ['id_producer' => 'id']);
  390. }
  391. public function getContact()
  392. {
  393. return $this->hasMany(User::className(), ['id_producer' => 'id'])
  394. ->where(['status' => User::STATUS_PRODUCER]);
  395. }
  396. public function getTaxRate()
  397. {
  398. return $this->hasOne(TaxRate::className(), ['id' => 'id_tax_rate_default']);
  399. }
  400. /**
  401. * Retourne les options de base nécessaires à la fonction de recherche.
  402. *
  403. * @return array
  404. */
  405. public static function defaultOptionsSearch()
  406. {
  407. return [
  408. 'with' => ['taxRate'],
  409. 'join_with' => [],
  410. 'orderby' => 'name ASC',
  411. 'attribute_id_producer' => 'id'
  412. ];
  413. }
  414. /**
  415. * Retourne la liste des établissements pour l'initialisation d'une liste
  416. * sélective.
  417. *
  418. * @return array
  419. */
  420. public static function getProducerPopulateDropdown()
  421. {
  422. $producers = Producer::find()
  423. ->where([
  424. 'active' => true,
  425. ])
  426. ->orderBy('postcode, city ASC')
  427. ->all();
  428. $departments = Departments::get();
  429. $dataProducers = [];
  430. $optionsProducers = [];
  431. foreach ($producers as $p) {
  432. $departmentCode = substr($p->postcode, 0, 2);
  433. if (!key_exists('d' . $departmentCode, $dataProducers) && isset($departments[$departmentCode])) {
  434. $dataProducers['d' . $departmentCode] = '<strong>' . $departments[$departmentCode] . '</strong>';
  435. $optionsProducers['d' . $departmentCode] = ['disabled' => true];
  436. }
  437. $dataProducers[$p->id] = '<span class="glyphicon glyphicon-lock"></span> ' . Html::encode(
  438. $p->name
  439. ) . ' - ' . Html::encode($p->postcode) . ' ' . Html::encode(
  440. $p->city
  441. ) . ' <span class="glyphicon glyphicon-lock"></span>';
  442. if (strlen($p->code)) {
  443. $optionsProducers[$p->id] = ['class' => 'lock'];
  444. }
  445. }
  446. return ['data' => $dataProducers, 'options' => $optionsProducers];
  447. }
  448. /**
  449. * Retourne le CA de l'établissement pour un mois donné.
  450. *
  451. * @param string $period
  452. * @param boolean $format
  453. * @return string
  454. */
  455. public function getTurnover($period = '', $format = false)
  456. {
  457. if (!$period) {
  458. $period = date('Y-m');
  459. }
  460. $connection = Yii::$app->getDb();
  461. $command = $connection->createCommand(
  462. '
  463. SELECT SUM(product_order.price * product_order.quantity) AS turnover
  464. FROM `order`, product_order, distribution, product
  465. WHERE `order`.id = product_order.id_order
  466. AND distribution.id_producer = :id_producer
  467. AND `order`.id_distribution = distribution.id
  468. AND product_order.id_product = product.id
  469. AND distribution.date > :date_begin
  470. AND distribution.date < :date_end',
  471. [
  472. ':date_begin' => date('Y-m-31', strtotime("-1 month", strtotime($period))),
  473. ':date_end' => date('Y-m-01', strtotime("+1 month", strtotime($period))),
  474. ':id_producer' => $this->id
  475. ]
  476. );
  477. $result = $command->queryOne();
  478. $turnover = $result['turnover'];
  479. if ($format) {
  480. return number_format($turnover, 2) . ' €';
  481. } else {
  482. return $turnover;
  483. }
  484. }
  485. public function getAmountToBeBilledByTurnover($turnover, $format = false)
  486. {
  487. $amountToBeBilled = 0;
  488. $producerPriceRangeArray = ProducerPriceRange::find()->all();
  489. foreach($producerPriceRangeArray as $priceRange) {
  490. if($turnover >= $priceRange->range_begin && $turnover < $priceRange->range_end) {
  491. $amountToBeBilled = $priceRange->price;
  492. }
  493. }
  494. if($format) {
  495. return Price::format($amountToBeBilled);
  496. }
  497. else {
  498. return $amountToBeBilled;
  499. }
  500. }
  501. public function getAmountToBeBilledByMonth($month, $format = false)
  502. {
  503. $turnover = $this->getTurnover($month);
  504. return $this->getAmountToBeBilledByTurnover($turnover, $format);
  505. }
  506. public function getSummaryAmountsToBeBilled($label, $numberOfMonths = 1)
  507. {
  508. $text = '';
  509. $numMonthCurrent = date('m');
  510. if($numberOfMonths == 1
  511. || ($numberOfMonths == 3 && (in_array($numMonthCurrent, [1, 4, 7, 10])))
  512. || ($numberOfMonths == 6 && (in_array($numMonthCurrent, [1, 7])))) {
  513. for ($i = 1; $i <= $numberOfMonths; $i++) {
  514. $month = date('Y-m', strtotime('-' . $i . ' month'));
  515. $turnover = $this->getTurnover($month);
  516. if ($turnover) {
  517. if ($this->isBillingTypeClassic()) {
  518. $text .= '<strong>';
  519. }
  520. $text .= $this->getAmountToBeBilledByTurnover($turnover, true);
  521. if ($this->isBillingTypeClassic()) {
  522. $text .= '</strong>';
  523. }
  524. $text .= ' / '.Price::format($turnover);
  525. $text .= '<br />';
  526. }
  527. }
  528. if (strlen($text)) {
  529. $text = $label . ' : <br />' . $text;
  530. }
  531. }
  532. return $text;
  533. }
  534. public function getAmountBilledLastMonth()
  535. {
  536. if($this->isBillingTypeClassic()) {
  537. $month = date('Y-m', strtotime('-1 month'));
  538. return $this->getAmountToBeBilledByMonth($month);
  539. }
  540. elseif($this->isBillingTypeFreePrice()) {
  541. return $this->free_price;
  542. }
  543. return 0;
  544. }
  545. /**
  546. * Retourne le montant à facturer pour une période donnée.
  547. *
  548. * @param string $periode
  549. * @param float $ca
  550. * @param boolean $format
  551. * @return string
  552. */
  553. public function getMAmountBilled($format = false)
  554. {
  555. if ($format) {
  556. return number_format($this->free_price, 2) . ' €';
  557. } else {
  558. return $this->free_price;
  559. }
  560. }
  561. /**
  562. * Retourne la facture d'une période donnée.
  563. *
  564. * @param string $periode
  565. * @return Facture
  566. */
  567. public function getInvoice($period = '')
  568. {
  569. if (!$period) {
  570. $period = date('Y-m', strtotime('-1 month'));
  571. }
  572. $invoice = Invoice::searchOne(
  573. ['id_producer' => $this->id, 'period' => ':period'],
  574. ['params' => [':period' => $period]]
  575. );
  576. return $invoice;
  577. }
  578. /**
  579. * Retourne la facture du mois dernier.
  580. *
  581. * @return Facture
  582. */
  583. public function getInvoiceLastMonth()
  584. {
  585. return $this->getInvoice(date('Y-m', strtotime('-1 month')));
  586. }
  587. /**
  588. * Retourne une configuration d'un établissement donné.
  589. *
  590. * @param string $config
  591. * @param integer $id_etablissement
  592. * @return mixed
  593. */
  594. public static function getConfig($config = '', $idProducer = 0)
  595. {
  596. if (strlen($config)) {
  597. if (!$idProducer) {
  598. $idProducer = GlobalParam::getCurrentProducerId();
  599. }
  600. $producer = self::findOne($idProducer);
  601. if ($producer) {
  602. return $producer->$config;
  603. }
  604. }
  605. return false;
  606. }
  607. /**
  608. * Retourne le montant de l'abonnement à prix libre définit par
  609. * le producteur.
  610. *
  611. * @param boolean $format
  612. * @return mixed
  613. */
  614. public function getFreePrice($format = true)
  615. {
  616. if (!is_null($this->free_price)) {
  617. if ($format) {
  618. return number_format($this->free_price, 2, ',', false) . ' €';
  619. } else {
  620. return $this->free_price;
  621. }
  622. }
  623. }
  624. /**
  625. * Lie un utilisateur à un producteur.
  626. *
  627. * @param integer $id_user
  628. * @param integer $id_producer
  629. * @return UserProducer
  630. */
  631. public static function addUser($idUser, $idProducer, $bookmark = 1)
  632. {
  633. $userProducer = UserProducer::searchOne([
  634. 'user_producer.id_user' => $idUser,
  635. 'user_producer.id_producer' => $idProducer
  636. ]);
  637. if (!$userProducer) {
  638. $newUserProducer = new UserProducer;
  639. $newUserProducer->id_producer = $idProducer;
  640. $newUserProducer->id_user = $idUser;
  641. $newUserProducer->credit = 0;
  642. $newUserProducer->active = 1;
  643. $newUserProducer->bookmark = (int)$bookmark;
  644. $newUserProducer->save();
  645. } else {
  646. if (!$userProducer->active) {
  647. $userProducer->active = 1;
  648. $userProducer->save();
  649. }
  650. }
  651. return $userProducer;
  652. }
  653. public function getSpecificDelays()
  654. {
  655. $array = [];
  656. $daysArray = [
  657. 'monday',
  658. 'tuesday',
  659. 'wednesday',
  660. 'thursday',
  661. 'friday',
  662. 'saturday',
  663. 'sunday'
  664. ];
  665. foreach ($daysArray as $day) {
  666. $fieldDelay = 'order_delay_' . $day;
  667. $fieldDeadline = 'order_deadline_' . $day;
  668. $delay = $this->order_delay;
  669. $deadline = $this->order_deadline;
  670. if ($this->$fieldDelay) {
  671. $delay = $this->$fieldDelay;
  672. }
  673. if ($this->$fieldDeadline) {
  674. $deadline = $this->$fieldDeadline;
  675. }
  676. $array[$day] = [
  677. 'order_delay' => $delay,
  678. 'order_deadline' => $deadline,
  679. ];
  680. }
  681. return $array;
  682. }
  683. public function hasSpecificDelays()
  684. {
  685. $daysArray = [
  686. 'monday',
  687. 'tuesday',
  688. 'wednesday',
  689. 'thursday',
  690. 'friday',
  691. 'saturday',
  692. 'sunday'
  693. ];
  694. foreach ($daysArray as $day) {
  695. $fieldDelay = 'order_delay_' . $day;
  696. $fieldDeadline = 'order_deadline_' . $day;
  697. if ($this->$fieldDelay || $this->$fieldDeadline) {
  698. return true;
  699. }
  700. }
  701. return false;
  702. }
  703. /**
  704. * Retourne le chemin vers le fichier contenant la clé secrète d'API de Stripe
  705. *
  706. * @return string
  707. */
  708. public function getFilenamePrivateKeyApiStripe()
  709. {
  710. return '../../common/config/stripe/api-' . $this->id . '.key';
  711. }
  712. public function getFilenamePrivateKeyEndpointStripe()
  713. {
  714. return '../../common/config/stripe/endpoint-' . $this->id . '.key';
  715. }
  716. public function savePrivateKeyStripe($filename, $value)
  717. {
  718. if (strlen($value) > 0) {
  719. $handle = fopen($filename, "w");
  720. fwrite($handle, $value);
  721. fclose($handle);
  722. }
  723. }
  724. public function savePrivateKeyApiStripe()
  725. {
  726. $this->savePrivateKeyStripe(
  727. $this->getFilenamePrivateKeyApiStripe(),
  728. $this->option_stripe_private_key
  729. );
  730. }
  731. public function savePrivateKeyEndpointStripe()
  732. {
  733. $this->savePrivateKeyStripe(
  734. $this->getFilenamePrivateKeyEndpointStripe(),
  735. $this->option_stripe_endpoint_secret
  736. );
  737. }
  738. /**
  739. * Retourne la clé secrète d'API de Stripe.
  740. *
  741. * @return string
  742. */
  743. public function getPrivateKeyStripe($filename)
  744. {
  745. if (file_exists($filename)) {
  746. $handle = fopen($filename, "r");
  747. $filesize = filesize($filename);
  748. if ($handle && $filesize) {
  749. $secretKey = fread($handle, $filesize);
  750. fclose($handle);
  751. return $secretKey;
  752. }
  753. }
  754. return '';
  755. }
  756. public function getPrivateKeyApiStripe()
  757. {
  758. return $this->getPrivateKeyStripe($this->getFilenamePrivateKeyApiStripe());
  759. }
  760. public function getPrivateKeyEndpointStripe()
  761. {
  762. return $this->getPrivateKeyStripe($this->getFilenamePrivateKeyEndpointStripe());
  763. }
  764. /**
  765. * Retourne le compte producteur de démonstration.
  766. *
  767. * @return Producer
  768. */
  769. public static function getDemoAccount()
  770. {
  771. $producer = Producer::find()->where('name LIKE \'Démo\'')->one();
  772. return $producer;
  773. }
  774. /**
  775. * Retourne true si le compte est un compte de démo.
  776. *
  777. * @return boolean
  778. */
  779. public function isDemo()
  780. {
  781. if (strpos($this->name, 'Démo') !== false) {
  782. return true;
  783. }
  784. return false;
  785. }
  786. public function getFullAddress($nl2br = false)
  787. {
  788. $address = '';
  789. $address .= $this->name . "\n";
  790. if (strlen($this->address)) {
  791. $address .= $this->address . "\n";
  792. }
  793. if (strlen($this->postcode) || strlen($this->city)) {
  794. $address .= $this->postcode . ' ' . $this->city;
  795. }
  796. if ($nl2br) {
  797. $address = nl2br($address);
  798. }
  799. return $address;
  800. }
  801. public function getHtmlLogo()
  802. {
  803. $html = '';
  804. if (strlen($this->logo)) {
  805. $html = '<img src="' . $this->getUrlLogo() . '" class="producer-logo" />';
  806. }
  807. return $html;
  808. }
  809. public function getUrlLogo()
  810. {
  811. return Yii::$app->urlManagerProducer->getHostInfo(
  812. ) . '/' . Yii::$app->urlManagerProducer->baseUrl . '/uploads/' . $this->logo;
  813. }
  814. public function getEmailOpendistrib()
  815. {
  816. return $this->slug . '@opendistrib.net';
  817. }
  818. public function getMainContact()
  819. {
  820. if ($this->contact) {
  821. foreach ($this->contact as $contact) {
  822. if ($contact->is_main_contact) {
  823. return $contact;
  824. }
  825. }
  826. }
  827. return false;
  828. }
  829. public function isOnlinePaymentActive()
  830. {
  831. return $this->online_payment || ($this->option_stripe_mode_test && !Yii::$app->user->isGuest && Yii::$app->user->identity->status > 10);
  832. }
  833. public function isOnlinePaymentActiveAndTypeOrder()
  834. {
  835. return $this->isOnlinePaymentActive() && $this->option_online_payment_type == 'order' ;
  836. }
  837. public static function getBillingFrequencyPopulateDropdown()
  838. {
  839. return self::$billingFrequencyArray;
  840. }
  841. public function isBillingFrequencyMonthly()
  842. {
  843. return $this->option_billing_frequency == self::BILLING_FREQUENCY_MONTHLY;
  844. }
  845. public function isBillingFrequencyQuarterly()
  846. {
  847. return $this->option_billing_frequency == self::BILLING_FREQUENCY_QUARTERLY;
  848. }
  849. public function isBillingFrequencyBiannual()
  850. {
  851. return $this->option_billing_frequency == self::BILLING_FREQUENCY_BIANNUAL;
  852. }
  853. public static function getBillingTypePopulateDropdown()
  854. {
  855. return self::$billingTypeArray;
  856. }
  857. public function isBillingTypeClassic()
  858. {
  859. return $this->option_billing_type == self::BILLING_TYPE_CLASSIC;
  860. }
  861. public function isBillingTypeFreePrice()
  862. {
  863. return $this->option_billing_type == self::BILLING_TYPE_FREE_PRICE;
  864. }
  865. }