| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359 |
- <?php
- namespace App\Service;
- use App\Model\Employee;
- use App\Model\ExpenseClaims;
- use App\Model\ExpenseClaimsDetails;
- use App\Model\Fee;
- use App\Model\Item;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\DB;
- class ExpenseClaimsService extends Service
- {
- public function expenseClaimsList($data,$user){
- $model = $this->expenseClaimsSetCommon($data, $user);
- $list = $this->limit($model,'',$data);
- $list = $this->fillData($list);
- return [true, $list];
- }
- public function expenseClaimsSetCommon($data,$user, $field = []){
- if(empty($field)) $field = ExpenseClaims::$field;
- $model = ExpenseClaims::Clear($user,$data);
- $model = $model->where('del_time',0)
- ->select($field)
- ->orderby('id', 'desc');
- if(! empty($data['month'])) $model->where('month', $data['month']);
- if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
- if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
- $return = $this->changeDateToTimeStampAboutRange($data['time']);
- $model->where('month','>=',$return[0]);
- $model->where('month','<=',$return[1]);
- }
- return $model;
- }
- public function fillData($data){
- if(empty($data['data'])) return $data;
- $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
- foreach ($data['data'] as $key => $value){
- $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
- $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
- $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
- }
- return $data;
- }
- public function expenseClaimsAdd($data,$user){
- list($status,$msg) = $this->expenseClaimsRule($data, $user);
- if(! $status) return [$status, $msg];
- try {
- DB::beginTransaction();
- $model = new ExpenseClaims();
- $model->code = $this->generateBillNo([
- 'top_depart_id' => $user['top_depart_id'],
- 'type' => ExpenseClaims::Order_type,
- 'period' => date("Ym", $data['month'])
- ]);
- $model->month = $data['month'];
- $model->crt_id = $user['id'];
- $model->top_depart_id = $data['top_depart_id'];
- $model->save();
- list($old, $new) = $this->saveDetail($model->id, time(), $data, $user);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false, $exception->getLine()."_".$exception->getMessage()];
- }
- return [true, ['file' => ['old' => $old, 'new' => $new]]];
- }
- private function saveDetail($id, $time, $data, $user, $old = [])
- {
- $new = [];
- $unit = [];
- $oldFilesMap = array_flip($old);
- if (!empty($data['details']) && is_array($data['details'])) {
- foreach ($data['details'] as $value) {
- $unit[] = [
- 'expense_claims_id' => $id,
- 'item_id' => $value['item_id'] ?? 0,
- 'employee_id' => $value['employee_id'] ?? "",
- 'fee_id' => $value['fee_id'] ?? 0,
- 'amount' => $value['amount'] ?? 0,
- 'remark' => $value['remark'] ?? "",
- 'claim_date' => strtotime($value['claim_date']),
- 'entrust_type' => $value['entrust_type'] ?? 0,
- 'expense_type' => $value['expense_type'] ?? 0,
- 'voucher_no' => $value['voucher_no'] ?? "",
- 'file_url' => $value['file_url'] ?? "",
- 'file_name' => $value['file_name'] ?? "",
- 'top_depart_id' => $data['top_depart_id'] ?? 0,
- 'crt_time' => $time,
- 'crt_id' => $user['id'],
- ];
- $currentUrl = $value['file_url'] ?? "";
- if (!empty($currentUrl)) {
- if (isset($oldFilesMap[$currentUrl])) {
- unset($oldFilesMap[$currentUrl]);
- } else {
- $new[] = $currentUrl;
- }
- }
- }
- if (!empty($unit)) ExpenseClaimsDetails::insert($unit);
- }
- return [array_keys($oldFilesMap), $new];
- }
- private function expenseClaimsRule(&$data, $user, $is_add = true){
- $data['top_depart_id'] = $user['top_depart_id'];
- if (empty($data['month'])) return [false, '月份不能为空'];
- $data['month'] = $this->changeDateToDate($data['month']);
- // if(!isset($data['month'])) return [false,"月份必传"];
- // $monthStr = $data['month']; // 假设是 "2026-03"
- $monthStart = $data['month'];
- // 获取该月最后一秒:下个月 1 号减去 1 秒
- $monthEnd = strtotime('+1 month', $monthStart) - 1;
- if(empty($data['details'])) return [false, '项目费用报销单详情不能为空'];
- foreach ($data['details'] as $index => $item) {
- if(empty($item['item_id'])) return [false, "第" . ($index + 1) . "行项目不能为空"];
- if(empty($item['fee_id'])) return [false, "第" . ($index + 1) . "行费用类型不能为空"];
- if(! isset($item['amount'])) return [false, "第" . ($index + 1) . "行费用金额不存在"];
- $res = $this->checkNumber($item['amount'], 2, 'non-negative');
- if (! $res['valid']) return [false, "第" . ($index + 1) . "行费用金额" . $res['error']];
- if (!isset($item['claim_date'])) return [false, "第" . ($index + 1) . "行项费用产生日期缺失"];
- // 将报销日期转换为时间戳
- $claimTime = strtotime($item['claim_date']);
- // 判断:claim_date 必须早于 month
- // 如果 claim_date 是 2026-02-28,而 month 是 2026-03-01,则校验通过
- if ($claimTime < $monthStart || $claimTime > $monthEnd) return [false, "第" . ($index + 1) . "行项费用产生日期必须在当前月份内(" . date("Y-m", $data['month']) . ")"];
- }
- $query = ExpenseClaims::where('top_depart_id', $data['top_depart_id'])
- ->where('month', $monthStart)
- ->where('del_time', 0);
- if (!$is_add) {
- if (empty($data['id'])) return [false, 'ID不能为空'];
- $query->where('id', '<>', $data['id']);
- }
- if ($query->exists()) return [false, date("Y-m", $monthStart) . '已存在项目费用报销单'];
- return [true,""];
- }
- public function expenseClaimsEdit($data,$user){
- list($status,$msg) = $this->expenseClaimsRule($data, $user, false);
- if(!$status) return [$status,$msg];
- try {
- DB::beginTransaction();
- $model = ExpenseClaims::where('id',$data['id'])->first();
- // $model->month = $data['month'];
- // $model->crt_id = $user['id'];
- // $model->save();
- $time = time();
- $old = ExpenseClaimsDetails::where('del_time',0)
- ->where('expense_claims_id', $model->id)
- ->where('file_url','<>','')
- ->pluck('file_url')
- ->all();
- ExpenseClaimsDetails::where('del_time',0)
- ->where('expense_claims_id', $model->id)
- ->update(['del_time' => $time]);
- list($old, $new) = $this->saveDetail($model->id, $time, $data, $user, $old);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ['file' => ['old' => $old, 'new' => $new]]];
- }
- public function expenseClaimsDel($data){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- try {
- DB::beginTransaction();
- $time = time();
- ExpenseClaims::where('del_time',0)
- ->whereIn('id',$data['id'])
- ->update(['del_time' => $time]);
- $old = ExpenseClaimsDetails::where('del_time',0)
- ->where('expense_claims_id', $data['id'])
- ->where('file_url','<>','')
- ->pluck('file_url')
- ->all();
- ExpenseClaimsDetails::where('del_time',0)
- ->whereIn('expense_claims_id', $data['id'])
- ->update(['del_time' => $time]);
- DB::commit();
- }catch (\Exception $exception){
- DB::rollBack();
- return [false,$exception->getMessage()];
- }
- return [true, ['file' => ['old' => $old]]];
- }
- public function expenseClaimsDetail($data, $user){
- if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
- $customer = ExpenseClaims::where('del_time',0)
- ->where('id',$data['id'])
- ->first();
- if(empty($customer)) return [false,'单据不存在或已被删除'];
- $customer = $customer->toArray();
- $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
- $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
- $customer['month'] = $this->UtcTime($customer['month']);
- $details = $this->getDetail($data,$user);
- $customer["details"] = $details;
- return [true, $customer];
- }
- private function getDetail($data,$user){
- $data = ExpenseClaimsDetails::where('del_time',0)
- ->where('expense_claims_id', $data['id'])
- ->get()->toArray();
- $item_ids = collect($data)->pluck('item_id')->unique()->values()->all();
- $employee_ids = collect($data)->pluck('employee_id')->unique()->values()->all();
- $fee_ids = collect($data)->pluck('fee_id')->unique()->values()->all();
- $item = Item::TopClear($user, $data);
- $item_key_list = $item->whereIn('id',$item_ids)->pluck('title','id');
- $item = Employee::TopClear($user, $data);
- $employee_key_list = $item->whereIn('id',$employee_ids)->pluck('title','id');
- $item = Fee::TopClear($user, $data);
- $fee_key_list = $item->whereIn('id',$fee_ids)->pluck('title','id');
- $fileUploadService = new FileUploadService();
- foreach ($data as &$v) {
- // 1. 假设数据库里的 claim_date 是 Unix 时间戳(整数)
- // 2. createFromTimestamp 第二个参数设为 'UTC' 确保时间轴对齐
- // 3. toIso8601ZuluString() 会自动生成 T 和 Z 以及 .000 毫秒
- $v['claim_date'] = $this->UtcTime( $v['claim_date']);
- $v['item_title'] = $item_key_list[$v['item_id']] ?? "";
- $v['employee_title'] = $employee_key_list[$v['employee_id']] ?? "";
- $v['fee_title'] = $fee_key_list[$v['fee_id']] ?? "";
- if(! empty($v['file_url'])) $v['file_url_show'] = $fileUploadService->getFileShow($v['file_url']);
- }
- return $data;
- }
- private function UtcTime($time){
- return Carbon::createFromTimestamp($time, 'UTC')
- ->toIso8601ZuluString();
- }
- public function fillDataForExport($data, $column, &$return)
- {
- if (empty($data)) return;
- $mainIds = array_column($data, 'id');
- // 获取详情映射 [expense_claims_id => [details...]]
- $detailsMap = $this->getDetailsMap($mainIds);
- // 默认空行模板
- $defaultRow = array_fill_keys($column, '');
- foreach ($data as $main) {
- $mainId = $main['id'];
- $details = $detailsMap[$mainId] ?? [];
- // 提取主表信息
- $mainInfo = [
- 'code' => $main['code'],
- 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
- ];
- if (empty($details)) {
- // 如果没有详情,至少导出一行主表信息
- $return[] = array_merge($defaultRow, $mainInfo);
- } else {
- // 遍历明细,每一行明细都带上主表的 code 和 month
- foreach ($details as $sub) {
- // 合并主表字段 + 详情字段
- $fullRow = array_merge($mainInfo, $sub);
- // 仅保留 column 配置中要求的列
- $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
- }
- }
- }
- }
- public function getDetailsMap($main_ids)
- {
- // 1. 获取详情
- $details = ExpenseClaimsDetails::where('del_time', 0)
- ->whereIn('expense_claims_id', $main_ids)
- ->get();
- if ($details->isEmpty()) return [];
- // 2. 批量提取所有关联 ID 用于预加载
- $empIds = $details->pluck('employee_id')->filter()->unique();
- $itemIds = $details->pluck('item_id')->unique();
- $feeIds = $details->pluck('fee_id')->unique();
- // 3. 建立档案映射 Map
- $empMap = Employee::whereIn('id', $empIds)->get()->keyBy('id');
- $itemMap = Item::whereIn('id', $itemIds)->get()->keyBy('id');
- $feeMap = Fee::whereIn('id', $feeIds)->get()->keyBy('id');
- $res = [];
- foreach ($details as $item) {
- $tmpEmp = $empMap[$item->employee_id] ?? null;
- $tmpItem = $itemMap[$item->item_id] ?? null;
- $tmpFee = $feeMap[$item->fee_id] ?? null;
- // 4. 组装明细行字段 (key 要与模板配置中的 export 对应)
- $res[$item->expense_claims_id][] = [
- 'employee_number' => $tmpEmp ? $tmpEmp->number : '',
- 'employee_title' => $tmpEmp ? $tmpEmp->title : '',
- 'item_code' => $tmpItem ? $tmpItem->code : '',
- 'item_title' => $tmpItem ? $tmpItem->title : '',
- 'fee_code' => $tmpFee ? $tmpFee->code : '',
- 'fee_title' => $tmpFee ? $tmpFee->title : '',
- 'amount' => $item->amount,
- 'claim_date' => $item->claim_date ? date('Y-m-d', $item->claim_date) : '',
- 'voucher_no' => $item->voucher_no,
- 'remark' => $item->remark,
- 'entrust_type_title' => ExpenseClaimsDetails::State_Type[$item->entrust_type] ?? '',
- 'expense_type_title' => ExpenseClaimsDetails::State_Type_2[$item->expense_type] ?? '',
- ];
- }
- return $res;
- }
- }
|