ExpenseClaimsService.php 16 KB

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