CardIssueController.php 14 KB

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