IndexController.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace addons\ElectronCoupon\console\controllers;
  3. use addons\ElectronCoupon\common\models\ElectronCouponGiveLogs;
  4. use addons\ElectronCoupon\common\models\ElectronCouponUserCoupon;
  5. use common\enums\StatusEnum;
  6. use common\models\mall\Mall;
  7. use yii\console\Controller;
  8. use yii\console\ExitCode;
  9. use yii\db\Exception;
  10. class IndexController extends Controller
  11. {
  12. public function actionIndex()
  13. {
  14. try {
  15. // 获取当前系统所有可用的 mall_id
  16. $malls = Mall::getEnableMallList();
  17. foreach ($malls as $mall) {
  18. $params = [
  19. 'where' => [
  20. ['mall_id' => $mall['id']],
  21. ['status' => StatusEnum::ENABLED],
  22. ],
  23. ];
  24. $list = ElectronCouponGiveLogs::lists($params, false);
  25. foreach ($list as $item) {
  26. $created_at = $item['created_at'];
  27. $times = $created_at + $item['share_expiry'] * 3600;
  28. //时间到,退还给赠与者
  29. if (time() >= $times) $this->fallback($item);
  30. }
  31. }
  32. return ExitCode::OK;
  33. } catch (\Exception $e) {
  34. var_dump($e->getMessage());
  35. \Yii::getLogger()->flush(true);
  36. return false;
  37. }
  38. }
  39. public function fallback($item)
  40. {
  41. $t = \Yii::$app->db->beginTransaction();
  42. try {
  43. $type = $item['active_time'] == 0 ? 0 : 1; //该券是否被激活
  44. $model = ElectronCouponUserCoupon::getOne([['e_coupon_id' => $item['e_coupon_id'], 'user_id' => $item['give_user_id'], 'id' => $item['user_e_coupon_id']]], false);
  45. if ($type == 0) {
  46. $model->receive_amount++;
  47. } else {
  48. $model->active_amount++;
  49. }
  50. $model->num++;
  51. $res = $model->save();
  52. if ($res == false) throw new Exception($model->getErrorMessage());
  53. $model = ElectronCouponUserCoupon::findOne(['e_coupon_id' => $item['e_coupon_id'], 'user_id' => $item['user_id'], 'id' => $item['accept_user_e_coupon_id']]);
  54. if ($type == 0) {
  55. $model->receive_amount--;
  56. if ($model->receive_amount < 0) $model->receive_amount = 0;
  57. } else {
  58. $model->active_amount--;
  59. if ($model->active_amount < 0) $model->active_amount = 0;
  60. }
  61. $model->num--;
  62. if ($model->num < 0) $model->num = 0;
  63. $res = $model->save();
  64. if ($res == false) throw new Exception($model->getErrorMessage());
  65. $item->status = StatusEnum::DISABLED;
  66. $item->save();
  67. $t->commit();
  68. return true;
  69. } catch (\Exception $e) {
  70. $t->rollBack();
  71. return false;
  72. }
  73. }
  74. }