AddonsCouponUserRelate.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. <?php
  2. namespace addons\Coupon\common\models;
  3. use addons\Coupon\common\enums\AddonsCouponEnum;
  4. use addons\Store\common\enums\StoreEnum;
  5. use addons\Store\common\models\StoreCouponUserRelate;
  6. use common\enums\AddonsEnum;
  7. use common\enums\OrderStatusEnum;
  8. use common\enums\RedisKeyEnum;
  9. use common\enums\StatusEnum;
  10. use common\helpers\LockHelper;
  11. use common\models\mall\MallAddons;
  12. use common\models\user\User;
  13. use Exception;
  14. use Yii;
  15. /**
  16. * This is the model class for table "{{%addons_coupon_user_relate}}".
  17. *
  18. * @property int $id
  19. * @property int $mall_id
  20. * @property int $user_id 用户
  21. * @property int $coupon_id 优惠卷
  22. * @property int $coupon_status 优惠券状态,2:领取中,3:已过期,4:已失效(后台操作失效、转赠被领取后、使用之后)
  23. * @property int $status 状态[-1:删除;0:禁用;1启用]
  24. * @property int $is_giving 是否已赠送:0-否;1-是;
  25. * @property int $giving_status 转赠状态,0:未转赠,1:转赠中,2:已被领取(转赠完成)
  26. * @property string $receive_type 获取方式,如"商品详情页领取"
  27. * @property string $receive_platform 领取来源,从哪个平台领取的,wechat:微信,mp-wx:微信小程序,h5,app,work-wx:企业微信
  28. * @property int $is_force_failure 是否强制失效,后台操作用户已领取的优惠券失效
  29. * @property int $is_send_reward 是否已经发放优惠券奖励,1:是,0:否
  30. * @property int $created_at 创建时间
  31. * @property int $updated_at
  32. * @property int $give_time 转赠次数
  33. * @property int $start_time 优惠券开始生效时间
  34. * @property int $end_time 优惠券过期时间
  35. * @property int $is_use 是否已使用:0=未使用,1=已使用
  36. * @property string $mch_id
  37. */
  38. class AddonsCouponUserRelate extends \common\models\base\BaseActiveRecord
  39. {
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public static function tableName()
  44. {
  45. return '{{%addons_coupon_user_relate}}';
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function rules()
  51. {
  52. return [
  53. [['mall_id', 'user_id', 'coupon_id'], 'required'],
  54. [['mall_id', 'user_id', 'coupon_id', 'coupon_status', 'status', 'is_giving', 'giving_status', 'is_force_failure', 'is_send_reward', 'created_at', 'updated_at', 'start_time', 'end_time', 'is_use','give_time'], 'integer'],
  55. [['receive_type'], 'string', 'max' => 255],
  56. [['receive_platform'], 'string', 'max' => 25],
  57. [['mch_id'], 'string'],
  58. [['store_id'], 'safe'],
  59. ];
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function attributeLabels()
  65. {
  66. return [
  67. 'id' => 'ID',
  68. 'mall_id' => '商城ID',
  69. 'user_id' => '会员ID',
  70. 'coupon_id' => '优惠券ID',
  71. 'coupon_status' => '优惠券状态',
  72. 'status' => 'Status',
  73. 'is_giving' => '优惠券是否已转赠',
  74. 'giving_status' => '转赠状态',
  75. 'receive_type' => '领取场景',
  76. 'receive_platform' => '领取平台',
  77. 'is_force_failure' => '是否已被强制失效',
  78. 'is_send_reward' => '是否已发放奖励',
  79. 'give_time'=>'转赠次数',
  80. 'created_at' => 'Created At',
  81. 'updated_at' => 'Updated At',
  82. 'start_time' => '有效期开始时间',
  83. 'end_time' => '有效期结束时间',
  84. 'is_use' => '是否已使用',
  85. 'mch_id' => '商户id',
  86. ];
  87. }
  88. /**
  89. * @return ActiveQueryInterface the relational query object.
  90. */
  91. public function getUser()
  92. {
  93. return $this->hasOne(User::class, ['id' => 'user_id']);
  94. }
  95. /**
  96. * 商品
  97. * @return \yii\db\ActiveQuery
  98. */
  99. public function getCoupon()
  100. {
  101. return $this->hasOne(AddonsCoupon::class, ['id' => 'coupon_id']);
  102. // ->where(['status' => StatusEnum::ENABLED]);
  103. }
  104. /**
  105. * 保存数据
  106. * @Author: zhengjianhua
  107. * @DateTime: 2021/12/18 0018 11:13
  108. * @Copyright: copyright (c) 2021 广东七件事集团
  109. * @param $params
  110. * @return AddonsCoupon|bool
  111. * @throws \yii\db\Exception
  112. */
  113. public static function setData($params)
  114. {
  115. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON , $params['coupon_id']);
  116. $identification = uniqid();
  117. $t = Yii::$app->db->beginTransaction();
  118. try {
  119. if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
  120. $where[] = ['id' => $params['coupon_id'], 'mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED];
  121. $coupon_model = AddonsCoupon::getOne($where);
  122. if (empty($coupon_model)) throw new Exception('该优惠券不存在');
  123. if($coupon_model["coupon_status"]==AddonsCouponEnum::STATUS_NOT_BEGIN) throw new Exception('该优惠券不能领取');
  124. if($coupon_model["coupon_status"]==AddonsCouponEnum::STATUS_EXPIRED) throw new Exception('该优惠券已过期');
  125. if($coupon_model["coupon_status"]==AddonsCouponEnum::STATUS_FAILURE) {
  126. $message = '该优惠券已失效';
  127. // 判断用户是否领取过优惠券
  128. $counts = self::find()->where(['mall_id' => $params['mall_id'],'user_id' => $params['user_id'],'coupon_id' => $params['coupon_id']])->count();
  129. if ($counts) {
  130. $message = '您已领取过优惠券';
  131. }
  132. throw new Exception($message);
  133. }
  134. if ($coupon_model["total_count"] <= 0){
  135. $coupon_model->status = StatusEnum::DISABLED;
  136. $coupon_model->save();
  137. $t->commit();
  138. throw new Exception('该优惠券被领完啦');
  139. }
  140. if ($params['num'] > $coupon_model['total_count']){
  141. throw new Exception('该优惠券数量不足');
  142. }
  143. if($coupon_model['is_receive_limit']){
  144. $counts= self::find()->where(['mall_id'=>$params['mall_id'],'user_id'=>$params['user_id'],'coupon_id'=>$params['coupon_id']])->count();
  145. if(($counts+$params['num'])>$coupon_model['receive_count'])throw new Exception('每人只可以领取'.$coupon_model['receive_count'].'张');
  146. }
  147. if($coupon_model['is_member']){
  148. $member_relate_list = AddonsCouponMemberRelate::lists(['where'=>[['mall_id'=>$params['mall_id']],['coupon_id'=>$coupon_model['id']]], 'select' => 'member_level']);
  149. $level_arr = array_column($member_relate_list,'member_level');
  150. if(!in_array($params['user']['level'],$level_arr))throw new Exception('该优惠券指定会员等级');
  151. }
  152. $time = time();
  153. switch ($coupon_model['expire_type']){
  154. case AddonsCouponEnum::EXPIRE_TYPE2:
  155. $params['start_time'] = $coupon_model['begin_at'];
  156. $params['end_time'] = $coupon_model['end_at'];
  157. break;
  158. case AddonsCouponEnum::EXPIRE_TYPE1:
  159. $params['start_time'] = $time;
  160. $params['end_time'] = $coupon_model['expire_day'] * 86400 + $time;
  161. break;
  162. case AddonsCouponEnum::EXPIRE_TYPE3:
  163. $params['start_time'] = $coupon_model['effect_days'] * 86400 + $time;
  164. $params['end_time'] = $coupon_model['expire_day'] * 86400 + $params['start_time'];
  165. break;
  166. default:
  167. throw new Exception('有效期时间设置不对');
  168. }
  169. $coupon_user_relate = null;
  170. if (!empty($params['coupon_id'])) {
  171. $insert = [];
  172. $remind_datas = [];
  173. $now = time();
  174. for ($i = 0; $i < $params['num']; $i++) {
  175. $insert[] = [ $params['mall_id'], $params['user_id'], $params['coupon_id'], $coupon_model['coupon_status'], 1, $params['start_time'], $params['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($params['receive_type'], $params['mall_id']), $params['receive_platform'], 0, 0, $now, $now,$coupon_model['mch_id'] ];
  176. $remind_datas[] = [$params['mall_id'], $params['user_id'], $params['coupon_id'], $params['end_time'], 1, 1, $now, $now];
  177. }
  178. $field = ['mall_id','user_id','coupon_id', 'coupon_status', 'status','start_time','end_time','is_use','is_giving','giving_status', 'receive_type','receive_platform', 'is_force_failure','is_send_reward', 'created_at', 'updated_at','mch_id'];
  179. // 批量插入数据
  180. $res = Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $insert)->execute();
  181. if($res==false) throw new Exception('领取失败');
  182. $coupon_user_relate = AddonsCouponUserRelate::getOne([
  183. [ 'user_id'=>$params['user_id']],
  184. ['mall_id'=>$params['mall_id']],
  185. ['coupon_id'=>$params['coupon_id']]
  186. ],true,[],'id desc');
  187. $total_count = $coupon_model->total_count - $params['num'];
  188. $coupon_model->total_count = $total_count >= 0 ? $total_count : 0;
  189. $res = $coupon_model->save();
  190. if($res==false) throw new Exception('领取失败 ' . $coupon_model->getErrotMessage());
  191. if (1 == $coupon_model->is_remind && !empty($remind_datas)) {
  192. $remind_fields = ['mall_id', 'user_id', 'coupon_id', 'expire_time', 'status', 'send_status', 'created_at', 'updated_at'];
  193. $remind_table_name = (new AddonsCouponRemind())->tableSchema->name;
  194. Yii::$app->db->createCommand()->batchInsert($remind_table_name, $remind_fields, $remind_datas)->execute();
  195. }
  196. }
  197. LockHelper::ulock($lock_key,$identification);
  198. $t->commit();
  199. return $coupon_user_relate;
  200. } catch (Exception $e) {
  201. LockHelper::ulock($lock_key,$identification);
  202. $t->rollBack();
  203. self::$static_error = $e->getMessage();
  204. return false;
  205. }
  206. }
  207. /**
  208. * @desc:领取别人赠与
  209. * @Author: hua
  210. * @Date: 2021/12/24
  211. * @Time: 17:38
  212. * @Copyright: copyright (c) 2021 广东七件事集团
  213. * @param $params
  214. * @return AddonsCoupon|false|null
  215. */
  216. public static function receiveByGive($params)
  217. {
  218. $t = Yii::$app->db->beginTransaction();
  219. try {
  220. $share_log_model = AddonsCouponShareLog::findOne(['id'=>$params['coupon_share_log_id']]);
  221. if (empty($share_log_model)) throw new Exception('未找到转赠记录');
  222. $params['user_coupon_id'] = $share_log_model->user_coupon_id;
  223. $where[] = ['id' => $params['user_coupon_id'], 'mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED];
  224. $coupon_user_relate_model = AddonsCouponUserRelate::getOne($where);
  225. if (empty($coupon_user_relate_model)) throw new Exception('该优惠券不存在');
  226. if ($coupon_user_relate_model['user_id'] == $params['user_id']) throw new Exception('不能领取自己分享的优惠券');
  227. if($coupon_user_relate_model["coupon_status"]==AddonsCouponEnum::STATUS_EXPIRED) throw new Exception('该优惠券已过期');
  228. if($coupon_user_relate_model["coupon_status"]==AddonsCouponEnum::STATUS_FAILURE) throw new Exception('该优惠券已失效');
  229. if($coupon_user_relate_model["is_use"]==1) throw new Exception('该优惠券已被赠送者使用');
  230. if($coupon_user_relate_model["is_giving"]==0) throw new Exception('该优惠券没有被赠送者送出');
  231. if($coupon_user_relate_model["giving_status"]==AddonsCouponEnum::GIVING_STATUS2) throw new Exception('该优惠券已被领取');
  232. $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_user_relate_model['coupon_id']]);
  233. if($coupon_model['is_member']){
  234. $member_relate_list = AddonsCouponMemberRelate::lists(['where'=>[['mall_id'=>$params['mall_id']],['coupon_id'=>$coupon_model['id']]], 'select' => 'member_level']);
  235. $level_arr = array_column($member_relate_list,'member_level');
  236. $receiveUserInfo = User::findOne(['id' => $params['user_id']]);
  237. if(!in_array($receiveUserInfo['level'],$level_arr))throw new Exception('该优惠券指定会员等级');
  238. }
  239. if (1 == $coupon_model['is_receive_limit']) {
  240. $received_counts = AddonsCouponUserRelate::find()
  241. ->where(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED, 'coupon_id' => $coupon_model['id']])
  242. ->andWhere(['or', ['is_giving' => 0], ['is_giving' => 1, 'giving_status' => [AddonsCouponEnum::GIVING_STATUS0,AddonsCouponEnum::GIVING_STATUS1]]])
  243. ->count();
  244. if(!empty($params['direct_gift'])){
  245. if ($coupon_model['receive_count'] > 0 && $received_counts >= $coupon_model['receive_count']) throw new Exception('对方已经领取过了');
  246. }else{
  247. if ($coupon_model['receive_count'] > 0 && $received_counts >= $coupon_model['receive_count']) throw new Exception('你已经领取过了');
  248. }
  249. }
  250. $now = time();
  251. if(!empty($coupon_model->store_id)){
  252. $coupon_user_model = new StoreCouponUserRelate();
  253. $coupon_user_model->from_type = 1;
  254. }else{
  255. $coupon_user_model = new self();
  256. $coupon_user_model->mch_id = $coupon_model->mch_id;
  257. }
  258. $coupon_user_model->mall_id = $params['mall_id'];
  259. $coupon_user_model->user_id = $params['user_id'];
  260. $coupon_user_model->coupon_id = $coupon_user_relate_model['coupon_id'];
  261. $coupon_user_model->coupon_status = $coupon_user_relate_model['coupon_status'];
  262. $coupon_user_model->status = 1;
  263. $coupon_user_model->start_time = $coupon_user_relate_model['start_time'];
  264. $coupon_user_model->end_time = $coupon_user_relate_model['end_time'];
  265. $coupon_user_model->is_use = 0;
  266. $coupon_user_model->is_giving = 0;
  267. $coupon_user_model->giving_status = 0;
  268. $coupon_user_model->receive_type = AddonsCouponEnum::getSendFromMap(AddonsCouponEnum::SEND_FROM6, $params['mall_id']).',赠送者ID:'.$share_log_model->giving_user_id;
  269. $coupon_user_model->receive_platform = $params['receive_platform'];
  270. $coupon_user_model->is_force_failure = 0;
  271. $coupon_user_model->is_send_reward = 0;
  272. $coupon_user_model->created_at = $now;
  273. $coupon_user_model->updated_at = $now;
  274. $coupon_user_model->store_id = !empty($coupon_model->store_id) ? $coupon_model->store_id : 0;
  275. $res = $coupon_user_model->save();
  276. if($res==false) throw new Exception($coupon_user_model->getErrorMessage());
  277. $share_data = [
  278. 'mall_id' => $params['mall_id'],
  279. 'coupon_share_log_id' => $params['coupon_share_log_id'],
  280. 'get_user_coupon_id' => $coupon_user_model->id,
  281. 'receive_user_id' => $params['user_id'],
  282. ];
  283. $res = AddonsCouponShareLog::setData($share_data);
  284. if($res==false) throw new Exception($share_log_model->getErrorMessage());
  285. $coupon_user_relate_model->giving_status = AddonsCouponEnum::GIVING_STATUS2;
  286. $coupon_user_relate_model->coupon_status = AddonsCouponEnum::STATUS_FAILURE;
  287. $res = $coupon_user_relate_model->save();
  288. if($res==false) throw new Exception('更新赠送者优惠券状态失败');
  289. if (1 == $coupon_model['is_remind']) {
  290. $remind_datas[] = [$params['mall_id'], $params['coupon_id'], $params['user_id'], $coupon_user_relate_model['end_time'], 1, 1, $now, $now];
  291. $remind_fields = ['mall_id', 'coupon_id', 'user_id', 'expire_time', 'status', 'send_status', 'created_at', 'updated_at'];
  292. $remind_table_name = (new AddonsCouponRemind())->tableSchema->name;
  293. Yii::$app->db->createCommand()->batchInsert($remind_table_name, $remind_fields, $remind_datas)->execute();
  294. }
  295. $t->commit();
  296. return $coupon_user_model;
  297. } catch (Exception $e) {
  298. $t->rollBack();
  299. self::$static_error = $e->getMessage();
  300. return false;
  301. }
  302. }
  303. /**
  304. * 更新
  305. * @param $params
  306. * @return bool
  307. */
  308. public static function updateData($params)
  309. {
  310. try {
  311. $count = self::updateAll($params['fields'], ['coupon_id' => $params['coupon_id'], 'user_id' => $params['user_id']]);
  312. if (!$count) return false;
  313. return true;
  314. } catch (Exception $e) {
  315. self::$static_error = $e->getMessage();
  316. return false;
  317. }
  318. }
  319. /**
  320. * 转送
  321. * @param $params
  322. * @return bool
  323. * @throws \yii\db\Exception
  324. */
  325. /*
  326. public static function transfer($params)
  327. {
  328. $t = \Yii::$app->db->beginTransaction();
  329. try {
  330. $model = self::findOne($params['user_coupon_id']);
  331. if (empty($model)) throw new Exception('查无数据');
  332. $model->status = StatusEnum::DELETE;
  333. $model->save();
  334. $data = [
  335. 'coupon_id' => $model->coupon_id,
  336. 'user_id' => $params['user_id'],
  337. 'is_use' => 0,
  338. 'from' => ReceiveTypeEnum::TRANSFER,
  339. 'extra' => '来源user_coupon_id是:' . $params['user_coupon_id'],
  340. 'end_time' => $params['end_time'],
  341. ];
  342. $model = new self();
  343. if (!$model->load($data, '') || !$model->save()) throw new Exception($model->getErrorMessage());
  344. $model->save();
  345. $t->commit();
  346. return true;
  347. } catch (Exception $e) {
  348. $t->rollBack();
  349. self::$static_error = $e->getMessage();
  350. return false;
  351. }
  352. }
  353. */
  354. /**
  355. * @desc:购买商品赠送优惠券
  356. * @Author: hua
  357. * @Date: 2021/12/3
  358. * @Time: 15:42
  359. * @Copyright: copyright (c) 2021 广东七件事集团
  360. * @param $mall_id
  361. * @param $goods_ids
  362. * @param $user_id
  363. * @param string $order_id
  364. * @param int $order_status
  365. * @return false
  366. */
  367. public static function BuyGoodsGiveCoupon($mall_id, $goods_ids, $user_id,$order_id='', $order_status = OrderStatusEnum::ACCOMPLISH)
  368. {
  369. try {
  370. $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
  371. if (!$is_install) return false;
  372. $params = [
  373. 'where'=>[['mall_id' => $mall_id],['item_id' => $goods_ids],[ 'is_enable' => 1],['status' => StatusEnum::ENABLED], ['item_type' => 'goods']],
  374. 'with'=>['detail'=>function($query){
  375. $query->where(['status'=>StatusEnum::ENABLED]);
  376. }],
  377. ];
  378. $give_item_setting_list = CouponGiveItemSetting::lists($params);
  379. if (empty($give_item_setting_list)) return false;
  380. $give_coupon_arr = [];
  381. foreach ($give_item_setting_list as $give_item_setting) {
  382. // 如果当前订单状态为完成,但是仅限于支付完成赠送或者当前订单状态为支付,但是仅限于订单完成赠送,那么就不执行赠送
  383. if ($order_status == OrderStatusEnum::ACCOMPLISH && $give_item_setting['send_type'] == StatusEnum::ENABLED ||
  384. $order_status == OrderStatusEnum::PAY && $give_item_setting['send_type'] == StatusEnum::DISABLED) continue;
  385. foreach ($give_item_setting['detail'] as $item) {
  386. if (isset($give_coupon_arr[$item['coupon_id']])) {
  387. $give_coupon_arr[$item['coupon_id']] += $item['num'];
  388. } else {
  389. $give_coupon_arr[$item['coupon_id']] = $item['num'];
  390. }
  391. }
  392. }
  393. if (count($give_coupon_arr) > 0) {
  394. $res = self::giveCoupon($mall_id,$user_id,$give_coupon_arr,AddonsCouponEnum::SEND_FROM2,'platform');
  395. if($res==false) throw new \Exception('购买商品-订单完成order_id'.$order_id.'-赠送优惠券失败');
  396. }
  397. } catch (\Exception $e) {
  398. self::setStaticError($e->getMessage());
  399. return false;
  400. }
  401. }
  402. //订单满额赠送
  403. public static function FullAmountGiveCoupon($mall_id, $user_id, $config = '', $order_id = '' )
  404. {
  405. try {
  406. $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
  407. if (!$is_install) return false;
  408. if (empty($config)) return false;
  409. $config = json_decode($config, true);
  410. if (empty($config['multiple_selection'])) return false;
  411. $params = [
  412. 'where'=>[['mall_id' => $mall_id],['item_id' => $order_id],[ 'is_enable' => 0],['status' => StatusEnum::ENABLED], ['item_type' => 'order']],
  413. ];
  414. $give_item_setting_list = CouponGiveItemSetting::lists($params);
  415. if (!empty($give_item_setting_list)) return false;
  416. $give_coupon_arr = [];
  417. foreach ($config['multiple_selection'] as $key => $value) {
  418. $give_coupon_arr[$value['relevant_id']] = $value['num'];
  419. }
  420. if (!empty($give_coupon_arr)) {
  421. $res = self::giveCoupon($mall_id,$user_id,$give_coupon_arr,AddonsCouponEnum::SEND_FROM18,'platform');
  422. if($res===false) throw new \Exception('订单满额赠送order_id'.$order_id.'-赠送优惠券失败');
  423. }
  424. $result = Yii::$app->db->createCommand()->insert(CouponGiveItemSetting::tableName(),[
  425. 'mall_id' => $mall_id,
  426. 'item_id' => $order_id,
  427. 'is_enable' => 0,
  428. 'status' => StatusEnum::ENABLED,
  429. 'item_type' => 'order',
  430. 'send_type' => 0,
  431. 'created_at' => time(),
  432. 'updated_at' => time()])->execute();
  433. } catch (\Exception $e) {
  434. self::setStaticError($e->getMessage());
  435. print_r($e->getMessage());
  436. return false;
  437. }
  438. }
  439. /**
  440. * @desc:赠送优惠券
  441. * @Author: hua
  442. * @Date: 2021/12/6
  443. * @Time: 11:33
  444. * @Copyright: copyright (c) 2021 广东七件事集团
  445. * @param $mall_id
  446. * @param $user_id
  447. * @param $give_coupon_arr //$give_coupon_arr=['coupon_id'=>'num'];
  448. * @param $receive_type
  449. * @param $receive_platform
  450. * @return array|bool
  451. */
  452. public static function giveCouponOld($mall_id, $user_id,$give_coupon_arr,$receive_type =2,$receive_platform='platform')
  453. {
  454. $trans = Yii::$app->db->beginTransaction();
  455. $locks = [];
  456. try {
  457. $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
  458. if (!$is_install) throw new Exception('优惠券并未安装');
  459. $coupon_id_arr = array_keys($give_coupon_arr);
  460. $coupon_list = AddonsCoupon::findAll(['mall_id' => $mall_id, 'id' => $coupon_id_arr, 'status' => StatusEnum::ENABLED, 'coupon_status' => AddonsCouponEnum::STATUS_RECEIVING]);
  461. if (empty($coupon_list)) throw new Exception('暂无可用优惠券');
  462. $user = User::findOne(['id' => $user_id]);
  463. $can_give_coupon_arr = [];
  464. $time = time();
  465. foreach ($coupon_list as $coupon) {
  466. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON , $coupon['id']);
  467. $identification = uniqid();
  468. if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
  469. $locks[$lock_key] = $identification;
  470. if ($coupon['expire_type'] == 2 && $coupon['end_at'] <= $time) continue;
  471. if ($coupon['total_count'] <= 0) continue;
  472. $member_level_arr = array_column($coupon['memberRelate'], 'level');
  473. if(!empty($member_level_arr)&&!in_array($user['level'], $member_level_arr))continue;
  474. $time = time();
  475. switch ($coupon['expire_type']){
  476. case AddonsCouponEnum::EXPIRE_TYPE2:
  477. $start_time = $time;
  478. $end_time = $coupon['end_at'];
  479. break;
  480. case AddonsCouponEnum::EXPIRE_TYPE1:
  481. $start_time = $time;
  482. $end_time = $coupon['expire_day'] * 86400 + $time;
  483. break;
  484. case AddonsCouponEnum::EXPIRE_TYPE3:
  485. $start_time = $coupon['effect_days'] * 86400 + $time;
  486. $end_time = $coupon['expire_day'] * 86400 + $start_time;
  487. break;
  488. default:
  489. throw new Exception('有效期时间设置不对');
  490. }
  491. $can_give_coupon_arr[$coupon['id']] = [
  492. 'num' => $give_coupon_arr[$coupon['id']],
  493. 'start_time' => $start_time,
  494. 'end_time' => $end_time,
  495. 'total_count' => $coupon['total_count'],
  496. 'name' => $coupon['name'],
  497. 'coupon_status' => $coupon['coupon_status'],
  498. ];
  499. }
  500. $field = ['mall_id','user_id','coupon_id', 'coupon_status', 'status','start_time','end_time','is_use','is_giving','giving_status', 'receive_type','receive_platform', 'is_force_failure','is_send_reward', 'created_at', 'updated_at'];
  501. $insert = [];
  502. foreach ($can_give_coupon_arr as $coupon_id => $item) {
  503. $num = $item['num'];
  504. if($item['total_count']<$item['num']) $num = $item['total_count'];
  505. for ($i = 0; $i < $num; $i++) {
  506. $insert[] = [ $mall_id, $user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
  507. }
  508. $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_id]);
  509. $coupon_model->total_count -= $num;
  510. $res = $coupon_model->save();
  511. if($res==false) throw new \Exception('赠送优惠券失败');
  512. }
  513. if (!empty($insert)) {
  514. $res = Yii::$app->db->createCommand()->batchInsert(AddonsCouponUserRelate::tableName(), $field, $insert)->execute();
  515. if ($res==false) {
  516. throw new \Exception('赠送优惠券失败');
  517. }
  518. }
  519. $trans->commit();
  520. LockHelper::batchUlock($locks);
  521. return $can_give_coupon_arr;
  522. } catch (\Exception $e) {
  523. $trans->rollBack();
  524. LockHelper::batchUlock($locks);
  525. self::setStaticError($e->getMessage());
  526. return false;
  527. }
  528. }
  529. public static function giveCoupon($mall_id, $user_id,$give_coupon_arr,$receive_type =2,$receive_platform='platform')
  530. {
  531. $trans = Yii::$app->db->beginTransaction();
  532. $locks = [];
  533. try {
  534. $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
  535. if (!$is_install) throw new Exception('优惠券并未安装');
  536. $coupon_id_arr = array_keys($give_coupon_arr);
  537. $coupon_list = AddonsCoupon::findAll(['mall_id' => $mall_id, 'id' => $coupon_id_arr, 'status' => StatusEnum::ENABLED, 'coupon_status' => AddonsCouponEnum::STATUS_RECEIVING]);
  538. if (empty($coupon_list)) throw new Exception('暂无可用优惠券');
  539. $user = User::findOne(['id' => $user_id]);
  540. $can_give_coupon_arr = [];
  541. $time = time();
  542. foreach ($coupon_list as $coupon) {
  543. $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON , $coupon['id']);
  544. $identification = uniqid();
  545. if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
  546. $locks[$lock_key] = $identification;
  547. if ($coupon['expire_type'] == 2 && $coupon['end_at'] <= $time) continue;
  548. if ($coupon['total_count'] <= 0) continue;
  549. $member_level_arr = array_column($coupon['memberRelate'], 'level');
  550. if(!empty($member_level_arr)&&!in_array($user['level'], $member_level_arr))continue;
  551. $time = time();
  552. switch ($coupon['expire_type']){
  553. case AddonsCouponEnum::EXPIRE_TYPE2:
  554. $start_time = $time;
  555. $end_time = $coupon['end_at'];
  556. break;
  557. case AddonsCouponEnum::EXPIRE_TYPE1:
  558. $start_time = $time;
  559. $end_time = $coupon['expire_day'] * 86400 + $time;
  560. break;
  561. case AddonsCouponEnum::EXPIRE_TYPE3:
  562. $start_time = $coupon['effect_days'] * 86400 + $time;
  563. $end_time = $coupon['expire_day'] * 86400 + $start_time;
  564. break;
  565. default:
  566. throw new Exception('有效期时间设置不对');
  567. }
  568. if(!empty($coupon['store_id'])){
  569. $give_destination = StoreCouponUserRelate::tableName();
  570. // $give_destination_model = StoreCouponUserRelate::find();
  571. }else{
  572. $give_destination = AddonsCouponUserRelate::tableName();
  573. // $give_destination_model = AddonsCouponUserRelate::find();
  574. // //获取用户已领取的数量
  575. // $user_have_num = $give_destination_model->where(['status' => StatusEnum::ENABLED, 'coupon_id' => $coupon['id'], 'mall_id' => $mall_id, 'user_id' => $user_id])->count();
  576. // //如果优惠券限制可领取数量,用户已领取的优惠券超过限制数量则跳过领取
  577. // if ($coupon['is_receive_limit'] == 1 && $user_have_num >= $coupon['receive_count']) continue;
  578. }
  579. $can_give_coupon_arr[$coupon['id']] = [
  580. 'num' => $give_coupon_arr[$coupon['id']],
  581. 'start_time' => $start_time,
  582. 'end_time' => $end_time,
  583. 'total_count' => $coupon['total_count'],
  584. 'name' => $coupon['name'],
  585. 'store_id' => $coupon['store_id'],
  586. 'coupon_status' => $coupon['coupon_status'],
  587. 'give_destination' => $give_destination,
  588. ];
  589. }
  590. $field = ['mall_id','user_id','coupon_id', 'coupon_status', 'status','start_time','end_time','is_use','is_giving','giving_status', 'receive_type','receive_platform', 'is_force_failure','is_send_reward', 'created_at', 'updated_at'];
  591. $insert = [];
  592. $insert_store = [];
  593. foreach ($can_give_coupon_arr as $coupon_id => $item) {
  594. switch ($item['give_destination']){
  595. case AddonsCouponUserRelate::tableName():
  596. $num = $item['num'];
  597. if($item['total_count']<$item['num']) $num = $item['total_count'];
  598. for ($i = 0; $i < $num; $i++) {
  599. $insert[] = [ $mall_id, $user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
  600. }
  601. break;
  602. case StoreCouponUserRelate::tableName():
  603. $num = $item['num'];
  604. if($item['total_count']<$item['num']) $num = $item['total_count'];
  605. for ($i = 0; $i < $num; $i++) {
  606. $insert_store[] = [$mall_id, $item['store_id'],1,$user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
  607. }
  608. break;
  609. }
  610. $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_id]);
  611. $coupon_model->total_count -= $num;
  612. $res = $coupon_model->save();
  613. if($res==false) throw new \Exception('赠送优惠券失败');
  614. }
  615. if (!empty($insert)) {
  616. $res = Yii::$app->db->createCommand()->batchInsert(AddonsCouponUserRelate::tableName(), $field, $insert)->execute();
  617. if ($res==false) {
  618. throw new \Exception('赠送优惠券失败');
  619. }
  620. }
  621. if (!empty($insert_store)) {
  622. $field = ['mall_id', 'store_id', 'from_type', 'user_id', 'coupon_id', 'coupon_status', 'status', 'start_time', 'end_time', 'is_use', 'is_giving', 'giving_status', 'receive_type', 'receive_platform', 'is_force_failure', 'is_send_reward', 'created_at', 'updated_at'];
  623. // 批量插入数据
  624. $res = Yii::$app->db->createCommand()->batchInsert(StoreCouponUserRelate::tableName(), $field, $insert_store)->execute();
  625. }
  626. $trans->commit();
  627. LockHelper::batchUlock($locks);
  628. return $can_give_coupon_arr;
  629. } catch (\Exception $e) {
  630. $trans->rollBack();
  631. LockHelper::batchUlock($locks);
  632. self::setStaticError($e->getMessage());
  633. return false;
  634. }
  635. }
  636. /**
  637. * @notes:优惠券状态处理
  638. * @param $params
  639. * @return bool
  640. * @throws \yii\db\Exception
  641. * @author: lun
  642. * @Time: 2022/10/27 9:45
  643. */
  644. public static function handle($params)
  645. {
  646. $trans = Yii::$app->db->beginTransaction();
  647. try {
  648. $model = self::findOne(['mall_id' => $params['mall_id'], 'id' => $params['id'], 'status' => StatusEnum::ENABLED]);
  649. if (empty($model)) throw new Exception('查无此数据');
  650. if ($params['status'] == StatusEnum::DELETE) {
  651. $model->status = $params['status'];
  652. $model->is_force_failure = StatusEnum::ENABLED;
  653. }
  654. if (!$model->save()) throw new \yii\db\Exception($model->getErrorMessage());
  655. $trans->commit();
  656. return true;
  657. } catch (Exception $e) {
  658. $trans->rollBack();
  659. self::setData($e->getMessage());
  660. return false;
  661. }
  662. }
  663. //直接赠送
  664. public static function giveCouponBy2($params){
  665. $t = Yii::$app->db->beginTransaction();
  666. try {
  667. $mall_id = $params['mall_id'];
  668. $coupon_id = $params['coupon_id'];
  669. $user_id = $params['user_id'];
  670. $user_coupon_id = $params['user_coupon_id'];
  671. $receive_user_id = $params['receive_user_id'];
  672. $receive_platform = $params['receive_platform'];
  673. $num = $params['num'];
  674. $config = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_COUPON, 'basic');
  675. if(!empty($config['give_type'])&&$config['give_type']==2){
  676. // $coupon = AddonsCoupon::findOne(['mall_id' => $mall_id, 'id' => $coupon_id, 'coupon_status' => 2, 'status' => StatusEnum::ENABLED]);
  677. $coupon = AddonsCoupon::findOne(['mall_id' => $mall_id, 'id' => $coupon_id]);
  678. if (empty($coupon)) {
  679. throw new Exception('优惠券不存在或者已经失效');
  680. }
  681. if (1 != $coupon->is_giving) {
  682. throw new Exception('优惠券不可转赠');
  683. }
  684. $params = [
  685. 'mall_id' => $mall_id,
  686. 'coupon_id' => $coupon_id,
  687. 'user_coupon_id' => $user_coupon_id,
  688. 'giving_user_id' => $user_id,
  689. ];
  690. $res = AddonsCouponShareLog::setData($params);
  691. if($res==false) throw new Exception(AddonsCouponShareLog::getStaticError());
  692. $params = [
  693. 'mall_id'=>$mall_id,
  694. 'coupon_share_log_id'=>$res['id'],
  695. 'coupon_id' => $coupon_id,
  696. 'user_id'=>$receive_user_id,
  697. 'num'=>$num,
  698. 'receive_platform'=>$receive_platform,
  699. 'direct_gift'=>1,
  700. ];
  701. $res = AddonsCouponUserRelate::receiveByGive($params);
  702. if($res==false) throw new Exception(AddonsCouponUserRelate::getStaticError());
  703. }else{
  704. throw new Exception('不支持该赠送方式');
  705. }
  706. $t->commit();
  707. return $res;
  708. }catch (Exception $e){
  709. $t->rollBack();
  710. throw new Exception($e->getMessage());
  711. }
  712. }
  713. public static function fixMchId(){
  714. $list = AddonsCouponUserRelate::lists([
  715. 'where' => [
  716. ['>', 'mall_id', 0]
  717. ],
  718. 'select' => 'coupon_id',
  719. 'group' => 'coupon_id'
  720. ]);
  721. $coupon_ids = array_column($list, 'coupon_id');
  722. $coupon_list = AddonsCoupon::lists(['where' => [['id' => $coupon_ids], ['<>', 'mch_id', '']], 'select' => 'id,mch_id']);
  723. foreach ($coupon_list as $item) {
  724. $res = AddonsCouponUserRelate::updateAll(['mch_id' => $item['mch_id']], ['coupon_id' => $item['id']]);
  725. var_dump($res);
  726. }
  727. }
  728. }