Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Subscription.php 20KB

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