ExpenseClaimsService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. namespace App\Service;
  3. use App\Model\Employee;
  4. use App\Model\ExpenseClaims;
  5. use App\Model\ExpenseClaimsDetails;
  6. use App\Model\Fee;
  7. use App\Model\Item;
  8. use Carbon\Carbon;
  9. use Illuminate\Support\Facades\DB;
  10. class ExpenseClaimsService extends Service
  11. {
  12. public function expenseClaimsList($data, $user)
  13. {
  14. $model = $this->expenseClaimsSetCommon($data, $user);
  15. $list = $this->limit($model, '', $data);
  16. $list = $this->fillData($list, $user);
  17. return [true, $list];
  18. }
  19. public function expenseClaimsSetCommon($data, $user, $field = [])
  20. {
  21. if (empty($field)) $field = ExpenseClaims::$field;
  22. $model = ExpenseClaims::Clear($user, $data);
  23. $model = $model->where('del_time', 0)
  24. ->select($field)
  25. ->orderby('id', 'desc');
  26. if (!empty($data['month'])) $model->where('month', $data['month']);
  27. if (!empty($data['code'])) $model->where('code', 'LIKE', '%' . $data['code'] . '%');
  28. if (!empty($data['time'][0]) && !empty($data['time'][1])) {
  29. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  30. $model->where('month', '>=', $return[0]);
  31. $model->where('month', '<=', $return[1]);
  32. }
  33. return $model;
  34. }
  35. public function fillData($data, $user)
  36. {
  37. if (empty($data['data'])) return $data;
  38. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'], 'crt_id')));
  39. $map = ArchiveService::fillIsArchive(array_unique(array_column($data['data'],'month')), $user);
  40. foreach ($data['data'] as $key => $value) {
  41. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s', $value['crt_time']) : '';
  42. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  43. $data['data'][$key]['month'] = $value['month'] ? date('Y-m', $value['month']) : '';
  44. $data['data'][$key]['is_archive'] = $map[$value['month']] ?? false;
  45. }
  46. return $data;
  47. }
  48. public function expenseClaimsAdd($data, $user)
  49. {
  50. list($status, $msg) = $this->expenseClaimsRule($data, $user);
  51. if (!$status) return [$status, $msg];
  52. try {
  53. DB::beginTransaction();
  54. $model = new ExpenseClaims();
  55. $model->code = $this->generateBillNo([
  56. 'top_depart_id' => $user['top_depart_id'],
  57. 'type' => ExpenseClaims::Order_type,
  58. 'period' => date("Ym", $data['month'])
  59. ]);
  60. $model->month = $data['month'];
  61. $model->crt_id = $user['id'];
  62. $model->top_depart_id = $data['top_depart_id'];
  63. $model->save();
  64. list($old, $new) = $this->saveDetail($model->id, time(), $data, $user);
  65. DB::commit();
  66. } catch (\Exception $exception) {
  67. DB::rollBack();
  68. return [false, $exception->getLine() . "_" . $exception->getMessage()];
  69. }
  70. return [true, ['file' => ['old' => $old, 'new' => $new]]];
  71. }
  72. private function saveDetail($id, $time, $data, $user, $old = [])
  73. {
  74. $new = [];
  75. $unit = [];
  76. $oldFilesMap = array_flip($old);
  77. if (!empty($data['details']) && is_array($data['details'])) {
  78. foreach ($data['details'] as $value) {
  79. $unit[] = [
  80. 'expense_claims_id' => $id,
  81. 'item_id' => $value['item_id'] ?? 0,
  82. 'employee_id' => $value['employee_id'] ?? "",
  83. 'fee_id' => $value['fee_id'] ?? 0,
  84. 'amount' => $value['amount'] ?? 0,
  85. 'entrust1_amount' => $value['entrust1_amount'] ?? 0,
  86. 'entrust2_amount' => $value['entrust2_amount'] ?? 0,
  87. 'remark' => $value['remark'] ?? "",
  88. 'claim_date' => strtotime($value['claim_date']),
  89. 'entrust_type' => $value['entrust_type'] ?? 0,
  90. 'expense_type' => $value['expense_type'] ?? 0,
  91. 'voucher_no' => $value['voucher_no'] ?? "",
  92. 'file_url' => $value['file_url'] ?? "",
  93. 'file_name' => $value['file_name'] ?? "",
  94. 'top_depart_id' => $data['top_depart_id'] ?? 0,
  95. 'crt_time' => $time,
  96. 'crt_id' => $user['id'],
  97. 'r_id' => $value['r_id'] ?? 0,
  98. ];
  99. $currentUrl = $value['file_url'] ?? "";
  100. if (!empty($currentUrl)) {
  101. if (isset($oldFilesMap[$currentUrl])) {
  102. unset($oldFilesMap[$currentUrl]);
  103. } else {
  104. $new[] = $currentUrl;
  105. }
  106. }
  107. }
  108. if (!empty($unit)) ExpenseClaimsDetails::insert($unit);
  109. }
  110. return [array_keys($oldFilesMap), $new];
  111. }
  112. private function expenseClaimsRule(&$data, $user, $is_add = true)
  113. {
  114. $data['top_depart_id'] = $user['top_depart_id'];
  115. if (empty($data['month'])) return [false, '月份不能为空'];
  116. $data['month'] = $this->changeDateToDate($data['month']);
  117. //归档
  118. list($status, $msg) = ArchiveService::isArchive($data['month'], $user);
  119. if (!$status) return [false, $msg];
  120. $monthStart = $data['month'];
  121. // 获取该月最后一秒:下个月 1 号减去 1 秒
  122. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  123. if (empty($data['details'])) return [false, '费用项目单详情不能为空'];
  124. foreach ($data['details'] as $index => $item) {
  125. if (empty($item['item_id'])) return [false, "第" . ($index + 1) . "行项目不能为空"];
  126. if (empty($item['fee_id'])) return [false, "第" . ($index + 1) . "行费用类型不能为空"];
  127. if (!isset($item['amount'])) return [false, "第" . ($index + 1) . "行费用金额不存在"];
  128. $res = $this->checkNumber($item['amount'], 2, 'non-negative');
  129. if (!$res['valid']) return [false, "第" . ($index + 1) . "行费用金额" . $res['error']];
  130. if (!isset($item['claim_date'])) return [false, "第" . ($index + 1) . "行项费用产生日期缺失"];
  131. // 将报销日期转换为时间戳
  132. $claimTime = strtotime($item['claim_date']);
  133. // 判断:claim_date 必须早于 month
  134. // 如果 claim_date 是 2026-02-28,而 month 是 2026-03-01,则校验通过
  135. if ($claimTime < $monthStart || $claimTime > $monthEnd) return [false, "第" . ($index + 1) . "行项费用产生日期必须在当前月份内(" . date("Y-m", $data['month']) . ")"];
  136. if(! isset(ExpenseClaimsDetails::State_Type[$item['entrust_type']])) return [false, "第" . ($index + 1) . "委托类型不存在"];
  137. $title = ExpenseClaimsDetails::State_Type[$item['entrust_type']];
  138. if(! isset($item['entrust1_amount'])) return [false, "第" . ($index + 1) . "行境内委托金额不存在"];
  139. $res = $this->checkNumber($item['entrust1_amount'], 2, 'non-negative');
  140. if (!$res['valid']) return [false, "第" . ($index + 1) . "行境内委托金额". $res['error']];
  141. if(! isset($item['entrust2_amount'])) return [false, "第" . ($index + 1) . "行境外委托金额不存在"];
  142. $res = $this->checkNumber($item['entrust2_amount'], 2, 'non-negative');
  143. if (!$res['valid']) return [false, "第" . ($index + 1) . "行境外委托金额". $res['error']];
  144. $tmp = bcadd($item['entrust1_amount'], $item['entrust2_amount'],2);
  145. if(floatval($tmp) > $item['amount']) return [false, "第" . ($index + 1) . "行委托金额总和不能超过费用金额"];
  146. }
  147. $query = ExpenseClaims::where('top_depart_id', $data['top_depart_id'])
  148. ->where('month', $monthStart)
  149. ->where('del_time', 0);
  150. if (!$is_add) {
  151. if (empty($data['id'])) return [false, 'ID不能为空'];
  152. $query->where('id', '<>', $data['id']);
  153. }
  154. if ($query->exists()) return [false, date("Y-m", $monthStart) . '已存在费用项目单'];
  155. return [true, ""];
  156. }
  157. public function expenseClaimsEdit($data, $user)
  158. {
  159. list($status, $msg) = $this->expenseClaimsRule($data, $user, false);
  160. if (!$status) return [$status, $msg];
  161. try {
  162. DB::beginTransaction();
  163. $model = ExpenseClaims::where('id', $data['id'])->first();
  164. // $model->month = $data['month'];
  165. // $model->crt_id = $user['id'];
  166. // $model->save();
  167. $time = time();
  168. $old = ExpenseClaimsDetails::where('del_time', 0)
  169. ->where('expense_claims_id', $model->id)
  170. ->where('file_url', '<>', '')
  171. ->pluck('file_url')
  172. ->all();
  173. ExpenseClaimsDetails::where('del_time', 0)
  174. ->where('expense_claims_id', $model->id)
  175. ->update(['del_time' => $time]);
  176. list($old, $new) = $this->saveDetail($model->id, $time, $data, $user, $old);
  177. DB::commit();
  178. } catch (\Exception $exception) {
  179. DB::rollBack();
  180. return [false, $exception->getMessage()];
  181. }
  182. return [true, ['file' => ['old' => $old, 'new' => $new]]];
  183. }
  184. public function expenseClaimsDel($data, $user)
  185. {
  186. if ($this->isEmpty($data, 'id')) return [false, '请选择数据!'];
  187. try {
  188. DB::beginTransaction();
  189. $time = time();
  190. $month = ExpenseClaims::where('del_time', 0)
  191. ->whereIn('id', $data['id'])
  192. ->pluck('month')
  193. ->toArray();
  194. //归档
  195. list($status, $msg) = ArchiveService::isArchive($month, $user);
  196. if (!$status) return [false, $msg];
  197. ExpenseClaims::where('del_time', 0)
  198. ->whereIn('id', $data['id'])
  199. ->update(['del_time' => $time]);
  200. $old = ExpenseClaimsDetails::where('del_time', 0)
  201. ->where('expense_claims_id', $data['id'])
  202. ->where('file_url', '<>', '')
  203. ->pluck('file_url')
  204. ->all();
  205. ExpenseClaimsDetails::where('del_time', 0)
  206. ->whereIn('expense_claims_id', $data['id'])
  207. ->update(['del_time' => $time]);
  208. DB::commit();
  209. } catch (\Exception $exception) {
  210. DB::rollBack();
  211. return [false, $exception->getMessage()];
  212. }
  213. return [true, ['file' => ['old' => $old]]];
  214. }
  215. public function expenseClaimsDetail($data, $user)
  216. {
  217. if ($this->isEmpty($data, 'id')) return [false, '请选择数据!'];
  218. $customer = ExpenseClaims::where('del_time', 0)
  219. ->where('id', $data['id'])
  220. ->first();
  221. if (empty($customer)) return [false, '单据不存在或已被删除'];
  222. $customer = $customer->toArray();
  223. $customer['crt_name'] = Employee::where('id', $customer['crt_id'])->value('title');
  224. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s", $customer['crt_time']) : '';
  225. $map = ArchiveService::fillIsArchive($customer['month'], $user);
  226. $customer['is_archive'] = $map[$customer['month']] ?? false;
  227. $customer['month'] = $this->UtcTime($customer['month']);
  228. $details = $this->getDetail($data, $user);
  229. $customer["details"] = $details;
  230. return [true, $customer];
  231. }
  232. private function getDetail($data, $user)
  233. {
  234. $data = ExpenseClaimsDetails::where('del_time', 0)
  235. ->where('expense_claims_id', $data['id'])
  236. ->get()->toArray();
  237. $item_ids = collect($data)->pluck('item_id')->unique()->values()->all();
  238. $employee_ids = collect($data)->pluck('employee_id')->unique()->values()->all();
  239. $fee_ids = collect($data)->pluck('fee_id')->unique()->values()->all();
  240. $item = Item::TopClear($user, $data);
  241. $item_key_list = $item->whereIn('id', $item_ids)->pluck('title', 'id');
  242. $item = Employee::TopClear($user, $data);
  243. $employee_key_list = $item->whereIn('id', $employee_ids)->pluck('title', 'id');
  244. $item = Fee::TopClear($user, $data);
  245. $fee_key_list = $item->whereIn('id', $fee_ids)->pluck('title', 'id');
  246. $fileUploadService = new FileUploadService();
  247. foreach ($data as &$v) {
  248. // 1. 假设数据库里的 claim_date 是 Unix 时间戳(整数)
  249. // 2. createFromTimestamp 第二个参数设为 'UTC' 确保时间轴对齐
  250. // 3. toIso8601ZuluString() 会自动生成 T 和 Z 以及 .000 毫秒
  251. $v['claim_date'] = $this->UtcTime($v['claim_date']);
  252. $v['item_title'] = $item_key_list[$v['item_id']] ?? "";
  253. $v['employee_title'] = $employee_key_list[$v['employee_id']] ?? "";
  254. $v['fee_title'] = $fee_key_list[$v['fee_id']] ?? "";
  255. if (!empty($v['file_url'])) $v['file_url_show'] = $fileUploadService->getFileShow($v['file_url']);
  256. }
  257. return $data;
  258. }
  259. private function UtcTime($time)
  260. {
  261. return Carbon::createFromTimestamp($time, 'UTC')
  262. ->toIso8601ZuluString();
  263. }
  264. public function fillDataForExport($data, $column, &$return)
  265. {
  266. if (empty($data)) return;
  267. $mainIds = array_column($data, 'id');
  268. // 获取详情映射 [expense_claims_id => [details...]]
  269. $detailsMap = $this->getDetailsMap($mainIds);
  270. // 默认空行模板
  271. $defaultRow = array_fill_keys($column, '');
  272. foreach ($data as $main) {
  273. $mainId = $main['id'];
  274. $details = $detailsMap[$mainId] ?? [];
  275. // 提取主表信息
  276. $mainInfo = [
  277. 'code' => $main['code'],
  278. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  279. ];
  280. if (empty($details)) {
  281. // 如果没有详情,至少导出一行主表信息
  282. $return[] = array_merge($defaultRow, $mainInfo);
  283. } else {
  284. // 遍历明细,每一行明细都带上主表的 code 和 month
  285. foreach ($details as $sub) {
  286. // 合并主表字段 + 详情字段
  287. $fullRow = array_merge($mainInfo, $sub);
  288. // 仅保留 column 配置中要求的列
  289. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  290. }
  291. }
  292. }
  293. }
  294. public function getDetailsMap($main_ids)
  295. {
  296. // 1. 获取详情
  297. $details = ExpenseClaimsDetails::where('del_time', 0)
  298. ->whereIn('expense_claims_id', $main_ids)
  299. ->get();
  300. if ($details->isEmpty()) return [];
  301. // 2. 批量提取所有关联 ID 用于预加载
  302. $empIds = $details->pluck('employee_id')->filter()->unique();
  303. $itemIds = $details->pluck('item_id')->unique();
  304. $feeIds = $details->pluck('fee_id')->unique();
  305. // 3. 建立档案映射 Map
  306. $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
  307. $itemMap = Item::whereIn('id', $itemIds)->get()->keyBy('id');
  308. $feeMap = Fee::whereIn('id', $feeIds)->get()->keyBy('id');
  309. $res = [];
  310. foreach ($details as $item) {
  311. $tmpEmp = $empMap[$item->employee_id] ?? null;
  312. $tmpItem = $itemMap[$item->item_id] ?? null;
  313. $tmpFee = $feeMap[$item->fee_id] ?? null;
  314. // 4. 组装明细行字段 (key 要与模板配置中的 export 对应)
  315. $res[$item->expense_claims_id][] = [
  316. 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
  317. 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
  318. 'item_code' => $tmpItem ? $tmpItem->code : '',
  319. 'item_title' => $tmpItem ? $tmpItem->title : '',
  320. 'fee_code' => $tmpFee ? $tmpFee->code : '',
  321. 'fee_title' => $tmpFee ? $tmpFee->title : '',
  322. 'amount' => $item->amount,
  323. 'entrust1_amount' => $item->entrust1_amount,
  324. 'entrust2_amount' => $item->entrust2_amount,
  325. 'claim_date' => $item->claim_date ? date('Y-m-d', $item->claim_date) : '',
  326. 'voucher_no' => $item->voucher_no,
  327. 'remark' => $item->remark,
  328. 'entrust_type_title' => ExpenseClaimsDetails::State_Type[$item->entrust_type] ?? '',
  329. 'expense_type_title' => ExpenseClaimsDetails::State_Type_2[$item->expense_type] ?? '',
  330. ];
  331. }
  332. return $res;
  333. }
  334. }