Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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