Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

360 lines
13KB

  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. 'weight' => 'Poids',
  142. 'recipe' => 'Recette',
  143. 'monday' => 'Lundi',
  144. 'tuesday' => 'Mardi',
  145. 'wednesday' => 'Mercredi',
  146. 'thursday' => 'Jeudi',
  147. 'friday' => 'Vendredi',
  148. 'saturday' => 'Samedi',
  149. 'sunday' => 'Dimanche',
  150. 'order' => 'Ordre',
  151. 'quantity_max' => 'Quantité max par défaut',
  152. 'quantity_max_monday' => 'Quantité max : lundi',
  153. 'quantity_max_tuesday' => 'Quantité max : mardi',
  154. 'quantity_max_wednesday' => 'Quantité max : mercredi',
  155. 'quantity_max_thursday' => 'Quantité max : jeudi',
  156. 'quantity_max_friday' => 'Quantité max : vendredi',
  157. 'quantity_max_saturday' => 'Quantité max : samedi',
  158. 'quantity_max_sunday' => 'Quantité max : dimanche',
  159. 'unavailable' => 'Épuisé',
  160. 'apply_distributions' => 'Appliquer ces modifications dans les distributions futures',
  161. 'unit' => 'Unité',
  162. 'step' => 'Pas',
  163. 'id_tax_rate' => 'TVA'
  164. ];
  165. }
  166. public function afterFind() {
  167. if ($this->taxRate == null) {
  168. $producer = Producer::searchOne(['id' => GlobalParam::getCurrentProducerId()]) ;
  169. if($producer) {
  170. $this->populateRelation('taxRate', $producer->taxRate);
  171. }
  172. //$this->populateRelation('taxRate', GlobalParam::getCurrentProducer()->taxRate);
  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. /**
  191. * Retourne les options de base nécessaires à la fonction de recherche.
  192. *
  193. * @return array
  194. */
  195. public static function defaultOptionsSearch()
  196. {
  197. return [
  198. 'with' => ['taxRate'],
  199. 'join_with' => [],
  200. 'orderby' => 'order ASC',
  201. 'attribute_id_producer' => 'product.id_producer'
  202. ];
  203. }
  204. /**
  205. * Retourne la description du produit.
  206. *
  207. * @return string
  208. */
  209. public function getDescription()
  210. {
  211. $description = $this->description;
  212. if (isset($this->weight) && is_numeric($this->weight) && $this->weight > 0) {
  213. if ($this->weight >= 1000) {
  214. $description .= ' (' . ($this->weight / 1000) . 'kg)';
  215. } else {
  216. $description .= ' (' . $this->weight . 'g)';
  217. }
  218. }
  219. return $description;
  220. }
  221. /**
  222. * Retourne le libellé (admin) du produit.
  223. * @return type
  224. */
  225. public function getStrWordingAdmin()
  226. {
  227. return $this->name;
  228. }
  229. /**
  230. * Enregistre le produit.
  231. *
  232. * @param boolean $runValidation
  233. * @param array $attributeNames
  234. * @return boolean
  235. */
  236. public function save($runValidation = true, $attributeNames = NULL)
  237. {
  238. $this->id_producer = GlobalParam::getCurrentProducerId();
  239. return parent::save($runValidation, $attributeNames);
  240. }
  241. /**
  242. * Retourne les produits d'une production donnée.
  243. *
  244. * @param integer $idDistribution
  245. * @return array
  246. */
  247. public static function searchByDistribution($idDistribution)
  248. {
  249. return Product::find()
  250. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  251. ->where([
  252. 'id_producer' => GlobalParam::getCurrentProducerId(),
  253. 'product_distribution.id_distribution' => $idDistribution
  254. ])
  255. ->orderBy('product_distribution.active DESC, product.order ASC')
  256. ->all();
  257. }
  258. /**
  259. * Retourne le nombre de produits du producteur courant.
  260. *
  261. * @return integer
  262. */
  263. public static function count()
  264. {
  265. return self::searchCount();
  266. }
  267. /**
  268. * Retourne le produit "Don".
  269. *
  270. * @return Product
  271. */
  272. public static function getProductGift()
  273. {
  274. $productGift = Product::find()
  275. ->where([
  276. 'product.id_producer' => 0
  277. ])
  278. ->andFilterWhere(['like', 'product.name', 'Don'])
  279. ->one();
  280. return $productGift;
  281. }
  282. /**
  283. * Retourne le libellé d'une unité.
  284. *
  285. * @param $format wording_unit, wording, short
  286. * @param $unitInDb Unité stockée en base de données (ex: si g > kg, si mL > L)
  287. * @return $string Libellé de l'unité
  288. */
  289. public static function strUnit($unit, $format = 'wording_short', $unitInDb = false)
  290. {
  291. $strUnit = '';
  292. if ($unitInDb) {
  293. if ($unit == 'g') {
  294. $unit = 'kg';
  295. }
  296. if ($unit == 'mL') {
  297. $unit = 'L';
  298. }
  299. }
  300. if (isset(self::$unitsArray[$unit]) && isset(self::$unitsArray[$unit][$format])) {
  301. $strUnit = self::$unitsArray[$unit][$format];
  302. }
  303. return $strUnit;
  304. }
  305. public function getPrice()
  306. {
  307. return $this->price ;
  308. }
  309. /**
  310. * Retourne le prix du produit avec taxe
  311. */
  312. public function getPriceWithTax()
  313. {
  314. $taxRateValue = $this->taxRate ? $this->taxRate->value : 0 ;
  315. return Price::getPriceWithTax($this->price, $taxRateValue);
  316. }
  317. public function getTheTaxRate()
  318. {
  319. if($this->id_tax_rate) {
  320. return $this->id_tax_rate ;
  321. }
  322. else {
  323. return GlobalParam::getCurrentProducer()->taxRate->id;
  324. }
  325. }
  326. }