選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

496 行
20KB

  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\GlobalParam;
  39. use Yii;
  40. use common\components\ActiveRecordCommon;
  41. use common\models\Producer;
  42. use common\models\PointSale;
  43. use common\models\UserPointSale;
  44. use common\models\Order;
  45. use common\models\ProductOrder;
  46. use common\models\User;
  47. /**
  48. * This is the model class for table "commande_auto".
  49. *
  50. * @property integer $id
  51. * @property integer $id_user
  52. * @property integer $id_producer
  53. * @property integer $id_point_sale
  54. * @property string $date_begin
  55. * @property string $date_end
  56. * @property integer $monday
  57. * @property integer $tuesday
  58. * @property integer $wednesday
  59. * @property integer $thursday
  60. * @property integer $friday
  61. * @property integer $saturday
  62. * @property integer $sunday
  63. * @property integer $week_frequency
  64. * @property string $username
  65. * @property string $auto_payment
  66. * @property string $comment
  67. */
  68. class Subscription extends ActiveRecordCommon
  69. {
  70. /**
  71. * @inheritdoc
  72. */
  73. public static function tableName()
  74. {
  75. return 'subscription';
  76. }
  77. /**
  78. * @inheritdoc
  79. */
  80. public function rules()
  81. {
  82. return [
  83. [['id_producer', 'id_point_sale'], 'required'],
  84. [['id_user', 'id_producer', 'id_point_sale', 'monday', 'tuesday',
  85. 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'week_frequency'], 'integer'],
  86. [['auto_payment'], 'boolean'],
  87. [['date_begin', 'date_end', 'username', 'comment'], 'safe'],
  88. ];
  89. }
  90. /**
  91. * @inheritdoc
  92. */
  93. public function attributeLabels()
  94. {
  95. return [
  96. 'id' => 'ID',
  97. 'id_user' => 'Utilisateur',
  98. 'id_producer' => 'Etablissement',
  99. 'id_point_sale' => 'Point de vente',
  100. 'date_begin' => 'Date de début',
  101. 'date_end' => 'Date de fin',
  102. 'monday' => 'Lundi',
  103. 'tuesday' => 'Mardi',
  104. 'wednesday' => 'Mercredi',
  105. 'thursday' => 'Jeudi',
  106. 'friday' => 'Vendredi',
  107. 'saturday' => 'Samedi',
  108. 'sunday' => 'Dimanche',
  109. 'week_frequency' => 'Périodicité',
  110. 'auto_payment' => 'Paiement automatique',
  111. 'comment' => 'Commentaire'
  112. ];
  113. }
  114. /*
  115. * Relations
  116. */
  117. public function getUser()
  118. {
  119. return $this->hasOne(User::className(), ['id' => 'id_user']);
  120. }
  121. public function getProducer()
  122. {
  123. return $this->hasOne(
  124. Producer::className(),
  125. ['id' => 'id_producer']
  126. );
  127. }
  128. public function getPointSale()
  129. {
  130. return $this->hasOne(
  131. PointSale::className(),
  132. ['id' => 'id_point_sale']
  133. );
  134. }
  135. public function getProductSubscription()
  136. {
  137. return $this->hasMany(
  138. ProductSubscription::className(),
  139. ['id_subscription' => 'id']
  140. )->with('product');
  141. }
  142. /**
  143. * Retourne les options de base nécessaires à la fonction de recherche.
  144. *
  145. * @return array
  146. */
  147. public static function defaultOptionsSearch()
  148. {
  149. return [
  150. 'with' => ['producer'],
  151. 'join_with' => ['user', 'productSubscription', 'productSubscription.product', 'pointSale'],
  152. 'orderby' => 'user.name ASC',
  153. 'attribute_id_producer' => 'subscription.id_producer'
  154. ];
  155. }
  156. /**
  157. * Ajoute la commande pour une date donnée.
  158. *
  159. * @param string $date
  160. */
  161. public function add($date)
  162. {
  163. // distribution
  164. $distribution = Distribution::searchOne([
  165. 'distribution.date' => date('Y-m-d', strtotime($date))
  166. ]);
  167. if ($distribution && count($this->productSubscription) && $this->id_point_sale) {
  168. // commande
  169. $order = new Order;
  170. if (strlen($this->username)) {
  171. $order->username = $this->username;
  172. $order->id_user = 0;
  173. } else {
  174. $order->id_user = $this->id_user;
  175. }
  176. $order->date = date('Y-m-d H:i:s');
  177. $order->origin = Order::ORIGIN_AUTO;
  178. $order->id_point_sale = $this->id_point_sale;
  179. $order->id_distribution = $distribution->id;
  180. $order->id_subscription = $this->id;
  181. $order->status = 'tmp-order' ;
  182. if (strlen($this->comment)) {
  183. $order->comment = $this->comment;
  184. }
  185. $pointSale = PointSale::findOne($this->id_point_sale);
  186. if($pointSale) {
  187. $creditFunctioning = $pointSale->getCreditFunctioning();
  188. $order->auto_payment = 0;
  189. if ($order->id_user && Producer::getConfig('credit') && $pointSale->credit) {
  190. if ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL) {
  191. $order->auto_payment = $this->auto_payment;
  192. } elseif ($creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY) {
  193. $order->auto_payment = 1;
  194. } elseif ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER) {
  195. $user = User::findOne($order->id_user);
  196. $userProducer = UserProducer::searchOne([
  197. 'id_user' => $order->id_user,
  198. 'id_producer' => $distribution->id_producer
  199. ]);
  200. if ($userProducer) {
  201. $order->auto_payment = $userProducer->credit_active;
  202. }
  203. }
  204. }
  205. $order->tiller_synchronization = $order->auto_payment ;
  206. $userPointSale = UserPointSale::searchOne([
  207. 'id_point_sale' => $this->id_point_sale,
  208. 'id_user' => $this->id_user
  209. ]);
  210. if ($userPointSale && strlen($userPointSale->comment)) {
  211. $order->comment_point_sale = $userPointSale->comment;
  212. }
  213. $order->save();
  214. // liaison utilisateur / point de vente
  215. if ($order->id_user) {
  216. $pointSale = PointSale::findOne($this->id_point_sale);
  217. $pointSale->linkUser($order->id_user);
  218. }
  219. // produits
  220. $amountTotal = 0;
  221. $productsAdd = false;
  222. foreach ($this->productSubscription as $productSubscription) {
  223. $productOrder = new ProductOrder;
  224. $productOrder->id_order = $order->id;
  225. $productOrder->id_product = $productSubscription->product->id;
  226. $productOrder->quantity = $productSubscription->quantity;
  227. $productOrder->price = $productSubscription->product->getPrice([
  228. 'id_user' => $this->id_user,
  229. 'id_point_sale' => $this->id_point_sale
  230. ]);
  231. $productOrder->unit = $productSubscription->product->unit;
  232. $productOrder->step = $productSubscription->product->step;
  233. $productOrder->id_tax_rate = $productSubscription->product->taxRate->id;
  234. $productOrder->save();
  235. $productsAdd = true;
  236. }
  237. if (!$productsAdd) {
  238. $order->delete();
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Ajoute les commandes pour une date donnée à partir des abonnements.
  245. *
  246. * @param string $date
  247. * @param boolean $force
  248. */
  249. public static function addAll($date, $force = false)
  250. {
  251. $distribution = Distribution::searchOne([
  252. 'date' => date('Y-m-d', strtotime($date)),
  253. 'id_producer' => GlobalParam::getCurrentProducerId(),
  254. ]);
  255. if ($distribution) {
  256. $arrayOrdersDistribution = Order::searchAll([
  257. Order::tableName() . '.id_distribution' => $distribution->id
  258. ]);
  259. $arraySubscriptions = self::searchByDate($date);
  260. foreach ($arraySubscriptions as $subscription) {
  261. if (!$subscription->hasOrderAlreadyExist($arrayOrdersDistribution)) {
  262. $subscription->add($date);
  263. }
  264. }
  265. }
  266. }
  267. /**
  268. * Informe s'il existe une commande correspond à l'abonnement courant.
  269. *
  270. * @param array $arrayOrders
  271. * @return boolean
  272. */
  273. public function hasOrderAlreadyExist($arrayOrders)
  274. {
  275. if (is_array($arrayOrders) && count($arrayOrders) > 0) {
  276. foreach ($arrayOrders as $order) {
  277. if ((($order->id_user > 0 && $order->id_user == $this->id_user) ||
  278. (!$order->id_user && $order->username == $this->username)) &&
  279. $order->id_point_sale == $this->id_point_sale) {
  280. return true;
  281. }
  282. }
  283. }
  284. return false;
  285. }
  286. /**
  287. * Retourne les abonnements pour une date donnée.
  288. *
  289. * @param string $date
  290. * @return array
  291. */
  292. public static function searchByDate($date)
  293. {
  294. $date = date('Y-m-d', strtotime($date));
  295. $subscriptions = Subscription::searchAll();
  296. $arrSubscriptions = [];
  297. foreach ($subscriptions as $s) {
  298. if ($date >= $s->date_begin &&
  299. (!$s->date_end || $date <= $s->date_end) &&
  300. $s->matchWith($date)) {
  301. $arrSubscriptions[] = $s;
  302. }
  303. }
  304. return $arrSubscriptions;
  305. }
  306. /**
  307. * Valide le fait qu'un abonnement est bien compatible avec une date donnée.
  308. *
  309. * @param string $date
  310. * @return boolean
  311. */
  312. public function matchWith($date)
  313. {
  314. $arrayDays = [
  315. 1 => 'monday',
  316. 2 => 'tuesday',
  317. 3 => 'wednesday',
  318. 4 => 'thursday',
  319. 5 => 'friday',
  320. 6 => 'saturday',
  321. 7 => 'sunday'
  322. ];
  323. $nbDays = (strtotime($date) - strtotime($this->date_begin)) / (24 * 60 * 60);
  324. if (round($nbDays) % ($this->week_frequency * 7) < 7) {
  325. $numDay = date('N', strtotime($date));
  326. $day = $arrayDays[$numDay];
  327. if ($this->$day) {
  328. return true;
  329. }
  330. }
  331. return false;
  332. }
  333. /**
  334. * Recherche les distributions futures où l'abonnement peut s'appliquer.
  335. *
  336. * @return array
  337. */
  338. public function searchMatchedIncomingDistributions()
  339. {
  340. $producer = GlobalParam::getCurrentProducer();
  341. $params = [
  342. ':date_earliest_order' => date('Y-m-d'),
  343. ':date_begin' => date('Y-m-d', strtotime($this->date_begin)),
  344. ':id_producer' => GlobalParam::getCurrentProducerId()
  345. ];
  346. $incomingDistributions = Distribution::find()
  347. ->where('id_producer = :id_producer')
  348. ->andWhere('date >= :date_begin')
  349. ->andWhere('date >= :date_earliest_order');
  350. if ($this->date_end) {
  351. $incomingDistributions->andWhere('date < :date_end');
  352. $params[':date_end'] = date('Y-m-d', strtotime($this->date_end));
  353. }
  354. $incomingDistributions->orderBy('date ASC');
  355. $incomingDistributions->params($params);
  356. $incomingDistributionsArray = $incomingDistributions->all();
  357. $incomingDistributions = Distribution::filterDistributionsByDateDelay($incomingDistributionsArray) ;
  358. $matchedIncomingDistributionsArray = [];
  359. foreach ($incomingDistributionsArray as $incomingDistribution) {
  360. if ($this->matchWith($incomingDistribution->date)) {
  361. $matchedIncomingDistributionsArray[] = $incomingDistribution;
  362. }
  363. }
  364. return $matchedIncomingDistributionsArray;
  365. }
  366. public function deleteOrdersIncomingDistributions()
  367. {
  368. $params = [
  369. ':id_producer' => GlobalParam::getCurrentProducerId(),
  370. ':date_today' => date('Y-m-d'),
  371. ':date_begin' => $this->date_begin,
  372. ':id_subscription' => $this->id
  373. ];
  374. $orderDeadline = Producer::getConfig('order_deadline');
  375. $hour = date('G');
  376. if ($hour >= $orderDeadline) {
  377. $conditionDistributionDate = 'distribution.date > :date_today';
  378. } else {
  379. $conditionDistributionDate = 'distribution.date >= :date_today';
  380. }
  381. $orders = Order::find()
  382. ->joinWith('distribution')
  383. ->where('distribution.id_producer = :id_producer')
  384. ->andWhere($conditionDistributionDate)
  385. ->andWhere('distribution.date >= :date_begin')
  386. ->andWhere('order.id_subscription = :id_subscription');
  387. if ($this->date_end) {
  388. $orders->andWhere('distribution.date <= :date_end');
  389. $params[':date_end'] = $this->date_end;
  390. }
  391. $orders->params($params);
  392. $ordersArray = $orders->all();
  393. $configCredit = Producer::getConfig('credit');
  394. if ($ordersArray && count($ordersArray)) {
  395. foreach ($ordersArray as $order) {
  396. $theOrder = Order::searchOne(['id' => $order->id]);
  397. // remboursement de la commande
  398. if ($theOrder->id_user && $theOrder->getAmount(Order::AMOUNT_PAID) && $configCredit) {
  399. $theOrder->saveCreditHistory(
  400. CreditHistory::TYPE_REFUND,
  401. $theOrder->getAmount(Order::AMOUNT_PAID),
  402. $theOrder->distribution->id_producer,
  403. $theOrder->id_user,
  404. User::getCurrentId()
  405. );
  406. }
  407. ProductOrder::deleteAll(['id_order' => $order->id]);
  408. $order->delete();
  409. }
  410. }
  411. }
  412. public function updateIncomingDistributions($update = false)
  413. {
  414. $matchedDistributionsArray = $this->searchMatchedIncomingDistributions();
  415. if ($update) {
  416. $this->deleteOrdersIncomingDistributions();
  417. }
  418. if (count($matchedDistributionsArray)) {
  419. foreach ($matchedDistributionsArray as $distribution) {
  420. $this->add($distribution->date);
  421. }
  422. }
  423. }
  424. public function getUsername()
  425. {
  426. if($this->user) {
  427. return $this->user->getUsername() ;
  428. }
  429. return $this->username ;
  430. }
  431. }