ExpenseClaimsService.php 15 KB

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