CardIssueController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. namespace app\admin\controller\coupon;
  3. use app\controller\Curd;
  4. use app\model\Card;
  5. use app\model\CardIssue;
  6. use app\model\CardMain;
  7. use app\model\SysCategory;
  8. use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
  9. use Illuminate\Database\Query\Builder as QueryBuilder;
  10. use support\Db;
  11. use support\exception\BusinessException;
  12. use support\Log;
  13. use support\Model;
  14. use support\Request;
  15. use support\Response;
  16. use Tinywan\Jwt\JwtToken;
  17. class CardIssueController extends Curd
  18. {
  19. public function __construct()
  20. {
  21. $this->model = new CardIssue();
  22. }
  23. public function select(Request $request): Response
  24. {
  25. $cardMainName = $request->get('card_main_name');
  26. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  27. $order = $request->get('order', 'desc');
  28. $field = $field ?? 'card_issue_addtimes';
  29. if (!empty($where['card_issue_name'])) {
  30. $where['card_issue_name'] = ['like', $where['card_issue_name']];
  31. }
  32. if (!empty($where['card_issue_addtimes'])) {
  33. $where['card_issue_addtimes'][0] = strtotime($where['card_issue_addtimes'][0]);
  34. $where['card_issue_addtimes'][1] = strtotime($where['card_issue_addtimes'][1]);
  35. }
  36. if (!empty($cardMainName)) {
  37. $cardMainIds = CardMain::where('card_main_name', 'like', '%' . $cardMainName . '%')->pluck('card_main_id')->toArray();
  38. $where['join_issue_card_main_id'] = ['in', $cardMainIds];
  39. }
  40. $query = $this->doSelect($where, $field, $order);
  41. return $this->doFormat($query, $format, $limit);
  42. }
  43. /**
  44. * 指定查询where条件,并没有真正的查询数据库操作
  45. * @param array $where
  46. * @param string|null $field
  47. * @param string $order
  48. * @return EloquentBuilder|QueryBuilder|Model
  49. */
  50. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  51. {
  52. $model = $this->model->with([
  53. 'main',
  54. 'user'
  55. ]);
  56. foreach ($where as $column => $value) {
  57. if (is_array($value)) {
  58. if ($value[0] === 'like' || $value[0] === 'not like') {
  59. $model = $model->where($column, $value[0], "%$value[1]%");
  60. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  61. $model = $model->where($column, $value[0], $value[1]);
  62. } elseif ($value[0] == 'in') {
  63. $valArr = $value[1];
  64. if (is_string($value[1])) {
  65. $valArr = explode(",", trim($value[1]));
  66. }
  67. $model = $model->whereIn($column, $valArr);
  68. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  69. $valArr = $value[1];
  70. if (is_string($value[1])) {
  71. $valArr = explode(",", trim($value[1]));
  72. }
  73. $model = $model->whereNotIn($column, $valArr);
  74. } elseif ($value[0] == 'null') {
  75. $model = $model->whereNull($column);
  76. } elseif ($value[0] == 'not null') {
  77. $model = $model->whereNotNull($column);
  78. } elseif ($value[0] !== '' || $value[1] !== '') {
  79. $model = $model->whereBetween($column, $value);
  80. }
  81. } else {
  82. $model = $model->where($column, $value);
  83. }
  84. }
  85. if ($field) {
  86. $model = $model->orderBy($field, $order);
  87. }
  88. return $model;
  89. }
  90. /**
  91. * @Desc 查询后处理
  92. * @Author Gorden
  93. * @Date 2024/11/15 8:35
  94. *
  95. * @param $items
  96. * @return mixed
  97. */
  98. public function afterQuery($items)
  99. {
  100. foreach ($items as &$item) {
  101. if (!empty($item['main']['join_card_main_category_id'])) {
  102. $item['main']['category_name'] = SysCategory::where('category_id', $item['main']['join_card_main_category_id'])->value('category_name');
  103. }
  104. if (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'DAYS') {
  105. $item['main']['valid_term'] = $item['main']['card_main_valid_days'] ? $item['main']['card_main_valid_days'] . '天' : 0;
  106. } elseif (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'LONG') {
  107. $item['main']['valid_term'] = '长期有效';
  108. } elseif (!empty($item['main']['card_main_valid_mode']) && $item['main']['card_main_valid_mode'] == 'DATE') {
  109. $item['main']['valid_term'] = date('Y/m/d H:i:s', strtotime($item['main']['card_main_valid_begin'])) . '-' . date('Y/m/d H:i:s', strtotime($item['main']['card_main_valid_end']));
  110. }
  111. if (empty($item['main'])) {
  112. continue;
  113. }
  114. // $item['main']['cardMainJson'] = json_decode($item['main']['card_main_json'], true);
  115. // 总发行金额
  116. $item['issue_total_amount'] = sprintf('%.2f', $item['card_issue_num'] * $item['main']['card_main_amount']);
  117. $cardModel = Card::where('join_card_issue_id', $item['card_issue_id']);
  118. // 未激活
  119. $inactiveTotalModel = clone $cardModel;
  120. $item['inactive_total'] = $inactiveTotalModel->whereIn('card_status', ['INIT', 'WAITING', 'PENDING'])->count();
  121. $item['inactive_amount'] = sprintf('%.2f', $item['inactive_total'] * $item['main']['card_main_amount']);
  122. // 已激活
  123. $activeTotalModel = clone $cardModel;
  124. $item['active_total'] = $activeTotalModel->whereIn('card_status', ['USED', 'DONE'])->count();
  125. $item['active_amount'] = sprintf('%.2f', $item['active_total'] * $item['main']['card_main_amount']);
  126. // 无效
  127. $invalidTotalModel = clone $cardModel;
  128. $item['invalid_total'] = $invalidTotalModel->whereIn('card_status', ['EXPIRED', 'PAUSED', 'DISABLED'])->count();
  129. $item['invalid_amount'] = sprintf('%.2f', $item['invalid_total'] * $item['main']['card_main_amount']);
  130. }
  131. return $items;
  132. }
  133. /**
  134. * @Desc 创建发行
  135. * @Author Gorden
  136. * @Date 2024/11/18 10:09
  137. *
  138. * @param Request $request
  139. * @return Response
  140. */
  141. public function insert(Request $request): Response
  142. {
  143. $params = $request->post();
  144. Db::beginTransaction();
  145. try {
  146. if (empty($params['card_issue_serial_fill'])) {
  147. $params['card_issue_serial_fill'] = '0';
  148. }
  149. // 验证是否有相同的前缀,长度相同,且开始结束数字有交叉的
  150. $cardIssueExists = CardIssue::where('card_issue_serial_length', $params['card_issue_serial_length'])
  151. ->where('card_issue_serial_prefix', $params['card_issue_serial_prefix'])
  152. ->where(function ($query) use ($params) {
  153. $query->whereBetween('card_issue_serial_begin', [$params['card_issue_serial_begin'], $params['card_issue_serial_end']])
  154. ->orWhereBetween('card_issue_serial_end', [$params['card_issue_serial_begin'], $params['card_issue_serial_end']]);
  155. })->exists();
  156. if ($cardIssueExists) {
  157. throw new BusinessException("当前设置的发行规则在前缀、长度、开始数字、结束数字与已存在的规则存在冲突,请重新设置");
  158. }
  159. $cardIds = [];
  160. // 创建卡号
  161. for ($i = 0; $i < intval($params['card_issue_num']); $i++) {
  162. $prefixLength = strlen($params['card_issue_serial_prefix']);
  163. $suffixLength = strlen($params['card_issue_serial_suffix']);
  164. $cardIds[] = $params['card_issue_serial_prefix'] . str_pad($params['card_issue_serial_begin'] + $i, $params['card_issue_serial_length'] - $prefixLength - $suffixLength, $params['card_issue_serial_fill'], STR_PAD_LEFT) . $params['card_issue_serial_suffix'];
  165. }
  166. // 写入发行表
  167. $issueId = CardIssue::insertGetId([
  168. 'join_issue_card_main_id' => $params['join_issue_card_main_id'],
  169. 'card_issue_name' => $params['card_issue_name'],
  170. 'card_issue_num' => $params['card_issue_num'],
  171. 'card_issue_datetime' => date('Y-m-d H:i:s'),
  172. 'card_issue_serial_length' => $params['card_issue_serial_length'],
  173. 'card_issue_serial_prefix' => $params['card_issue_serial_prefix'],
  174. 'card_issue_serial_suffix' => $params['card_issue_serial_suffix'],
  175. 'card_issue_serial_begin' => $params['card_issue_serial_begin'],
  176. 'card_issue_serial_end' => $params['card_issue_serial_end'],
  177. 'card_issue_serial_fill' => $params['card_issue_serial_fill'],
  178. 'card_issue_begin_nbr' => $cardIds[0],
  179. 'card_issue_end_nbr' => $cardIds[count($cardIds) - 1],
  180. 'card_issue_creator_user_id' => JwtToken::getCurrentId(),
  181. 'card_issue_addtimes' => time()
  182. ]);
  183. // 分批入库
  184. $cardsCollect = collect($cardIds);
  185. $chunks = $cardsCollect->chunk(200);
  186. foreach ($chunks as $chunk) {
  187. $insertData = [];
  188. foreach ($chunk as $key => $item) {
  189. $insertData[$key] = [
  190. 'card_id' => $item,
  191. 'join_card_main_id' => $params['join_issue_card_main_id'],
  192. 'join_card_issue_id' => $issueId,
  193. 'card_status' => 'INIT',
  194. 'card_cdkey' => random_string(8, 'number'),
  195. 'card_addtimes' => time()
  196. ];
  197. }
  198. Card::insert($insertData);
  199. }
  200. Db::commit();
  201. _syslog("储值卡批次", '创建成功', false, $request->all());
  202. return json_success('success');
  203. } catch (BusinessException $e) {
  204. Db::rollBack();
  205. _syslog("储值卡批次", '创建失败', false, $request->all());
  206. Log::error("储值卡批次创建失败", ['msg' => $e->getMessage()]);
  207. return json_fail($e->getMessage());
  208. } catch (\Exception $e) {
  209. Db::rollBack();
  210. _syslog("储值卡批次", '创建失败', false, $request->all());
  211. Log::error("储值卡发行失败", ['msg' => $e->getMessage()]);
  212. return json_fail("储值卡批次创建失败");
  213. }
  214. }
  215. /**
  216. * @Desc 删除批次
  217. * @Author Gorden
  218. * @Date 2024/11/18 11:05
  219. *
  220. * @param Request $request
  221. * @return Response
  222. * @throws BusinessException
  223. */
  224. public function delete(Request $request): Response
  225. {
  226. $ids = $this->deleteInput($request);
  227. Db::beginTransaction();
  228. try {
  229. if (Card::whereIn('join_card_issue_id', $ids)->where(function ($query) {
  230. $query->where('card_status', '<>', 'INIT')
  231. ->orWhere('join_card_dept_id', '<>', '')
  232. ->orWhere('join_card_member_id', '<>', '');
  233. })->exists()) {
  234. return json_fail("存在已发行、已分配的卡,无法删除!");
  235. }
  236. $this->doDelete($ids);
  237. // 同时删除卡记录
  238. Card::whereIn('join_card_issue_id', $ids)->delete();
  239. Db::commit();
  240. _syslog("储值卡批次", '删除成功');
  241. return json_success('success');
  242. } catch (\Exception $e) {
  243. Db::rollBack();
  244. _syslog("储值卡批次", '删除失败');
  245. Log::error("储值卡批次删除失败", ['msg' => $e->getMessage()]);
  246. return json_fail("删除失败");
  247. }
  248. }
  249. /**
  250. * @Desc 获取没发行完的批次列表
  251. * @Author Gorden
  252. * @Date 2024/11/18 14:44
  253. *
  254. * @param Request $request
  255. * @return Response
  256. */
  257. public function getIssueList(Request $request)
  258. {
  259. $cardMainId = $request->get('card_main_id');
  260. if (!$cardMainId) {
  261. return json_fail('参数异常');
  262. }
  263. $isIssue = $request->get('is_issue');
  264. $allocation = $request->get('allocation');
  265. $cardIssues = CardIssue::where('join_issue_card_main_id', $cardMainId)
  266. ->select('card_issue_id', 'card_issue_name')
  267. ->get()
  268. ->toArray();
  269. if (empty($isIssue) && empty($allocation)) {
  270. return json_success('success', $cardIssues);
  271. }
  272. $cardIssueIds = array_column($cardIssues, 'card_issue_id');
  273. $inCardsIssueIds = Card::whereIn('join_card_issue_id', $cardIssueIds)
  274. ->when(!empty($isIssue), function ($query) use ($isIssue) {
  275. $query->where('is_issue', $isIssue);
  276. })->when(!empty($allocation), function ($query) use ($allocation) {
  277. if ($allocation == 'N') {
  278. $query->where('join_card_dept_id', '');
  279. } elseif ($allocation == 'Y') {
  280. $query->where('join_card_dept_id', '<>', '');
  281. }
  282. })
  283. ->groupBy('join_card_issue_id')
  284. ->pluck('join_card_issue_id')
  285. ->toArray();
  286. $data = [];
  287. foreach ($cardIssues as $cardIssue) {
  288. foreach ($inCardsIssueIds as $issueId) {
  289. if ($cardIssue['card_issue_id'] == $issueId) {
  290. $data[] = [
  291. 'card_issue_id' => $cardIssue['card_issue_id'],
  292. 'card_issue_name' => $cardIssue['card_issue_name']
  293. ];
  294. }
  295. }
  296. }
  297. return json_success('success', $data);
  298. }
  299. }