You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

преди 5 години
преди 6 години
преди 6 години
преди 6 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. /**
  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. [['username', 'comment', 'date_begin', 'date_end'], '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, $force = false)
  162. {
  163. // distribution
  164. $now = date('Y-m-d');
  165. $distributionDate = date('Y-m-d', strtotime($date));
  166. $distribution = Distribution::searchOne([
  167. 'distribution.date' => $distributionDate
  168. ]);
  169. if ($distribution
  170. && $distribution->active
  171. && ($distributionDate > $now || $force)
  172. && count($this->productSubscription)
  173. && $this->id_point_sale) {
  174. // commande
  175. $order = new Order;
  176. if (strlen($this->username)) {
  177. $order->username = $this->username;
  178. $order->id_user = 0;
  179. } else {
  180. $order->id_user = $this->id_user;
  181. }
  182. $user = false;
  183. if ($this->id_user) {
  184. $user = User::findOne($this->id_user);
  185. }
  186. $order->date = date('Y-m-d H:i:s');
  187. $order->origin = Order::ORIGIN_AUTO;
  188. $order->id_point_sale = $this->id_point_sale;
  189. $order->id_distribution = $distribution->id;
  190. $order->id_subscription = $this->id;
  191. $order->status = 'tmp-order';
  192. if (strlen($this->comment)) {
  193. $order->comment = $this->comment;
  194. }
  195. $pointSale = PointSale::findOne($this->id_point_sale);
  196. if ($pointSale) {
  197. $creditFunctioning = $pointSale->getCreditFunctioning();
  198. $order->auto_payment = 0;
  199. if ($order->id_user && Producer::getConfig('credit') && $pointSale->credit) {
  200. if ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL) {
  201. $order->auto_payment = $this->auto_payment;
  202. } elseif ($creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY) {
  203. $order->auto_payment = 1;
  204. } elseif ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER) {
  205. $user = User::findOne($order->id_user);
  206. $userProducer = UserProducer::searchOne([
  207. 'id_user' => $order->id_user,
  208. 'id_producer' => $distribution->id_producer
  209. ]);
  210. if ($userProducer) {
  211. $order->auto_payment = $userProducer->credit_active;
  212. }
  213. }
  214. }
  215. $order->tiller_synchronization = $order->auto_payment;
  216. $userPointSale = UserPointSale::searchOne([
  217. 'id_point_sale' => $this->id_point_sale,
  218. 'id_user' => $this->id_user
  219. ]);
  220. if ($userPointSale && strlen($userPointSale->comment)) {
  221. $order->comment_point_sale = $userPointSale->comment;
  222. }
  223. $order->save();
  224. // liaison utilisateur / point de vente
  225. if ($order->id_user) {
  226. $pointSale = PointSale::findOne($this->id_point_sale);
  227. $pointSale->linkUser($order->id_user);
  228. }
  229. // produits
  230. $productsAdd = false;
  231. foreach ($this->productSubscription as $productSubscription) {
  232. $productOrder = new ProductOrder;
  233. $productOrder->id_order = $order->id;
  234. $productOrder->id_product = $productSubscription->product->id;
  235. $productOrder->quantity = $productSubscription->quantity;
  236. $productOrder->price = $productSubscription->product->getPrice([
  237. 'user' => $user,
  238. 'point_sale' => $pointSale,
  239. 'quantity' => $productSubscription->quantity
  240. ]);
  241. $productOrder->unit = $productSubscription->product->unit;
  242. $productOrder->step = $productSubscription->product->step;
  243. $productOrder->id_tax_rate = $productSubscription->product->taxRate->id;
  244. $productOrder->save();
  245. $productsAdd = true;
  246. }
  247. if (!$productsAdd) {
  248. $order->delete();
  249. }
  250. $order->initReference();
  251. }
  252. }
  253. }
  254. /**
  255. * Ajoute les commandes pour une date donnée à partir des abonnements.
  256. *
  257. * @param string $date
  258. * @param boolean $force
  259. */
  260. public static function addAll($date, $force = false)
  261. {
  262. $distribution = Distribution::searchOne([
  263. 'date' => date('Y-m-d', strtotime($date)),
  264. 'id_producer' => GlobalParam::getCurrentProducerId(),
  265. ]);
  266. if ($distribution) {
  267. $arrayOrdersDistribution = Order::searchAll([
  268. Order::tableName() . '.id_distribution' => $distribution->id
  269. ]);
  270. $arraySubscriptions = self::searchByDate($date);
  271. foreach ($arraySubscriptions as $subscription) {
  272. if (!$subscription->hasOrderAlreadyExist($arrayOrdersDistribution)) {
  273. $subscription->add($date, $force);
  274. }
  275. }
  276. }
  277. }
  278. /**
  279. * Informe s'il existe une commande correspond à l'abonnement courant.
  280. *
  281. * @param array $arrayOrders
  282. * @return boolean
  283. */
  284. public function hasOrderAlreadyExist($arrayOrders)
  285. {
  286. if (is_array($arrayOrders) && count($arrayOrders) > 0) {
  287. foreach ($arrayOrders as $order) {
  288. if ((($order->id_user > 0 && $order->id_user == $this->id_user) ||
  289. (!$order->id_user && $order->username == $this->username)) &&
  290. $order->id_point_sale == $this->id_point_sale) {
  291. return true;
  292. }
  293. }
  294. }
  295. return false;
  296. }
  297. /**
  298. * Retourne les abonnements pour une date donnée.
  299. *
  300. * @param string $date
  301. * @return array
  302. */
  303. public static function searchByDate($date)
  304. {
  305. $date = date('Y-m-d', strtotime($date));
  306. $subscriptions = Subscription::searchAll();
  307. $arrSubscriptions = [];
  308. foreach ($subscriptions as $s) {
  309. if ($date >= $s->date_begin &&
  310. (!$s->date_end || $date <= $s->date_end) &&
  311. $s->matchWith($date)) {
  312. $arrSubscriptions[] = $s;
  313. }
  314. }
  315. return $arrSubscriptions;
  316. }
  317. /**
  318. * Valide le fait qu'un abonnement est bien compatible avec une date donnée.
  319. *
  320. * @param string $date
  321. * @return boolean
  322. */
  323. public function matchWith($date)
  324. {
  325. $arrayDays = [
  326. 1 => 'monday',
  327. 2 => 'tuesday',
  328. 3 => 'wednesday',
  329. 4 => 'thursday',
  330. 5 => 'friday',
  331. 6 => 'saturday',
  332. 7 => 'sunday'
  333. ];
  334. $nbDays = (strtotime($date) - strtotime($this->date_begin)) / (24 * 60 * 60);
  335. if (round($nbDays) % ($this->week_frequency * 7) < 7) {
  336. $numDay = date('N', strtotime($date));
  337. $day = $arrayDays[$numDay];
  338. if ($this->$day) {
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. /**
  345. * Recherche les distributions futures où l'abonnement peut s'appliquer.
  346. *
  347. * @return array
  348. */
  349. public function searchMatchedIncomingDistributions()
  350. {
  351. $params = [
  352. ':date_earliest_order' => date('Y-m-d'),
  353. ':date_begin' => date('Y-m-d', strtotime($this->date_begin)),
  354. ':id_producer' => GlobalParam::getCurrentProducerId()
  355. ];
  356. $incomingDistributions = Distribution::find()
  357. ->where('id_producer = :id_producer')
  358. ->andWhere('date >= :date_begin')
  359. ->andWhere('date > :date_earliest_order');
  360. if ($this->date_end) {
  361. $incomingDistributions->andWhere('date <= :date_end');
  362. $params[':date_end'] = date('Y-m-d', strtotime($this->date_end));
  363. }
  364. $incomingDistributions->orderBy('date ASC');
  365. $incomingDistributions->params($params);
  366. $incomingDistributionsArray = $incomingDistributions->all();
  367. Distribution::filterDistributionsByDateDelay($incomingDistributionsArray);
  368. $matchedIncomingDistributionsArray = [];
  369. foreach ($incomingDistributionsArray as $incomingDistribution) {
  370. if ($this->matchWith($incomingDistribution->date)) {
  371. $matchedIncomingDistributionsArray[] = $incomingDistribution;
  372. }
  373. }
  374. return $matchedIncomingDistributionsArray;
  375. }
  376. public function deleteOrdersIncomingDistributions($deleteAfterDateEnd = false)
  377. {
  378. $dateStart = $this->date_begin;
  379. $comparatorDateStart = '>=';
  380. if($deleteAfterDateEnd) {
  381. $dateStart = $this->date_end;
  382. $comparatorDateStart = '>';
  383. }
  384. $params = [
  385. ':id_producer' => GlobalParam::getCurrentProducerId(),
  386. ':date_today' => date('Y-m-d'),
  387. ':date_start' => $dateStart,
  388. ':id_subscription' => $this->id
  389. ];
  390. $orderDeadline = Producer::getConfig('order_deadline');
  391. $hour = date('G');
  392. if ($hour >= $orderDeadline) {
  393. $conditionDistributionDate = 'distribution.date > :date_today';
  394. } else {
  395. $conditionDistributionDate = 'distribution.date >= :date_today';
  396. }
  397. $orders = Order::find()
  398. ->joinWith('distribution')
  399. ->where('distribution.id_producer = :id_producer')
  400. ->andWhere($conditionDistributionDate)
  401. ->andWhere('distribution.date '.$comparatorDateStart.' :date_start')
  402. ->andWhere('order.id_subscription = :id_subscription');
  403. $orders->params($params);
  404. $ordersArray = $orders->all();
  405. $configCredit = Producer::getConfig('credit');
  406. $countOrdersDeleted = 0;
  407. if ($ordersArray && count($ordersArray)) {
  408. foreach ($ordersArray as $order) {
  409. $theOrder = Order::searchOne(['id' => $order->id]);
  410. // remboursement de la commande
  411. if ($theOrder->id_user && $theOrder->getAmount(Order::AMOUNT_PAID) && $configCredit) {
  412. $theOrder->saveCreditHistory(
  413. CreditHistory::TYPE_REFUND,
  414. $theOrder->getAmount(Order::AMOUNT_PAID),
  415. $theOrder->distribution->id_producer,
  416. $theOrder->id_user,
  417. User::getCurrentId()
  418. );
  419. }
  420. $order->delete(true);
  421. $countOrdersDeleted ++;
  422. }
  423. }
  424. return $countOrdersDeleted;
  425. }
  426. public function updateIncomingDistributions($update = false)
  427. {
  428. $matchedDistributionsArray = $this->searchMatchedIncomingDistributions();
  429. if ($update) {
  430. $this->deleteOrdersIncomingDistributions();
  431. }
  432. if (count($matchedDistributionsArray)) {
  433. foreach ($matchedDistributionsArray as $distribution) {
  434. $this->add($distribution->date);
  435. }
  436. }
  437. }
  438. public function getUsername()
  439. {
  440. if ($this->user) {
  441. return $this->user->getUsername();
  442. }
  443. return $this->username;
  444. }
  445. }