Coupon.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\cart;
  10. //use fecshop\models\mysqldb\cart\Coupon as MyCoupon;
  11. //use fecshop\models\mysqldb\cart\CouponUsage as MyCouponUsage;
  12. use fecshop\services\Service;
  13. use Yii;
  14. /**
  15. * Coupon services.
  16. * @author Terry Zhao <2358269014@qq.com>
  17. * @since 1.0
  18. */
  19. class Coupon extends Service
  20. {
  21. protected $_useCouponInit; // 是否初始化这个百年两
  22. protected $_customer_id; // 用户id
  23. protected $_coupon_code; // 优惠卷码
  24. protected $_coupon_model; // 优惠券model
  25. protected $_coupon_usage_model; // 优惠券使用次数记录model
  26. protected $_couponModelName = '\fecshop\models\mysqldb\cart\Coupon';
  27. protected $_couponModel;
  28. protected $_couponUsageModelName = '\fecshop\models\mysqldb\cart\CouponUsage';
  29. protected $_couponUsageModel;
  30. public $coupon_type_percent = 1;
  31. public $coupon_type_direct = 2;
  32. public function init()
  33. {
  34. parent::init();
  35. list($this->_couponModelName, $this->_couponModel) = Yii::mapGet($this->_couponModelName);
  36. list($this->_couponUsageModelName, $this->_couponUsageModel) = Yii::mapGet($this->_couponUsageModelName);
  37. }
  38. protected function actionGetPrimaryKey()
  39. {
  40. return 'coupon_id';
  41. }
  42. /**
  43. * @param $primaryKey | Int
  44. * @return Object($this->_couponModel)
  45. * 通过id找到cupon的对象
  46. */
  47. protected function actionGetByPrimaryKey($primaryKey)
  48. {
  49. $one = $this->_couponModel->findOne($primaryKey);
  50. $primaryKey = $this->getPrimaryKey();
  51. if ($one[$primaryKey]) {
  52. return $one;
  53. } else {
  54. return new $this->_couponModelName;
  55. }
  56. }
  57. /**
  58. * @param $customer_id | Int
  59. * @param $coupon_id | Int
  60. * 通过customer_id 和 coupon_id得到 Coupon Usage Model.
  61. */
  62. protected function actionGetCouponUsageModel($customer_id = '', $coupon_id = '')
  63. {
  64. if (!$this->_coupon_usage_model) {
  65. if (!$customer_id) {
  66. $customer_id = $this->_customer_id;
  67. }
  68. if (!$coupon_id) {
  69. $couponModel = $this->getCouponModel();
  70. $coupon_id = isset($couponModel['coupon_id']) ? $couponModel['coupon_id'] : '';
  71. }
  72. if ($customer_id && $coupon_id) {
  73. $one = $this->_couponUsageModel->findOne([
  74. 'customer_id' => $customer_id,
  75. 'coupon_id' => $coupon_id,
  76. ]);
  77. if ($one['customer_id']) {
  78. $this->_coupon_usage_model = $one;
  79. }
  80. }
  81. }
  82. if ($this->_coupon_usage_model) {
  83. return $this->_coupon_usage_model;
  84. }
  85. }
  86. /**
  87. * @param $coupon_code | String
  88. * 根据 coupon_code 得到 coupon model
  89. */
  90. protected function actionGetCouponModel($coupon_code = '')
  91. {
  92. if (!$this->_coupon_model) {
  93. if (!$coupon_code) {
  94. $coupon_code = $this->_coupon_code;
  95. }
  96. if ($coupon_code) {
  97. $one = $this->_couponModel->findOne(['coupon_code' => $coupon_code]);
  98. if ($one['coupon_code']) {
  99. $this->_coupon_model = $one;
  100. }
  101. }
  102. }
  103. if ($this->_coupon_model) {
  104. return $this->_coupon_model;
  105. }
  106. }
  107. /**
  108. * @param $filter|array
  109. * @return Array;
  110. * 通过过滤条件,得到coupon的集合。
  111. * example filter:
  112. * [
  113. * 'numPerPage' => 20,
  114. * 'pageNum' => 1,
  115. * 'orderBy' => ['_id' => SORT_DESC, 'sku' => SORT_ASC ],
  116. * 'where' => [
  117. * ['>','price',1],
  118. * ['<=','price',10]
  119. * ['sku' => 'uk10001'],
  120. * ],
  121. * 'asArray' => true,
  122. * ]
  123. */
  124. protected function actionColl($filter = '')
  125. {
  126. $query = $this->_couponModel->find();
  127. $query = Yii::$service->helper->ar->getCollByFilter($query, $filter);
  128. $coll = $query->all();
  129. return [
  130. 'coll' => $coll,
  131. 'count'=> $query->limit(null)->offset(null)->count(),
  132. ];
  133. }
  134. /**
  135. * @param $one|array , save one data .
  136. * @return int 保存coupon成功后,返回保存的id。
  137. */
  138. protected function actionSave($one)
  139. {
  140. $time = time();
  141. $primaryKey = $this->getPrimaryKey();
  142. $primaryVal = isset($one[$primaryKey]) ? $one[$primaryKey] : '';
  143. if ($primaryVal) {
  144. $model = $this->_couponModel->findOne($primaryVal);
  145. if (!$model) {
  146. Yii::$service->helper->errors->add('coupon {primaryKey} is not exist' , ['primaryKey' => $this->getPrimaryKey()] );
  147. return;
  148. }
  149. } else {
  150. $o_one = $this->_couponModel->find()
  151. ->where(['coupon_code' =>$one['coupon_code']])
  152. ->one();
  153. if ($o_one[$primaryKey]) {
  154. Yii::$service->helper->errors->add('coupon_code must be unique');
  155. return;
  156. }
  157. $model = new $this->_couponModelName;
  158. $model->created_at = time();
  159. if (isset(Yii::$app->user)) {
  160. $user = Yii::$app->user;
  161. if (isset($user->identity)) {
  162. $identity = $user->identity;
  163. $person_id = $identity['id'];
  164. $model->created_person = $person_id;
  165. }
  166. }
  167. }
  168. $model->attributes = $one;
  169. if ($model->validate()) {
  170. $model->updated_at = time();
  171. $model = Yii::$service->helper->ar->save($model, $one);
  172. $primaryVal = $model[$primaryKey];
  173. return $primaryVal;
  174. } else {
  175. $errors = $model->errors;
  176. Yii::$service->helper->errors->addByModelErrors($errors);
  177. return false;
  178. }
  179. }
  180. /**
  181. * @param $ids | Int or Array
  182. * @return bool
  183. * 如果传入的是id数组,则删除多个
  184. * 如果传入的是Int,则删除一个coupon
  185. */
  186. protected function actionRemove($ids)
  187. {
  188. if (!$ids) {
  189. Yii::$service->helper->errors->add('remove id is empty');
  190. return false;
  191. }
  192. if (is_array($ids) && !empty($ids)) {
  193. foreach ($ids as $id) {
  194. $model = $this->_couponModel->findOne($id);
  195. if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
  196. $model->delete();
  197. } else {
  198. Yii::$service->helper->errors->add('Coupon remove errors:ID {id} is not exist.', ['id' => $id]);
  199. return false;
  200. }
  201. }
  202. } else {
  203. $id = $ids;
  204. $model = $this->_couponModel->findOne($id);
  205. if (isset($model[$this->getPrimaryKey()]) && !empty($model[$this->getPrimaryKey()])) {
  206. $model->delete();
  207. } else {
  208. Yii::$service->helper->errors->add('Coupon remove errors:ID {id} is not exist.', ['id' => $id]);
  209. return false;
  210. }
  211. }
  212. return true;
  213. }
  214. /**
  215. * @param $coupon_code | String 优惠卷码
  216. * 初始化对象变量,这个函数是在使用优惠券 和 取消优惠券的时候,
  217. * 调用相应方法前,通过这个函数初始化类变量
  218. * $_useCouponInit # 是否初始化过,如果初始化过了,则不会执行
  219. * $_customer_id # 用户id
  220. * $_coupon_code # 优惠卷码
  221. * $_coupon_model # 优惠券model
  222. * $_coupon_usage_model # 优惠券使用次数记录model
  223. * 这是一个内部函数,不对外开放。
  224. */
  225. protected function useCouponInit($coupon_code)
  226. {
  227. if (!$this->_useCouponInit) {
  228. // $this->_customer_id
  229. if (Yii::$app->user->isGuest) {
  230. $this->_customer_id = '';
  231. } else {
  232. if (Yii::$app->user->identity->id) {
  233. $this->_customer_id = Yii::$app->user->identity->id;
  234. }
  235. }
  236. // $this->getCouponUsageModel();
  237. // $this->getCouponModel();
  238. // $this->_coupon_code
  239. $this->_coupon_code = $coupon_code;
  240. $this->_useCouponInit = 1;
  241. }
  242. }
  243. /**
  244. * @param $isGetDiscount | boolean, 是否是获取折扣信息,
  245. * 1.如果值为true,说明该操作是获取cart 中的coupon的折扣操作步骤中的active判断,则只进行优惠券存在和是否过期判断,不对使用次数判断
  246. * 2.如果值为false,则是add coupon操作,除了优惠券是否存在, 是否过期判断,还需要对使用次数进行判断。
  247. * 查看coupon是否是可用的,如果可用,返回true,如果不可用,返回false
  248. */
  249. protected function couponIsActive($isGetDiscount = false)
  250. {
  251. if ($this->_customer_id) {
  252. if ($couponModel = $this->getCouponModel()) {
  253. $expiration_date = $couponModel['expiration_date'];
  254. // 未过期
  255. if ($expiration_date > time()) {
  256. if ($isGetDiscount) {
  257. return true;
  258. }
  259. $couponUsageModel = $this->getCouponUsageModel();
  260. $times_used = 0;
  261. if ($couponUsageModel['times_used']) {
  262. $times_used = $couponUsageModel['times_used'];
  263. }
  264. $users_per_customer = $couponModel['users_per_customer'];
  265. // 次数限制
  266. if ($times_used < $users_per_customer) {
  267. return true;
  268. } else {
  269. Yii::$service->helper->errors->add('The coupon has exceeded the maximum number of uses');
  270. }
  271. } else {
  272. Yii::$service->helper->errors->add('coupon is expired');
  273. }
  274. } else {
  275. //Yii::$service->helper->errors->add("coupon is not exist");
  276. }
  277. }
  278. return false;
  279. }
  280. /**
  281. * @param $coupon_code | String , coupon_code字符串
  282. * @param $dc_price | Float 总价格
  283. * 根据优惠券和总价格,计算出来打折后的价格。譬如原来10元,打八折后,是8元。
  284. */
  285. protected function actionGetDiscount($coupon_code, $dc_price)
  286. {
  287. $discount_cost = 0;
  288. $this->useCouponInit($coupon_code);
  289. if ($this->couponIsActive(true)) {
  290. $couponModel = $this->getCouponModel();
  291. $type = $couponModel['type'];
  292. $conditions = $couponModel['conditions'];
  293. $discount = $couponModel['discount'];
  294. //echo $conditions.'##'.$dc_price;;exit;
  295. if ($conditions <= $dc_price) {
  296. if ($type == $this->coupon_type_percent) { // 百分比
  297. // $base_discount_cost = $discount / 100 * $dc_price;
  298. $base_discount_cost = (1-$discount / 100) * $dc_price;
  299. } elseif ($type == $this->coupon_type_direct) { // 直接折扣
  300. // $base_discount_cost = $dc_price - $discount;
  301. $base_discount_cost = $discount;
  302. }
  303. $curr_discount_cost = Yii::$service->page->currency->getCurrentCurrencyPrice($base_discount_cost);
  304. }
  305. }
  306. return [
  307. 'baseCost' => $base_discount_cost,
  308. 'currCost' => $curr_discount_cost,
  309. ];
  310. }
  311. /**
  312. * @param $type | String add or cancel
  313. * @return bool
  314. * 增加或者减少优惠券使用的次数
  315. */
  316. protected function updateCouponUse($type)
  317. {
  318. if ($this->_customer_id) {
  319. $c_model = $this->getCouponModel();
  320. if ($c_model) {
  321. if ($type == 'add') {
  322. $cu_model = $this->getCouponUsageModel();
  323. if (!$cu_model) {
  324. $cu_model = new $this->_couponUsageModelName;
  325. $cu_model->times_used = 1;
  326. $cu_model->customer_id = $this->_customer_id;
  327. $cu_model->coupon_id = $c_model['coupon_id'];
  328. $cu_model->save();
  329. } else {
  330. // 通过update函数 将times_used +1
  331. $sql = 'update '.$this->_couponUsageModel->tableName().' set times_used = times_used + 1 where id = :id';
  332. $data = [
  333. 'id' => $cu_model['id'],
  334. ];
  335. $result = $this->_couponUsageModel->getDb()->createCommand($sql, $data)->execute();
  336. }
  337. // coupon的总使用次数+1
  338. $sql = 'update '.$this->_couponModel->tableName().' set times_used = times_used + 1 where coupon_id = :coupon_id ';
  339. $data = [
  340. 'coupon_id' => $c_model['coupon_id'],
  341. ];
  342. $result = $this->_couponModel->getDb()->createCommand($sql, $data)->execute();
  343. return true;
  344. } elseif ($type == 'cancel') {
  345. $couponModel = $this->getCouponModel();
  346. $cu_model = $this->getCouponUsageModel();
  347. if ($cu_model) {
  348. // $this->_couponUsageModel 使用次数-1
  349. $sql = 'update '.$this->_couponUsageModel->tableName().' set times_used = times_used - 1 where id = :id';
  350. $data = [
  351. 'id' => $cu_model['id'],
  352. ];
  353. $result = $this->_couponUsageModel->getDb()->createCommand($sql, $data)->execute();
  354. // $this->_couponModel 使用次数-1
  355. $sql = 'update '.$this->_couponModel->tableName().' set times_used = times_used - 1 where coupon_id = :coupon_id ';
  356. $data = [
  357. 'coupon_id' => $c_model['coupon_id'],
  358. ];
  359. $result = $this->_couponModel->getDb()->createCommand($sql, $data)->execute();
  360. return true;
  361. }
  362. }
  363. }
  364. }
  365. }
  366. /**
  367. * @param $coupon_code | String 优惠卷码
  368. * 检查当前购物车中是否存在优惠券,如果存在,则覆盖当前的优惠券
  369. * 如果当前购物车没有使用优惠券,则检查优惠券是否可以使用
  370. * 如果优惠券可以使用,则使用优惠券进行打折。更新购物车信息。
  371. */
  372. protected function actionAddCoupon($coupon_code)
  373. {
  374. $this->useCouponInit($coupon_code);
  375. if ($this->couponIsActive()) {
  376. $couponModel = $this->getCouponModel();
  377. $type = $couponModel['type'];
  378. $conditions = $couponModel['conditions'];
  379. $discount = $couponModel['discount'];
  380. // 判断购物车金额是否满足条件
  381. $cartProduct = Yii::$service->cart->quoteItem->getCartProductInfo();
  382. $product_total = isset($cartProduct['product_total']) ? $cartProduct['product_total'] : 0;
  383. if ($product_total) {
  384. //var_dump($product_total);
  385. $dc_price = Yii::$service->page->currency->getBaseCurrencyPrice($product_total);
  386. if ($dc_price > $conditions) {
  387. // 更新购物侧的coupon 和优惠券的使用情况。
  388. // 在service中不要出现事务等操作。在调用层使用。
  389. //$innerTransaction = Yii::$app->db->beginTransaction();
  390. //try {
  391. $set_status = Yii::$service->cart->quote->setCartCoupon($coupon_code);
  392. $up_status = $this->updateCouponUse('add');
  393. if ($set_status && $up_status) {
  394. //$innerTransaction->commit();
  395. return true;
  396. } else {
  397. Yii::$service->helper->errors->add('add coupon fail');
  398. }
  399. //Yii::$service->helper->errors->add('add coupon fail');
  400. //$innerTransaction->rollBack();
  401. //} catch (\Exception $e) {
  402. //Yii::$service->helper->errors->add('add coupon fail');
  403. //$innerTransaction->rollBack();
  404. //}
  405. } else {
  406. Yii::$service->helper->errors->add('The coupon can not be used if the product amount in the shopping cart is less than {conditions} dollars', ['conditions' => $conditions]);
  407. }
  408. }
  409. } else {
  410. Yii::$service->helper->errors->add('Coupon is not available or has expired');
  411. }
  412. }
  413. /**
  414. * @param $coupon_code | String
  415. * 取消优惠券
  416. */
  417. protected function actionCancelCoupon($coupon_code)
  418. {
  419. $this->useCouponInit($coupon_code);
  420. if ($this->_customer_id) {
  421. $couponModel = $this->getCouponModel($coupon_code);
  422. if ($couponModel) {
  423. $up_status = $this->updateCouponUse('cancel');
  424. $cancel_status = Yii::$service->cart->quote->cancelCartCoupon($coupon_code);
  425. if ($up_status && $cancel_status) {
  426. return true;
  427. }
  428. }
  429. }
  430. }
  431. }