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

437 行
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 static $unitsArray = [
  64. 'piece' => [
  65. 'unit' => 'piece',
  66. 'wording_unit' => 'la pièce',
  67. 'wording' => 'pièce(s)',
  68. 'wording_short' => 'p.',
  69. 'coefficient' => 1
  70. ],
  71. 'g' => [
  72. 'unit' => 'g',
  73. 'wording_unit' => 'le g',
  74. 'wording' => 'g',
  75. 'wording_short' => 'g',
  76. 'coefficient' => 1000
  77. ],
  78. 'kg' => [
  79. 'unit' => 'kg',
  80. 'wording_unit' => 'le kg',
  81. 'wording' => 'kg',
  82. 'wording_short' => 'kg',
  83. 'coefficient' => 1
  84. ],
  85. 'mL' => [
  86. 'unit' => 'mL',
  87. 'wording_unit' => 'le mL',
  88. 'wording' => 'mL',
  89. 'wording_short' => 'mL',
  90. 'coefficient' => 1000
  91. ],
  92. 'L' => [
  93. 'unit' => 'L',
  94. 'wording_unit' => 'le litre',
  95. 'wording' => 'L',
  96. 'wording_short' => 'L',
  97. 'coefficient' => 1
  98. ],
  99. ];
  100. /**
  101. * @inheritdoc
  102. */
  103. public static function tableName()
  104. {
  105. return 'product';
  106. }
  107. /**
  108. * @inheritdoc
  109. */
  110. public function rules()
  111. {
  112. return [
  113. [['name', 'id_producer'], 'required'],
  114. [['active', 'order', 'id_producer', 'id_tax_rate'], 'integer'],
  115. [['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'unavailable', 'apply_distributions'], 'boolean'],
  116. [['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'],
  117. [['photo'], 'file'],
  118. [['name', 'description', 'photo', 'unit'], 'string', 'max' => 255],
  119. [['recipe'], 'string', 'max' => 1000],
  120. ['step', 'required', 'message' => 'Champs obligatoire', 'when' => function ($model) {
  121. if ($model->unit != 'piece') {
  122. return true;
  123. }
  124. return false;
  125. }],
  126. [['price_with_tax', 'wording_unit'], 'safe']
  127. ];
  128. }
  129. /**
  130. * @inheritdoc
  131. */
  132. public function attributeLabels()
  133. {
  134. return [
  135. 'id' => 'ID',
  136. 'name' => 'Nom',
  137. 'description' => 'Description',
  138. 'active' => 'Actif',
  139. 'photo' => 'Photo',
  140. 'price' => 'Prix (€) TTC',
  141. 'price' => 'Prix (€) TTC',
  142. 'weight' => 'Poids',
  143. 'recipe' => 'Recette',
  144. 'monday' => 'Lundi',
  145. 'tuesday' => 'Mardi',
  146. 'wednesday' => 'Mercredi',
  147. 'thursday' => 'Jeudi',
  148. 'friday' => 'Vendredi',
  149. 'saturday' => 'Samedi',
  150. 'sunday' => 'Dimanche',
  151. 'order' => 'Ordre',
  152. 'quantity_max' => 'Quantité max par défaut',
  153. 'quantity_max_monday' => 'Quantité max : lundi',
  154. 'quantity_max_tuesday' => 'Quantité max : mardi',
  155. 'quantity_max_wednesday' => 'Quantité max : mercredi',
  156. 'quantity_max_thursday' => 'Quantité max : jeudi',
  157. 'quantity_max_friday' => 'Quantité max : vendredi',
  158. 'quantity_max_saturday' => 'Quantité max : samedi',
  159. 'quantity_max_sunday' => 'Quantité max : dimanche',
  160. 'unavailable' => 'Épuisé',
  161. 'apply_distributions' => 'Appliquer ces modifications dans les distributions futures',
  162. 'unit' => 'Unité',
  163. 'step' => 'Pas',
  164. 'id_tax_rate' => 'TVA'
  165. ];
  166. }
  167. public function afterFind() {
  168. if ($this->taxRate == null) {
  169. $producer = Producer::searchOne(['id' => GlobalParam::getCurrentProducerId()]) ;
  170. if($producer) {
  171. $this->populateRelation('taxRate', $producer->taxRate);
  172. }
  173. }
  174. $this->wording_unit = Product::strUnit($this->unit) ;
  175. $this->price_with_tax = $this->getPriceWithTax() ;
  176. parent::afterFind();
  177. }
  178. public function getProductDistribution()
  179. {
  180. return $this->hasMany(ProductDistribution::className(), ['id_product' => 'id']);
  181. }
  182. public function getProductSubscription()
  183. {
  184. return $this->hasMany(ProductSubscription::className(), ['id_product' => 'id']);
  185. }
  186. public function getTaxRate()
  187. {
  188. return $this->hasOne(TaxRate::className(), ['id' => 'id_tax_rate']);
  189. }
  190. public function getProductPrice()
  191. {
  192. return $this->hasMany(ProductPrice::className(), ['id_product' => 'id']);
  193. }
  194. /**
  195. * Retourne les options de base nécessaires à la fonction de recherche.
  196. *
  197. * @return array
  198. */
  199. public static function defaultOptionsSearch()
  200. {
  201. return [
  202. 'with' => ['taxRate'],
  203. 'join_with' => [],
  204. 'orderby' => 'order ASC',
  205. 'attribute_id_producer' => 'product.id_producer'
  206. ];
  207. }
  208. /**
  209. * Retourne la description du produit.
  210. *
  211. * @return string
  212. */
  213. public function getDescription()
  214. {
  215. $description = $this->description;
  216. if (isset($this->weight) && is_numeric($this->weight) && $this->weight > 0) {
  217. if ($this->weight >= 1000) {
  218. $description .= ' (' . ($this->weight / 1000) . 'kg)';
  219. } else {
  220. $description .= ' (' . $this->weight . 'g)';
  221. }
  222. }
  223. return $description;
  224. }
  225. /**
  226. * Retourne le libellé (admin) du produit.
  227. * @return type
  228. */
  229. public function getStrWordingAdmin()
  230. {
  231. return $this->name;
  232. }
  233. /**
  234. * Enregistre le produit.
  235. *
  236. * @param boolean $runValidation
  237. * @param array $attributeNames
  238. * @return boolean
  239. */
  240. public function save($runValidation = true, $attributeNames = NULL)
  241. {
  242. $this->id_producer = GlobalParam::getCurrentProducerId();
  243. return parent::save($runValidation, $attributeNames);
  244. }
  245. /**
  246. * Retourne les produits d'une production donnée.
  247. *
  248. * @param integer $idDistribution
  249. * @return array
  250. */
  251. public static function searchByDistribution($idDistribution)
  252. {
  253. return Product::find()
  254. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  255. ->where([
  256. 'id_producer' => GlobalParam::getCurrentProducerId(),
  257. 'product_distribution.id_distribution' => $idDistribution
  258. ])
  259. ->orderBy('product_distribution.active DESC, product.order ASC')
  260. ->all();
  261. }
  262. /**
  263. * Retourne le nombre de produits du producteur courant.
  264. *
  265. * @return integer
  266. */
  267. public static function count()
  268. {
  269. return self::searchCount();
  270. }
  271. /**
  272. * Retourne le produit "Don".
  273. *
  274. * @return Product
  275. */
  276. public static function getProductGift()
  277. {
  278. $productGift = Product::find()
  279. ->where([
  280. 'product.id_producer' => 0
  281. ])
  282. ->andFilterWhere(['like', 'product.name', 'Don'])
  283. ->one();
  284. return $productGift;
  285. }
  286. /**
  287. * Retourne le libellé d'une unité.
  288. *
  289. * @param $format wording_unit, wording, short
  290. * @param $unitInDb Unité stockée en base de données (ex: si g > kg, si mL > L)
  291. * @return $string Libellé de l'unité
  292. */
  293. public static function strUnit($unit, $format = 'wording_short', $unitInDb = false)
  294. {
  295. $strUnit = '';
  296. if ($unitInDb) {
  297. if ($unit == 'g') {
  298. $unit = 'kg';
  299. }
  300. if ($unit == 'mL') {
  301. $unit = 'L';
  302. }
  303. }
  304. if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit][$format])) {
  305. $strUnit = self::$unitsArray[$unit][$format];
  306. }
  307. return $strUnit;
  308. }
  309. public function getPrice($params = [])
  310. {
  311. $specificPrices = $this->productPrice ;
  312. $user = isset($params['user']) ? $params['user'] : false ;
  313. $userProducer = isset($params['user_producer']) ? $params['user_producer'] : false ;
  314. $pointSale = isset($params['point_sale']) ? $params['point_sale'] : false ;
  315. if($specificPrices && ($user || $pointSale)) {
  316. $specificPricesArray = [
  317. 'user' => false,
  318. 'pointsale' => false,
  319. 'user_pointsale' => false,
  320. 'usergroup' => false,
  321. ] ;
  322. foreach($specificPrices as $specificPrice) {
  323. if($user
  324. && $specificPrice->id_user
  325. && !$specificPrice->id_point_sale
  326. && !$specificPrice->id_user_group
  327. && $specificPrice->id_user == $user->id) {
  328. $specificPricesArray['user'] = $specificPrice->price ;
  329. }
  330. if($user
  331. && $specificPrice->id_user_group
  332. && !$specificPrice->id_point_sale
  333. && !$specificPrice->id_user
  334. && $user->belongsToUserGroup($specificPrice->id_user_group)) {
  335. $specificPricesArray['usergroup'] = $specificPrice->price ;
  336. }
  337. if($pointSale
  338. && $specificPrice->id_point_sale
  339. && !$specificPrice->id_user
  340. && !$specificPrice->id_user_group
  341. && $specificPrice->id_point_sale == $pointSale->id) {
  342. $specificPricesArray['pointsale'] = $specificPrice->price ;
  343. }
  344. if($pointSale && $user
  345. && $specificPrice->id_point_sale
  346. && $specificPrice->id_user
  347. && $specificPrice->id_point_sale == $pointSale->id
  348. && $specificPrice->id_user == $user->id) {
  349. $specificPricesArray['user_pointsale'] = $specificPrice->price ;
  350. }
  351. }
  352. if($specificPricesArray['user_pointsale']) {
  353. return $specificPricesArray['user_pointsale'] ;
  354. }
  355. elseif($specificPricesArray['user']) {
  356. return $specificPricesArray['user'] ;
  357. }
  358. elseif($specificPricesArray['usergroup']) {
  359. return $specificPricesArray['usergroup'] ;
  360. }
  361. elseif($specificPricesArray['pointsale']) {
  362. return $specificPricesArray['pointsale'] ;
  363. }
  364. }
  365. if($userProducer && $userProducer->product_price_percent) {
  366. return $this->price * (1 + $userProducer->product_price_percent / 100) ;
  367. }
  368. if($pointSale && $pointSale->product_price_percent) {
  369. return $this->price * (1 + $pointSale->product_price_percent / 100) ;
  370. }
  371. return $this->price ;
  372. }
  373. /**
  374. * Retourne le prix du produit avec taxe
  375. */
  376. public function getPriceWithTax($params = [])
  377. {
  378. $taxRateValue = $this->taxRate ? $this->taxRate->value : 0 ;
  379. return Price::getPriceWithTax($this->getPrice($params), $taxRateValue);
  380. }
  381. public function getTheTaxRate()
  382. {
  383. if($this->id_tax_rate) {
  384. return $this->id_tax_rate ;
  385. }
  386. else {
  387. return GlobalParam::getCurrentProducer()->taxRate->id;
  388. }
  389. }
  390. }