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