您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

542 行
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\Debug;
  39. use common\helpers\GlobalParam;
  40. use common\helpers\Price;
  41. use Yii;
  42. use common\components\ActiveRecordCommon;
  43. /**
  44. * This is the model class for table "product".
  45. *
  46. * @property integer $id
  47. * @property string $name
  48. * @property string $description
  49. * @property integer $active
  50. * @property string $photo
  51. * @property double $price
  52. * @property double $pweight
  53. * @property string $recipe
  54. * @property string $unit
  55. * @property double $step
  56. */
  57. class Product extends ActiveRecordCommon
  58. {
  59. public $total = 0;
  60. public $apply_distributions = true;
  61. public $price_with_tax = 0;
  62. public $wording_unit = '';
  63. public $pointsSale;
  64. public static $unitsArray = [
  65. 'piece' => [
  66. 'unit' => 'piece',
  67. 'wording_unit' => 'la pièce',
  68. 'wording' => 'pièce(s)',
  69. 'wording_short' => 'p.',
  70. 'coefficient' => 1
  71. ],
  72. 'g' => [
  73. 'ref_unit' => 'kg',
  74. 'unit' => 'g',
  75. 'wording_unit' => 'le g',
  76. 'wording' => 'g',
  77. 'wording_short' => 'g',
  78. 'coefficient' => 1000
  79. ],
  80. 'kg' => [
  81. 'unit' => 'kg',
  82. 'wording_unit' => 'le kg',
  83. 'wording' => 'kg',
  84. 'wording_short' => 'kg',
  85. 'coefficient' => 1
  86. ],
  87. 'mL' => [
  88. 'ref_unit' => 'L',
  89. 'unit' => 'mL',
  90. 'wording_unit' => 'le mL',
  91. 'wording' => 'mL',
  92. 'wording_short' => 'mL',
  93. 'coefficient' => 1000
  94. ],
  95. 'L' => [
  96. 'unit' => 'L',
  97. 'wording_unit' => 'le litre',
  98. 'wording' => 'L',
  99. 'wording_short' => 'L',
  100. 'coefficient' => 1
  101. ],
  102. ];
  103. /**
  104. * @inheritdoc
  105. */
  106. public static function tableName()
  107. {
  108. return 'product';
  109. }
  110. /**
  111. * @inheritdoc
  112. */
  113. public function rules()
  114. {
  115. return [
  116. [['name', 'id_producer'], 'required'],
  117. [['active', 'order', 'id_producer', 'id_tax_rate', 'id_product_category'], 'integer'],
  118. [['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'unavailable', 'apply_distributions', 'available_on_points_sale'], 'boolean'],
  119. [['price', 'weight', 'step', 'quantity_max', 'quantity_max_monday', 'quantity_max_tuesday', 'quantity_max_wednesday', 'quantity_max_thursday', 'quantity_max_friday', 'quantity_max_saturday', 'quantity_max_sunday'], 'number'],
  120. [['photo'], 'file'],
  121. [['name', 'reference', 'description', 'photo', 'unit'], 'string', 'max' => 255],
  122. [['recipe'], 'string', 'max' => 1000],
  123. ['step', 'required', 'message' => 'Champs obligatoire', 'when' => function ($model) {
  124. if ($model->unit != 'piece') {
  125. return true;
  126. }
  127. return false;
  128. }],
  129. [['price_with_tax', 'wording_unit', 'pointsSale'], 'safe']
  130. ];
  131. }
  132. /**
  133. * @inheritdoc
  134. */
  135. public function attributeLabels()
  136. {
  137. return [
  138. 'id' => 'ID',
  139. 'name' => 'Nom',
  140. 'reference' => 'Référence',
  141. 'description' => 'Description',
  142. 'active' => 'Actif',
  143. 'photo' => 'Photo',
  144. 'price' => 'Prix (€) TTC',
  145. 'weight' => 'Poids',
  146. 'recipe' => 'Recette',
  147. 'monday' => 'Lundi',
  148. 'tuesday' => 'Mardi',
  149. 'wednesday' => 'Mercredi',
  150. 'thursday' => 'Jeudi',
  151. 'friday' => 'Vendredi',
  152. 'saturday' => 'Samedi',
  153. 'sunday' => 'Dimanche',
  154. 'order' => 'Ordre',
  155. 'quantity_max' => 'Quantité max par défaut',
  156. 'quantity_max_monday' => 'Quantité max : lundi',
  157. 'quantity_max_tuesday' => 'Quantité max : mardi',
  158. 'quantity_max_wednesday' => 'Quantité max : mercredi',
  159. 'quantity_max_thursday' => 'Quantité max : jeudi',
  160. 'quantity_max_friday' => 'Quantité max : vendredi',
  161. 'quantity_max_saturday' => 'Quantité max : samedi',
  162. 'quantity_max_sunday' => 'Quantité max : dimanche',
  163. 'unavailable' => 'Épuisé',
  164. 'apply_distributions' => 'Appliquer ces modifications dans les distributions futures',
  165. 'unit' => 'Unité',
  166. 'step' => 'Pas',
  167. 'id_tax_rate' => 'TVA',
  168. 'id_product_category' => 'Catégorie',
  169. 'available_on_points_sale' => 'Par défaut'
  170. ];
  171. }
  172. public function afterFind()
  173. {
  174. if ($this->taxRate == null) {
  175. $producer = Producer::searchOne(['id' => GlobalParam::getCurrentProducerId()]);
  176. if ($producer) {
  177. $this->populateRelation('taxRate', $producer->taxRate);
  178. }
  179. }
  180. $this->wording_unit = Product::strUnit($this->unit);
  181. $this->price_with_tax = $this->getPriceWithTax();
  182. parent::afterFind();
  183. }
  184. public function getProductDistribution()
  185. {
  186. return $this->hasMany(ProductDistribution::className(), ['id_product' => 'id']);
  187. }
  188. public function getProductSubscription()
  189. {
  190. return $this->hasMany(ProductSubscription::className(), ['id_product' => 'id']);
  191. }
  192. public function getTaxRate()
  193. {
  194. return $this->hasOne(TaxRate::className(), ['id' => 'id_tax_rate']);
  195. }
  196. public function getProductPrice()
  197. {
  198. return $this->hasMany(ProductPrice::className(), ['id_product' => 'id']);
  199. }
  200. public function getProductCategory()
  201. {
  202. return $this->hasOne(ProductCategory::className(), ['id' => 'id_product_category']);
  203. }
  204. public function getProductPointSale()
  205. {
  206. return $this->hasMany(ProductPointSale::className(), ['id_product' => 'id']);
  207. }
  208. /**
  209. * Retourne les options de base nécessaires à la fonction de recherche.
  210. *
  211. * @return array
  212. */
  213. public static function defaultOptionsSearch()
  214. {
  215. return [
  216. 'with' => ['taxRate', 'productPointSale'],
  217. 'join_with' => [],
  218. 'orderby' => 'order ASC',
  219. 'attribute_id_producer' => 'product.id_producer'
  220. ];
  221. }
  222. public function isAvailableOnPointSale($pointSale)
  223. {
  224. // disponible par défaut
  225. if ($this->available_on_points_sale) {
  226. foreach ($this->productPointSale as $productPointSale) {
  227. if ($pointSale->id == $productPointSale->id_point_sale
  228. //&& $productPointSale->id_product == $this->id
  229. && !$productPointSale->available) {
  230. return false;
  231. }
  232. }
  233. return true;
  234. } // indisponible par défaut
  235. else {
  236. foreach ($this->productPointSale as $productPointSale) {
  237. if ($pointSale->id == $productPointSale->id_point_sale
  238. //&& $productPointSale->id_product == $this->id
  239. && $productPointSale->available) {
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. }
  246. /**
  247. * Retourne la description du produit.
  248. *
  249. * @return string
  250. */
  251. public function getDescription()
  252. {
  253. $description = $this->description;
  254. if (isset($this->weight) && is_numeric($this->weight) && $this->weight > 0) {
  255. if ($this->weight >= 1000) {
  256. $description .= ' (' . ($this->weight / 1000) . 'kg)';
  257. } else {
  258. $description .= ' (' . $this->weight . 'g)';
  259. }
  260. }
  261. return $description;
  262. }
  263. /**
  264. * Retourne le libellé (admin) du produit.
  265. * @return type
  266. */
  267. public function getStrWordingAdmin()
  268. {
  269. return $this->name;
  270. }
  271. /**
  272. * Enregistre le produit.
  273. *
  274. * @param boolean $runValidation
  275. * @param array $attributeNames
  276. * @return boolean
  277. */
  278. public function save($runValidation = true, $attributeNames = NULL)
  279. {
  280. $this->id_producer = GlobalParam::getCurrentProducerId();
  281. return parent::save($runValidation, $attributeNames);
  282. }
  283. /**
  284. * Retourne les produits d'une production donnée.
  285. *
  286. * @param integer $idDistribution
  287. * @return array
  288. */
  289. public static function searchByDistribution($idDistribution)
  290. {
  291. return Product::find()
  292. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  293. ->where([
  294. 'id_producer' => GlobalParam::getCurrentProducerId(),
  295. 'product_distribution.id_distribution' => $idDistribution
  296. ])
  297. ->orderBy('product_distribution.active DESC, product.order ASC')
  298. ->all();
  299. }
  300. /**
  301. * Retourne le nombre de produits du producteur courant.
  302. *
  303. * @return integer
  304. */
  305. public static function count()
  306. {
  307. return self::searchCount();
  308. }
  309. /**
  310. * Retourne le produit "Don".
  311. *
  312. * @return Product
  313. */
  314. public static function getProductGift()
  315. {
  316. $productGift = Product::find()
  317. ->where([
  318. 'product.id_producer' => 0
  319. ])
  320. ->andFilterWhere(['like', 'product.name', 'Don'])
  321. ->one();
  322. return $productGift;
  323. }
  324. public function getRefUnit($unit)
  325. {
  326. if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit]['ref_unit'])) {
  327. return self::$unitsArray[$unit]['ref_unit'];
  328. }
  329. return $unit;
  330. }
  331. /**
  332. * Retourne le libellé d'une unité.
  333. *
  334. * @param $format wording_unit, wording, short
  335. * @param $unitInDb Unité stockée en base de données (ex: si g > kg, si mL > L)
  336. * @return $string Libellé de l'unité
  337. */
  338. public static function strUnit($unit, $format = 'wording_short', $unitInDb = false)
  339. {
  340. $strUnit = '';
  341. if ($unitInDb) {
  342. if ($unit == 'g') {
  343. $unit = 'kg';
  344. }
  345. if ($unit == 'mL') {
  346. $unit = 'L';
  347. }
  348. }
  349. if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit][$format])) {
  350. $strUnit = self::$unitsArray[$unit][$format];
  351. }
  352. return $strUnit;
  353. }
  354. public function getPriceArray($user, $pointSale)
  355. {
  356. $priceArray = [];
  357. $userProducer = null;
  358. if ($user) {
  359. $userProducer = UserProducer::searchOne([
  360. 'id_user' => $user->id,
  361. ]);
  362. }
  363. // specific prices
  364. $specificPriceArray = $this->getSpecificPricesFilterByPriorityMatch(
  365. $this->productPrice,
  366. $user,
  367. $pointSale
  368. );
  369. foreach ($specificPriceArray as $specificPrice) {
  370. $priceArray[] = [
  371. 'from_quantity' => $specificPrice->from_quantity ? $specificPrice->from_quantity : 0,
  372. 'price' => $this->getPrice([
  373. 'user' => $user,
  374. 'user_producer' => $userProducer,
  375. 'point_sale' => $pointSale,
  376. 'quantity' => $specificPrice->from_quantity
  377. ]),
  378. 'price_with_tax' => $this->getPriceWithTax([
  379. 'user' => $user,
  380. 'user_producer' => $userProducer,
  381. 'point_sale' => $pointSale,
  382. 'quantity' => $specificPrice->from_quantity
  383. ]),
  384. ];
  385. }
  386. if (!$this->hasPriceWithQuantityZero($priceArray)) {
  387. // base price
  388. $priceArray[] = [
  389. 'from_quantity' => 0,
  390. 'price' => $this->getPrice(),
  391. 'price_with_tax' => $this->getPriceWithTax(),
  392. ];
  393. }
  394. usort($priceArray, function ($a, $b) {
  395. if ($a['price'] < $b['price']) {
  396. return 1;
  397. } elseif ($a['price'] > $b['price']) {
  398. return -1;
  399. } else {
  400. return 0;
  401. }
  402. });
  403. return $priceArray;
  404. }
  405. public function hasPriceWithQuantityZero($priceArray)
  406. {
  407. foreach ($priceArray as $price) {
  408. if ($price['from_quantity'] == 0) {
  409. return true;
  410. }
  411. }
  412. return false;
  413. }
  414. public function getSpecificPricesFilterByPriorityMatch($specificPrices, $user, $pointSale)
  415. {
  416. $priorityMatchSpecificPrice = ProductPrice::getPriorityMatchOfSpecificPriceArray($specificPrices, $user, $pointSale);
  417. $specificPricesFilter = [];
  418. foreach ($specificPrices as $keySpecificPrice => $specificPrice) {
  419. if (($priorityMatchSpecificPrice && $specificPrice->$priorityMatchSpecificPrice($user, $pointSale))
  420. || $specificPrice->matchFromQuantityOnly()) {
  421. $specificPricesFilter[] = $specificPrice;
  422. }
  423. }
  424. return $specificPricesFilter;
  425. }
  426. public function getPrice($params = [])
  427. {
  428. $specificPrices = $this->productPrice;
  429. $user = isset($params['user']) ? $params['user'] : false;
  430. $userProducer = isset($params['user_producer']) ? $params['user_producer'] : false;
  431. $pointSale = isset($params['point_sale']) ? $params['point_sale'] : false;
  432. $quantity = (isset($params['quantity']) && $params['quantity']) ? $params['quantity'] : 1;
  433. if ($specificPrices && ($user || $pointSale)) {
  434. $specificPrices = $this->getSpecificPricesFilterByPriorityMatch($specificPrices, $user, $pointSale);
  435. $bestPrice = 9999;
  436. foreach ($specificPrices as $specificPrice) {
  437. $fromQuantity = $specificPrice->from_quantity;
  438. if ((($fromQuantity && $fromQuantity <= $quantity) || !$fromQuantity)
  439. && $specificPrice->price < $bestPrice) {
  440. $bestPrice = $specificPrice->price;
  441. }
  442. }
  443. if ($bestPrice != 9999) {
  444. return $bestPrice;
  445. }
  446. }
  447. if ($userProducer && $userProducer->product_price_percent) {
  448. return $this->price * (1 + $userProducer->product_price_percent / 100);
  449. }
  450. if ($pointSale && $pointSale->product_price_percent) {
  451. return $this->price * (1 + $pointSale->product_price_percent / 100);
  452. }
  453. return $this->price;
  454. }
  455. /**
  456. * Retourne le prix du produit avec taxe
  457. */
  458. public function getPriceWithTax($params = [])
  459. {
  460. $taxRateValue = $this->taxRate ? $this->taxRate->value : 0;
  461. return Price::getPriceWithTax($this->getPrice($params), $taxRateValue);
  462. }
  463. public function getTheTaxRate()
  464. {
  465. if ($this->id_tax_rate) {
  466. return $this->id_tax_rate;
  467. } else {
  468. return GlobalParam::getCurrentProducer()->taxRate->id;
  469. }
  470. }
  471. public function getNameExport()
  472. {
  473. $producer = GlobalParam::getCurrentProducer();
  474. if ($producer->option_export_display_product_reference && $this->reference && strlen($this->reference) > 0) {
  475. return $this->reference;
  476. }
  477. return $this->name;
  478. }
  479. }