CardMainController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. <?php
  2. namespace app\admin\controller\coupon;
  3. use app\admin\service\sys_manage\CategoryService;
  4. use app\controller\Curd;
  5. use app\model\Card;
  6. use app\model\CardIssue;
  7. use app\model\CardMain;
  8. use app\model\Goods;
  9. use app\model\SysDept;
  10. use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
  11. use Illuminate\Database\Query\Builder as QueryBuilder;
  12. use support\Db;
  13. use support\exception\BusinessException;
  14. use support\Log;
  15. use support\Model;
  16. use support\Request;
  17. use support\Response;
  18. use Tinywan\Jwt\JwtToken;
  19. class CardMainController extends Curd
  20. {
  21. public function __construct()
  22. {
  23. $this->model = new CardMain();
  24. }
  25. public function select(Request $request): Response
  26. {
  27. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  28. $order = $request->get('order', 'desc');
  29. $field = $field ?? 'card_main_addtimes';
  30. if (!empty($where['card_main_name'])) {
  31. $where['card_main_name'] = ['like', $where['card_main_name']];
  32. }
  33. if (!empty($where['card_main_addtimes'])) {
  34. $where['card_main_addtimes'][0] = strtotime($where['card_main_addtimes'][0]);
  35. $where['card_main_addtimes'][1] = strtotime($where['card_main_addtimes'][1]);
  36. }
  37. $query = $this->doSelect($where, $field, $order);
  38. return $this->doFormat($query, $format, $limit);
  39. }
  40. /**
  41. * 指定查询where条件,并没有真正的查询数据库操作
  42. * @param array $where
  43. * @param string|null $field
  44. * @param string $order
  45. * @return EloquentBuilder|QueryBuilder|Model
  46. */
  47. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  48. {
  49. $model = $this->model->with('category');
  50. foreach ($where as $column => $value) {
  51. if (is_array($value)) {
  52. if ($value[0] === 'like' || $value[0] === 'not like') {
  53. $model = $model->where($column, $value[0], "%$value[1]%");
  54. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  55. $model = $model->where($column, $value[0], $value[1]);
  56. } elseif ($value[0] == 'in' && !empty($value[1])) {
  57. $valArr = $value[1];
  58. if (is_string($value[1])) {
  59. $valArr = explode(",", trim($value[1]));
  60. }
  61. $model = $model->whereIn($column, $valArr);
  62. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  63. $valArr = $value[1];
  64. if (is_string($value[1])) {
  65. $valArr = explode(",", trim($value[1]));
  66. }
  67. $model = $model->whereNotIn($column, $valArr);
  68. } elseif ($value[0] == 'null') {
  69. $model = $model->whereNull($column);
  70. } elseif ($value[0] == 'not null') {
  71. $model = $model->whereNotNull($column);
  72. } elseif ($value[0] !== '' || $value[1] !== '') {
  73. $model = $model->whereBetween($column, $value);
  74. }
  75. } else {
  76. $model = $model->where($column, $value);
  77. }
  78. }
  79. if ($field) {
  80. $model = $model->orderBy($field, $order);
  81. }
  82. return $model;
  83. }
  84. /**
  85. * @Desc 查询后处理
  86. * @Author Gorden
  87. * @Date 2024/11/15 8:35
  88. *
  89. * @param $items
  90. * @return mixed
  91. */
  92. public function afterQuery($items)
  93. {
  94. foreach ($items as &$item) {
  95. if ($item['card_main_valid_mode'] == 'DAYS') {
  96. $item['valid_term'] = $item['card_main_valid_days'] ? $item['card_main_valid_days'] . '天' : 0;
  97. } elseif ($item['card_main_valid_mode'] == 'LONG') {
  98. $item['valid_term'] = '长期有效';
  99. } elseif ($item['card_main_valid_mode'] == 'DATE') {
  100. $item['valid_term'] = date('Y/m/d', strtotime($item['card_main_valid_begin'])) . '-' . date('Y/m/d', strtotime($item['card_main_valid_end']));
  101. }
  102. $item['total'] = Card::where('join_card_main_id', $item['card_main_id'])->count();
  103. $item['amount'] = sprintf('%.2f', $item['total'] * $item['card_main_amount']);
  104. }
  105. return $items;
  106. }
  107. /**
  108. * @Desc 卡的下拉搜索
  109. * @Author Gorden
  110. * @Date 2024/11/18 9:51
  111. *
  112. * @return Response
  113. */
  114. public function selectList()
  115. {
  116. $cardMain = CardMain::where('card_main_status', 'ACTIVED')
  117. ->orderBy('card_main_addtimes', 'DESC')
  118. ->select('card_main_id', 'card_main_name')
  119. ->get()
  120. ->toArray();
  121. return json_success('success', $cardMain);
  122. }
  123. /**
  124. * @Desc 储值卡详情
  125. * @Author Gorden
  126. * @Date 2024/11/15 11:33
  127. *
  128. * @param Request $request
  129. * @return Response
  130. */
  131. public function info(Request $request): Response
  132. {
  133. $cardMainId = $request->get('card_main_id');
  134. if (!$cardMainId) {
  135. return json_fail('参数异常');
  136. }
  137. $main = CardMain::with('category')->where('card_main_id', $cardMainId)->first();
  138. if ($main->card_main_valid_mode == 'DAYS') {
  139. $main->valid_term = $main->card_main_valid_days ? $main->card_main_valid_days . '天' : 0;
  140. } elseif ($main->card_main_valid_mode == 'LONG') {
  141. $main->valid_term = '长期有效';
  142. } elseif ($main->card_main_valid_mode == 'DATE') {
  143. $main->valid_term = date('Y/m/d', strtotime($main->card_main_valid_begin)) . '-' . date('Y/m/d', strtotime($main->card_main_valid_end));
  144. }
  145. // 发行记录
  146. $cardIssue = CardIssue::where('join_issue_card_main_id', $cardMainId)->orderBy('card_issue_addtimes', 'DESC')->get()->toArray();
  147. $cardMainJson = json_decode($main->card_main_json, true);
  148. // 适用门店
  149. $premises = [];
  150. if (!empty($cardMainJson['premises_ary'])){
  151. $premises = SysDept::whereIn('dept_id',$cardMainJson['premises_ary'])->pluck('dept_name');
  152. }
  153. $category = [];
  154. if (!empty($cardMainJson['goods_category_ary'])){
  155. $category = CategoryService::getCategoryAndSupper($cardMainJson['goods_category_ary']);
  156. }
  157. // 适用产品
  158. $goods = [];
  159. if (!empty($cardMainJson['goods_ary'])){
  160. $goods = Goods::whereIn('goods_id',$cardMainJson['goods_ary'])
  161. ->select('goods_id','goods_name','goods_cover','goods_sales_price','goods_addtimes')
  162. ->orderByDesc('goods_sort')->orderByDesc('goods_addtimes')->get()->toArray();
  163. foreach ($goods as &$goodsItem){
  164. $goodsItem['goods_cover'] = getenv("STORAGE_DOMAIN").$goodsItem['goods_cover'];
  165. }
  166. }
  167. // 发行统计
  168. $cardTotal = Card::where('join_card_main_id', $cardMainId)->count();
  169. $isIssueTotal = Card::where('join_card_main_id', $cardMainId)->where('is_issue', 'Y')->count();
  170. $cardInitTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'INIT')->count();
  171. $cardWaitingTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'WAITING')->count();
  172. $cardPendingTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'PENDING')->count();
  173. $cardUsedTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'USED')->count();
  174. $cardDoneTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'DONE')->count();
  175. $cardExpiredTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'EXPIRED')->count();
  176. $cardPausedTotal = Card::where('join_card_main_id', $cardMainId)->where('card_status', 'PAUSED')->count();
  177. $statistics = [
  178. [
  179. 'total' => $cardTotal,
  180. 'isIssueTotal' => $isIssueTotal,
  181. 'initTotal' => $cardInitTotal,
  182. 'waitingTotal' => $cardWaitingTotal,
  183. 'pendingTotal' => $cardPendingTotal,
  184. 'usedTotal' => $cardUsedTotal,
  185. 'doneTotal' => $cardDoneTotal,
  186. 'expiredTotal' => $cardExpiredTotal,
  187. 'pausedTotal' => $cardPausedTotal
  188. ]
  189. ];
  190. $data = [
  191. 'main' => $main,
  192. 'issue' => $cardIssue,
  193. 'premises'=>$premises,
  194. 'category'=>$category,
  195. 'goods'=>$goods,
  196. 'statistics' => $statistics
  197. ];
  198. return json_success('', $data);
  199. }
  200. /**
  201. * @Desc 插入前置方法
  202. * @Author Gorden
  203. * @Date 2024/11/14 14:29
  204. *
  205. * @param Request $request
  206. * @return array
  207. * @throws BusinessException
  208. */
  209. public function insertInput(Request $request): array
  210. {
  211. $params = $request->post();
  212. $data = $this->inputFilter($request->post());
  213. if ($data['card_main_valid_mode'] == 'DATE') {
  214. $data['card_main_valid_begin'] = date('Y-m-d 00:00:00', strtotime($data['card_main_valid_begin']));
  215. $data['card_main_valid_end'] = date('Y-m-d 23:59:59', strtotime($data['card_main_valid_end']));
  216. $data['card_main_valid_days'] = 0;
  217. } elseif ($data['card_main_valid_mode'] == 'LONG' || $data['card_main_valid_mode'] == 'DAYS') {
  218. $data['card_main_valid_begin'] = '';
  219. $data['card_main_valid_end'] = '';
  220. }
  221. $cardMainJson = [
  222. 'desc' => $params['card_main_desc'] ?? [],
  223. 'is_recharge' => $params['is_recharge'] ?? 'N',
  224. 'issue' => $params['issue'] ?? 'BATCH',
  225. 'demand_config' => []
  226. ];
  227. if ($params['issue'] == 'DEMAND') {
  228. $cardMainJson['demand_config'] = [
  229. 'length' => $params['card_length'],
  230. 'begin' => $params['card_begin'],
  231. 'end' => $params['card_end'],
  232. 'prefix' => $params['card_prefix'],
  233. 'suffix' => $params['card_suffix'],
  234. 'rand' => $params['card_rand'],
  235. 'rand_varchar' => is_numeric($params['card_rand']) ? 'NUMBER' : 'STRING',
  236. ];
  237. }
  238. // 关联产品
  239. $cardMainJson['goods_ary'] = $params['goods_id'] ?? [];
  240. // 关联产品分类
  241. $cardMainJson['goods_category_ary'] = $params['category_id'] ?? [];
  242. // 关联门店
  243. $cardMainJson['premises_ary'] = $params['premises'] ?? [];
  244. $data['card_main_json'] = json_encode($cardMainJson);
  245. return $data;
  246. }
  247. /**
  248. * 更新前置方法
  249. * @param Request $request
  250. * @return array
  251. * @throws BusinessException
  252. */
  253. protected function updateInput(Request $request): array
  254. {
  255. $params = $request->post();
  256. $primary_key = $this->model->getKeyName();
  257. $id = $request->post($primary_key);
  258. $data = $this->inputFilter($request->post());
  259. $model = $this->model->find($id);
  260. if (!$model) {
  261. throw new BusinessException('记录不存在', 2);
  262. }
  263. if ($data['card_main_valid_mode'] == 'DATE') {
  264. $data['card_main_valid_begin'] = date('Y-m-d 00:00:00', strtotime($data['card_main_valid_begin']));
  265. $data['card_main_valid_end'] = date('Y-m-d 23:59:59', strtotime($data['card_main_valid_end']));
  266. $data['card_main_valid_days'] = 0;
  267. } elseif ($data['card_main_valid_mode'] == 'LONG' || $data['card_main_valid_mode'] == 'DAYS') {
  268. $data['card_main_valid_begin'] = '';
  269. $data['card_main_valid_end'] = '';
  270. }
  271. $cardMainJson = [];
  272. if (!empty($model->card_main_json)) {
  273. $cardMainJson = json_decode($model->card_main_json, true);
  274. }
  275. $cardMainJson['desc'] = $params['card_main_desc'] ?? [];
  276. if (!empty($params['is_recharge'])) {
  277. $cardMainJson['is_recharge'] = $params['is_recharge'];
  278. }
  279. if (!empty($params['issue'])) {
  280. $cardMainJson['issue'] = $params['issue'];
  281. }
  282. if ($cardMainJson['issue'] == 'BATCH') {
  283. $cardMainJson['demand_config'] = [];
  284. } elseif ($cardMainJson['issue'] == 'DEMAND') {
  285. $cardMainJson['demand_config'] = [
  286. 'length' => $params['card_length'],
  287. 'begin' => $params['card_begin'],
  288. 'end' => $params['card_end'],
  289. 'prefix' => $params['card_prefix'],
  290. 'suffix' => $params['card_suffix'],
  291. 'rand' => $params['card_rand'],
  292. 'rand_varchar' => is_numeric($params['card_rand']) ? 'NUMBER' : 'STRING',
  293. ];
  294. }
  295. // 关联产品
  296. $cardMainJson['goods_ary'] = $params['goods_id'] ?? [];
  297. // 关联产品分类
  298. $cardMainJson['goods_category_ary'] = $params['category_id'] ?? [];
  299. // 关联门店
  300. $cardMainJson['premises_ary'] = $params['premises'] ?? [];
  301. $data['card_main_json'] = json_encode($cardMainJson);
  302. // 卡状态设置为禁用,则未绑定的卡冻结,恢复未发行状态
  303. if ($data['card_main_status'] == 'DISABLED' && $model->card_main_status != 'DISABLED') {
  304. Card::where('join_card_main_id', $id)->where('join_card_member_id', '')->update(['card_status' => 'PAUSED', 'is_issue' => 'N']);
  305. // 记录日志
  306. _syslog("储值卡", "禁用");
  307. } elseif ($data['card_main_status'] == 'ACTIVED' && $model->card_main_status == 'DISABLED') {
  308. Card::where('join_card_main_id', $id)->where('join_card_member_id', '')
  309. ->where('card_status', 'PAUSED')
  310. ->update(['card_status' => 'INIT']);
  311. // 记录日志
  312. _syslog("储值卡", "启用");
  313. }
  314. unset($data[$primary_key]);
  315. return [$id, $data];
  316. }
  317. /**
  318. * @Desc 删除储值卡
  319. * @Author Gorden
  320. * @Date 2024/11/18 16:33
  321. *
  322. * @param Request $request
  323. * @return Response
  324. * @throws BusinessException
  325. */
  326. public function delete(Request $request): Response
  327. {
  328. $ids = $this->deleteInput($request);
  329. Db::beginTransaction();
  330. try {
  331. if (Card::whereIn('join_card_main_id', $ids)->where(function ($query) {
  332. $query->where('card_status', '<>', 'INIT')
  333. ->orWhere('join_card_dept_id', '<>', '')
  334. ->orWhere('join_card_member_id', '<>', '');
  335. })->exists()) {
  336. return json_fail("存在已发行、已分配的卡,无法删除!");
  337. }
  338. $this->doDelete($ids);
  339. // 同时删除批次记录
  340. CardIssue::whereIn('join_issue_card_main_id', $ids)->delete();
  341. // 同时删除卡记录
  342. Card::whereIn('join_card_main_id', $ids)->delete();
  343. Db::commit();
  344. _syslog("储值卡", '删除成功');
  345. return json_success('success');
  346. } catch (\Exception $e) {
  347. Db::rollBack();
  348. _syslog("储值次", '删除失败');
  349. Log::error("储值卡删除失败", ['msg' => $e->getMessage()]);
  350. return json_fail("删除失败");
  351. }
  352. }
  353. /**
  354. * @Desc 储值卡统计
  355. * @Author Gorden
  356. * @Date 2024/11/22 13:06
  357. *
  358. * @param Request $request
  359. * @return Response
  360. */
  361. public function statistics(Request $request)
  362. {
  363. $classify = $request->get('card_main_classify');
  364. $categoryId = $request->get('join_card_main_category_id');
  365. $name = $request->get('card_main_name');
  366. $addtimes = $request->get('card_main_addtimes');
  367. $amount = $request->get('card_main_amount');
  368. $cardMain = CardMain::when(!empty($classify), function ($query) use ($classify) {
  369. $query->where('card_main_classify', $classify);
  370. })->when(!empty($categoryId), function ($query) use ($categoryId) {
  371. $query->where('join_card_main_category_id', $categoryId);
  372. })->when(!empty($name), function ($query) use ($name) {
  373. $query->where('card_main_name', 'like', '%' . $name . '%');
  374. })->when(!empty($amount), function ($query) use ($amount) {
  375. $query->where('card_main_amount', $amount);
  376. })->when(!empty($addtimes), function ($query) use ($addtimes) {
  377. $addtimes[0] = strtotime($addtimes[0]);
  378. $addtimes[1] = strtotime($addtimes[1]);
  379. $query->whereBetween('card_main_addtimes', $addtimes);
  380. });
  381. $totalModel = clone $cardMain;
  382. $totalList = $totalModel->select('card_main_id', 'card_main_amount')->get()->toArray();
  383. $statistics = [
  384. 'total' => ['total' => 0, 'amount' => 0],
  385. 'is_issue' => ['total' => 0, 'amount' => 0],
  386. 'init' => ['total' => 0, 'amount' => 0],
  387. 'waiting' => ['total' => 0, 'amount' => 0],
  388. 'pending' => ['total' => 0, 'amount' => 0],
  389. 'used' => ['total' => 0, 'amount' => 0],
  390. 'done' => ['total' => 0, 'amount' => 0],
  391. 'expired' => ['total' => 0, 'amount' => 0],
  392. 'paused' => ['total' => 0, 'amount' => 0]
  393. ];
  394. foreach ($totalList as $total) {
  395. // 发行统计
  396. $isIssueTotal = Card::where('is_issue', 'Y')->where('join_card_main_id', $total['card_main_id'])->count();
  397. $statistics['is_issue']['total'] += $isIssueTotal;
  398. $statistics['is_issue']['amount'] = sprintf('%.2f', $isIssueTotal * $total['card_main_amount'] + $statistics['is_issue']['amount']);
  399. // 待分配统计
  400. $initTotal = Card::where('card_status', 'INIT')->where('join_card_main_id', $total['card_main_id'])->count();
  401. $statistics['init']['total'] += $initTotal;
  402. $statistics['init']['amount'] = sprintf('%.2f', $initTotal * $total['card_main_amount'] + $statistics['init']['amount']);
  403. // 已分配,待售统计
  404. $waitingTotal = Card::where('card_status', 'WAITING')->where('join_card_main_id', $total['card_main_id'])->count();
  405. $statistics['waiting']['total'] += $waitingTotal;
  406. $statistics['waiting']['amount'] = sprintf('%.2f', $waitingTotal * $total['card_main_amount'] + $statistics['waiting']['amount']);
  407. // 已售,待激活统计
  408. $pendingTotal = Card::where('card_status', 'PENDING')->where('join_card_main_id', $total['card_main_id'])->count();
  409. $statistics['pending']['total'] += $pendingTotal;
  410. $statistics['pending']['amount'] = sprintf('%.2f', $pendingTotal * $total['card_main_amount'] + $statistics['pending']['amount']);
  411. // 已激活统计
  412. $usedTotal = Card::where('card_status', 'USED')->where('join_card_main_id', $total['card_main_id'])->count();
  413. $statistics['used']['total'] += $usedTotal;
  414. $statistics['used']['amount'] = sprintf('%.2f', $usedTotal * $total['card_main_amount'] + $statistics['used']['amount']);
  415. // 使用完成统计
  416. $doneTotal = Card::where('card_status', 'DONE')->where('join_card_main_id', $total['card_main_id'])->count();
  417. $statistics['done']['total'] += $doneTotal;
  418. $statistics['done']['amount'] = sprintf('%.2f', $doneTotal * $total['card_main_amount'] + $statistics['done']['amount']);
  419. // 过期统计
  420. $doneTotal = Card::where('card_status', 'EXPIRED')->where('join_card_main_id', $total['card_main_id'])->count();
  421. $statistics['expired']['total'] += $doneTotal;
  422. $statistics['expired']['amount'] = sprintf('%.2f', $doneTotal * $total['card_main_amount'] + $statistics['expired']['amount']);
  423. // 冻结统计
  424. $pausedTotal = Card::where('card_status', 'PAUSED')->where('join_card_main_id', $total['card_main_id'])->count();
  425. $statistics['paused']['total'] += $pausedTotal;
  426. $statistics['paused']['amount'] = sprintf('%.2f', $pausedTotal * $total['card_main_amount'] + $statistics['paused']['total']);
  427. }
  428. $statistics['total']['total'] = $statistics['init']['total'] + $statistics['waiting']['total']
  429. + $statistics['pending']['total'] + $statistics['used']['total'] + $statistics['done']['total']
  430. + $statistics['expired']['total'] + $statistics['paused']['total'];
  431. $statistics['total']['amount'] = sprintf('%.2f', $statistics['init']['amount']
  432. + $statistics['waiting']['amount'] + $statistics['pending']['amount'] + $statistics['used']['amount']
  433. + $statistics['expired']['amount'] + $statistics['done']['amount'] + $statistics['paused']['amount']);
  434. return json_success('success', $statistics);
  435. }
  436. }