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.

1008 lines
37KB

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