Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

454 lines
17KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace common\models;
  38. use common\helpers\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', 'id_product_category'], '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', 'reference', '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. 'reference' => 'Référence',
  138. 'description' => 'Description',
  139. 'active' => 'Actif',
  140. 'photo' => 'Photo',
  141. 'price' => 'Prix (€) TTC',
  142. 'price' => 'Prix (€) TTC',
  143. 'weight' => 'Poids',
  144. 'recipe' => 'Recette',
  145. 'monday' => 'Lundi',
  146. 'tuesday' => 'Mardi',
  147. 'wednesday' => 'Mercredi',
  148. 'thursday' => 'Jeudi',
  149. 'friday' => 'Vendredi',
  150. 'saturday' => 'Samedi',
  151. 'sunday' => 'Dimanche',
  152. 'order' => 'Ordre',
  153. 'quantity_max' => 'Quantité max par défaut',
  154. 'quantity_max_monday' => 'Quantité max : lundi',
  155. 'quantity_max_tuesday' => 'Quantité max : mardi',
  156. 'quantity_max_wednesday' => 'Quantité max : mercredi',
  157. 'quantity_max_thursday' => 'Quantité max : jeudi',
  158. 'quantity_max_friday' => 'Quantité max : vendredi',
  159. 'quantity_max_saturday' => 'Quantité max : samedi',
  160. 'quantity_max_sunday' => 'Quantité max : dimanche',
  161. 'unavailable' => 'Épuisé',
  162. 'apply_distributions' => 'Appliquer ces modifications dans les distributions futures',
  163. 'unit' => 'Unité',
  164. 'step' => 'Pas',
  165. 'id_tax_rate' => 'TVA',
  166. 'id_product_category' => 'Catégorie'
  167. ];
  168. }
  169. public function afterFind() {
  170. if ($this->taxRate == null) {
  171. $producer = Producer::searchOne(['id' => GlobalParam::getCurrentProducerId()]) ;
  172. if($producer) {
  173. $this->populateRelation('taxRate', $producer->taxRate);
  174. }
  175. }
  176. $this->wording_unit = Product::strUnit($this->unit) ;
  177. $this->price_with_tax = $this->getPriceWithTax() ;
  178. parent::afterFind();
  179. }
  180. public function getProductDistribution()
  181. {
  182. return $this->hasMany(ProductDistribution::className(), ['id_product' => 'id']);
  183. }
  184. public function getProductSubscription()
  185. {
  186. return $this->hasMany(ProductSubscription::className(), ['id_product' => 'id']);
  187. }
  188. public function getTaxRate()
  189. {
  190. return $this->hasOne(TaxRate::className(), ['id' => 'id_tax_rate']);
  191. }
  192. public function getProductPrice()
  193. {
  194. return $this->hasMany(ProductPrice::className(), ['id_product' => 'id']);
  195. }
  196. public function getProductCategory()
  197. {
  198. return $this->hasOne(ProductCategory::className(), ['id' => 'id_product_category']) ;
  199. }
  200. /**
  201. * Retourne les options de base nécessaires à la fonction de recherche.
  202. *
  203. * @return array
  204. */
  205. public static function defaultOptionsSearch()
  206. {
  207. return [
  208. 'with' => ['taxRate'],
  209. 'join_with' => [],
  210. 'orderby' => 'order ASC',
  211. 'attribute_id_producer' => 'product.id_producer'
  212. ];
  213. }
  214. /**
  215. * Retourne la description du produit.
  216. *
  217. * @return string
  218. */
  219. public function getDescription()
  220. {
  221. $description = $this->description;
  222. if (isset($this->weight) && is_numeric($this->weight) && $this->weight > 0) {
  223. if ($this->weight >= 1000) {
  224. $description .= ' (' . ($this->weight / 1000) . 'kg)';
  225. } else {
  226. $description .= ' (' . $this->weight . 'g)';
  227. }
  228. }
  229. return $description;
  230. }
  231. /**
  232. * Retourne le libellé (admin) du produit.
  233. * @return type
  234. */
  235. public function getStrWordingAdmin()
  236. {
  237. return $this->name;
  238. }
  239. /**
  240. * Enregistre le produit.
  241. *
  242. * @param boolean $runValidation
  243. * @param array $attributeNames
  244. * @return boolean
  245. */
  246. public function save($runValidation = true, $attributeNames = NULL)
  247. {
  248. $this->id_producer = GlobalParam::getCurrentProducerId();
  249. return parent::save($runValidation, $attributeNames);
  250. }
  251. /**
  252. * Retourne les produits d'une production donnée.
  253. *
  254. * @param integer $idDistribution
  255. * @return array
  256. */
  257. public static function searchByDistribution($idDistribution)
  258. {
  259. return Product::find()
  260. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  261. ->where([
  262. 'id_producer' => GlobalParam::getCurrentProducerId(),
  263. 'product_distribution.id_distribution' => $idDistribution
  264. ])
  265. ->orderBy('product_distribution.active DESC, product.order ASC')
  266. ->all();
  267. }
  268. /**
  269. * Retourne le nombre de produits du producteur courant.
  270. *
  271. * @return integer
  272. */
  273. public static function count()
  274. {
  275. return self::searchCount();
  276. }
  277. /**
  278. * Retourne le produit "Don".
  279. *
  280. * @return Product
  281. */
  282. public static function getProductGift()
  283. {
  284. $productGift = Product::find()
  285. ->where([
  286. 'product.id_producer' => 0
  287. ])
  288. ->andFilterWhere(['like', 'product.name', 'Don'])
  289. ->one();
  290. return $productGift;
  291. }
  292. /**
  293. * Retourne le libellé d'une unité.
  294. *
  295. * @param $format wording_unit, wording, short
  296. * @param $unitInDb Unité stockée en base de données (ex: si g > kg, si mL > L)
  297. * @return $string Libellé de l'unité
  298. */
  299. public static function strUnit($unit, $format = 'wording_short', $unitInDb = false)
  300. {
  301. $strUnit = '';
  302. if ($unitInDb) {
  303. if ($unit == 'g') {
  304. $unit = 'kg';
  305. }
  306. if ($unit == 'mL') {
  307. $unit = 'L';
  308. }
  309. }
  310. if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit][$format])) {
  311. $strUnit = self::$unitsArray[$unit][$format];
  312. }
  313. return $strUnit;
  314. }
  315. public function getPrice($params = [])
  316. {
  317. $specificPrices = $this->productPrice ;
  318. $user = isset($params['user']) ? $params['user'] : false ;
  319. $userProducer = isset($params['user_producer']) ? $params['user_producer'] : false ;
  320. $pointSale = isset($params['point_sale']) ? $params['point_sale'] : false ;
  321. if($specificPrices && ($user || $pointSale)) {
  322. $specificPricesArray = [
  323. 'user' => false,
  324. 'pointsale' => false,
  325. 'user_pointsale' => false,
  326. 'usergroup' => false,
  327. ] ;
  328. foreach($specificPrices as $specificPrice) {
  329. if($user
  330. && $specificPrice->id_user
  331. && !$specificPrice->id_point_sale
  332. && !$specificPrice->id_user_group
  333. && $specificPrice->id_user == $user->id) {
  334. $specificPricesArray['user'] = $specificPrice->price ;
  335. }
  336. if($user
  337. && $specificPrice->id_user_group
  338. && !$specificPrice->id_point_sale
  339. && !$specificPrice->id_user
  340. && $user->belongsToUserGroup($specificPrice->id_user_group)) {
  341. $specificPricesArray['usergroup'] = $specificPrice->price ;
  342. }
  343. if($pointSale
  344. && $specificPrice->id_point_sale
  345. && !$specificPrice->id_user
  346. && !$specificPrice->id_user_group
  347. && $specificPrice->id_point_sale == $pointSale->id) {
  348. $specificPricesArray['pointsale'] = $specificPrice->price ;
  349. }
  350. if($pointSale && $user
  351. && $specificPrice->id_point_sale
  352. && $specificPrice->id_user
  353. && $specificPrice->id_point_sale == $pointSale->id
  354. && $specificPrice->id_user == $user->id) {
  355. $specificPricesArray['user_pointsale'] = $specificPrice->price ;
  356. }
  357. }
  358. if($specificPricesArray['user_pointsale']) {
  359. return $specificPricesArray['user_pointsale'] ;
  360. }
  361. elseif($specificPricesArray['user']) {
  362. return $specificPricesArray['user'] ;
  363. }
  364. elseif($specificPricesArray['usergroup']) {
  365. return $specificPricesArray['usergroup'] ;
  366. }
  367. elseif($specificPricesArray['pointsale']) {
  368. return $specificPricesArray['pointsale'] ;
  369. }
  370. }
  371. if($userProducer && $userProducer->product_price_percent) {
  372. return $this->price * (1 + $userProducer->product_price_percent / 100) ;
  373. }
  374. if($pointSale && $pointSale->product_price_percent) {
  375. return $this->price * (1 + $pointSale->product_price_percent / 100) ;
  376. }
  377. return $this->price ;
  378. }
  379. /**
  380. * Retourne le prix du produit avec taxe
  381. */
  382. public function getPriceWithTax($params = [])
  383. {
  384. $taxRateValue = $this->taxRate ? $this->taxRate->value : 0 ;
  385. return Price::getPriceWithTax($this->getPrice($params), $taxRateValue);
  386. }
  387. public function getTheTaxRate()
  388. {
  389. if($this->id_tax_rate) {
  390. return $this->id_tax_rate ;
  391. }
  392. else {
  393. return GlobalParam::getCurrentProducer()->taxRate->id;
  394. }
  395. }
  396. public function getNameExport()
  397. {
  398. $producer = GlobalParam::getCurrentProducer() ;
  399. if($producer->option_export_display_product_reference && $this->reference && strlen($this->reference) > 0) {
  400. return $this->reference ;
  401. }
  402. return $this->name ;
  403. }
  404. }