AuxiliaryAccountService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. namespace App\Service;
  3. use App\Model\AuxiliaryAccount;
  4. use App\Model\AuxiliaryAccountDetails;
  5. use App\Model\Employee;
  6. use App\Model\ExpenseClaims;
  7. use App\Model\ExpenseClaimsDetails;
  8. use App\Model\Fee;
  9. use App\Model\MonthlyDdOrder;
  10. use App\Model\MonthlyDdOrderDetails;
  11. use App\Model\MonthlyPsOrder;
  12. use App\Model\MonthlyPsOrderDetails;
  13. use Carbon\Carbon;
  14. use Illuminate\Support\Facades\DB;
  15. class AuxiliaryAccountService extends Service
  16. {
  17. public function auxiliaryAccountList($data,$user){
  18. $model = $this->setCommon($data, $user);
  19. $list = $this->limit($model,'',$data);
  20. $list = $this->fillData($list);
  21. return [true, $list];
  22. }
  23. public function setCommon($data,$user, $field = []){
  24. if(empty($field)) $field = AuxiliaryAccount::$field;
  25. $model = AuxiliaryAccount::Clear($user,$data);
  26. $model = $model->where('del_time',0)
  27. ->select($field)
  28. ->orderby('month', 'desc');
  29. if(! empty($data['month'])) $model->where('month', $data['month']);
  30. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  31. if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
  32. $return = $this->changeDateToTimeStampAboutRange($data['time']);
  33. $model->where('month','>=',$return[0]);
  34. $model->where('month','<=',$return[1]);
  35. }
  36. return $model;
  37. }
  38. public function fillData($data){
  39. if(empty($data['data'])) return $data;
  40. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_column($data['data'],'crt_id')));
  41. foreach ($data['data'] as $key => $value){
  42. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  43. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  44. $data['data'][$key]['month'] = $value['month'] ? date('Y-m',$value['month']) : '';
  45. }
  46. return $data;
  47. }
  48. public function auxiliaryAccountSummary($data,$user){
  49. //传参月份
  50. if(!isset($data['month'])) return [201,'月份必传'];
  51. $month = $data['month'];
  52. $monthStart = strtotime($month);
  53. $monthEnd = strtotime("$month +1 month") - 1;
  54. //获取员工汇总月份工资
  55. list($status,$employee_month_amount) = $this->employeeMonthAmount($data,$user,$monthStart,$monthEnd);
  56. if (!$status) return [$status,$employee_month_amount];
  57. //获取设备折旧费用
  58. list($status,$device_month_amount) = $this->deviceMonthAmount($data,$user,$monthStart,$monthEnd);
  59. if (!$status) return [$status,$device_month_amount];
  60. //获取费用汇总的费用数据
  61. list($status,$fee_month_amount) = $this->feeMonthAmount($data,$user,$monthStart,$monthEnd);
  62. if (!$status) return [$status,$fee_month_amount];
  63. return [true,[
  64. "employee_month_amount" => $employee_month_amount,
  65. "device_month_amount" => $device_month_amount,
  66. "fee_month_amount" => $fee_month_amount,
  67. ]];
  68. }
  69. private function employeeMonthAmount($month,$user,$monthStart,$monthEnd){
  70. $data['top_depart_id'] = $user['top_depart_id'];
  71. $month_ps_order = MonthlyPsOrder::Clear($user,$data);
  72. $month_ps_order_id = $month_ps_order->where('del_time',0)->where("month",$monthStart)->first();
  73. if(empty($month_ps_order_id)){
  74. return [false,"请补充对应月份人员月度工资信息"];
  75. }else{
  76. $month_ps_order_id = $month_ps_order_id->id;
  77. }
  78. $model = MonthlyPsOrderDetails::Clear($user,$data);
  79. //总金额
  80. $total_amount = $model->where('main_id',$month_ps_order_id)->where('del_time',0)->sum("salary");
  81. //委内
  82. $entrust_in_amount = $model->where('main_id',$month_ps_order_id)->where("entrust_type",1)->sum("salary");
  83. //委外
  84. $entrust_out_amount = $model->where('main_id',$month_ps_order_id)->where("entrust_type",2)->sum("salary");
  85. return [true,[
  86. "total_amount" => $total_amount,
  87. "entrust_in_amount" => $entrust_in_amount,
  88. "entrust_out_amount" => $entrust_out_amount,
  89. ]];
  90. }
  91. private function deviceMonthAmount($month,$user,$monthStart,$monthEnd){
  92. $data['top_depart_id'] = $user['top_depart_id'];
  93. $month_ps_order = MonthlyDdOrder::Clear($user,$data);
  94. $month_ps_order_id = $month_ps_order->where('del_time',0)->where("month",$monthStart)->first();
  95. if(empty($month_ps_order_id)){
  96. return [false,"请补充对应月份设备月度折旧信息"];
  97. }else{
  98. $month_ps_order_id = $month_ps_order_id->id;
  99. }
  100. $model = MonthlyDdOrderDetails::Clear($user,$data);
  101. //总金额
  102. $total_amount = $model->where('main_id',$month_ps_order_id)->sum("depreciation_amount");
  103. return [true,[
  104. "total_amount" => $total_amount,
  105. ]];
  106. }
  107. private function feeMonthAmount($month,$user,$monthStart,$monthEnd){
  108. $data['top_depart_id'] = $user['top_depart_id'];
  109. $month_ps_order = ExpenseClaims::Clear($user,$data);
  110. $month_ps_order_id = $month_ps_order->where('del_time',0)->where("month",$monthStart)->first();
  111. if(empty($month_ps_order_id)){
  112. return [false,"请补充对应月份费用信息"];
  113. }else{
  114. $month_ps_order_id = $month_ps_order_id->id;
  115. }
  116. $model = new ExpenseClaimsDetails();
  117. //总金额
  118. $list = $model->where('expense_claims_id',$month_ps_order_id)->where('del_time',0)->select("fee_id","amount as total_amount","remark","entrust_type","item_id")->get()->toArray();
  119. foreach ($list as &$v){
  120. $v['entrust1_amount'] = $v['entrust_type'] == 1 ? $v['total_amount'] : 0;
  121. $v['entrust2_amount'] = $v['entrust_type'] == 2 ? $v['total_amount'] : 0;
  122. }
  123. ///分组
  124. $fee_type_list = Fee::Clear($user,$data)->where('del_time',0)->select("title","id","parent_id")->get()->toArray();
  125. return [true,$this->groupListByRoot($list,$fee_type_list)];
  126. }
  127. /**
  128. * 将报销明细按照一级费用分类进行分组
  129. * * @param array $list 报销明细列表 (含 fee_id, amount 等)
  130. * @param array $fee_type_list 费用类型树 (含 id, parent_id, title)
  131. * @return array
  132. */
  133. public function groupListByRoot(array $list, array $fee_type_list)
  134. {
  135. // 1. 建立 ID 索引,方便快速查找
  136. $idMap = array_column($fee_type_list, null, 'id');
  137. // 2. 预处理映射表:让所有子 ID 直接指向它的最顶层“祖宗” ID
  138. $childToRoot = [];
  139. $grouped = [];
  140. foreach ($fee_type_list as $type) {
  141. $current = $type;
  142. // 向上追溯直到 parent_id 为 0,即找到一级分类
  143. while ($current['parent_id'] != 0) {
  144. $current = $idMap[$current['parent_id']];
  145. }
  146. $childToRoot[$type['id']] = [
  147. 'id' => $current['id'],
  148. 'title' => $current['title']
  149. ];
  150. // if (!isset($grouped[$current['id']])) {
  151. // $grouped[$current['id']] = [
  152. // 'first_level_id' => $current['id'],
  153. // 'first_level_title' => $current['title'],
  154. // 'details' => []
  155. // ];
  156. // }
  157. }
  158. $map = Fee::whereIn('id', array_unique(array_column($list,'fee_id')))
  159. ->pluck('title','id')
  160. ->all();
  161. // 3. 遍历明细数据进行分组
  162. foreach ($list as $item) {
  163. $feeId = $item['fee_id'];
  164. $item['fee_title'] = $map[$item['fee_id']] ?? "";
  165. // 获取该费用对应的一级分类信息
  166. $rootInfo = $childToRoot[$feeId] ?? ['id' => 0, 'title' => '其他费用'];
  167. $rootId = $rootInfo['id'];
  168. if (!isset($grouped[$rootId])) {
  169. $grouped[$rootId] = [
  170. 'first_level_id' => $rootId,
  171. 'first_level_title' => $rootInfo['title'],
  172. 'details' => []
  173. ];
  174. }
  175. $grouped[$rootId]['details'][] = $item;
  176. }
  177. // 4. 重置数组索引并返回
  178. return array_values($grouped);
  179. }
  180. public function auxiliaryAccountAdd($data,$user){
  181. list($status,$msg) = $this->auxiliaryAccountRule($data, $user);
  182. if(!$status) return [$status,$msg];
  183. try {
  184. DB::beginTransaction();
  185. $model = new AuxiliaryAccount();
  186. $model->code = $this->generateBillNo([
  187. 'top_depart_id' => $user['top_depart_id'],
  188. 'type' => ExpenseClaims::Order_type,
  189. 'period' => date("Ym", $data['month'])
  190. ]);
  191. $model->month = $data['month'];
  192. $model->crt_id = $user['id'];
  193. $model->top_depart_id = $data['top_depart_id'];
  194. $model->save();
  195. $this->saveDetail($model->id, time(), $data,$user['id'],$user);
  196. DB::commit();
  197. }catch (\Exception $exception){
  198. DB::rollBack();
  199. return [false,$exception->getLine().':'.$exception->getMessage()];
  200. }
  201. return [true, ''];
  202. }
  203. private function saveDetail($id, $time, $data,$crt_id,$user){
  204. if(! empty($data['details'])){
  205. $unit = [];
  206. foreach ($data['details'] as $value){
  207. $unit[] = [
  208. 'auxiliary_account_id' => $id,
  209. 'voucher_date' => strtotime($value['voucher_date']),
  210. 'voucher_type' => $value['voucher_type'],
  211. 'voucher_no' => $value['voucher_no'],
  212. 'voucher_remark' => $value['voucher_remark'],
  213. 'voucher_amount' => $value['voucher_amount'],
  214. 'entrust_type' => $value['entrust_type']??"",
  215. 'type' => $value['type'],
  216. 'fee_id' => $value['fee_id']??0,
  217. 'remark' => $value['remark']??"",
  218. 'entrust1_amount' => $value['entrust1_amount']??0,
  219. 'entrust2_amount' => $value['entrust2_amount']??0,
  220. 'aggregation_amount' => $value['aggregation_amount']??00,
  221. 'total_amount' => $value['total_amount'],
  222. 'top_depart_id' => $user['top_depart_id'],
  223. 'item_id' => $value['item_id'],
  224. 'crt_time' => $time,
  225. 'crt_id' => $crt_id,
  226. ];
  227. }
  228. if(!empty($unit)) AuxiliaryAccountDetails::insert($unit);
  229. }
  230. }
  231. private function auxiliaryAccountRule(&$data, $user, $is_add = true){
  232. $data['top_depart_id'] = $user['top_depart_id'];
  233. if (empty($data['month'])) return [false, '月份不能为空'];
  234. $data['month'] = $this->changeDateToDate($data['month']);
  235. $monthStart = $data['month'];
  236. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  237. if(empty($data['details'])) return [false, '研发支出辅助账单明细不能为空'];
  238. // 初始化各类型的计数器
  239. $typeCounters = [];
  240. $fee_map = Fee::where('top_depart_id', $data['top_depart_id'])
  241. ->whereIn('id', array_unique(array_column($data['details'], 'fee_id')))
  242. ->pluck('title', 'id')
  243. ->all();
  244. foreach ($data['details'] as $item) {
  245. if(empty($item['type']) || ! isset(AuxiliaryAccountDetails::Type[$item['type']])) return [false, 'type类型不能为空或错误'];
  246. $type = $item['type'];
  247. $tabName = AuxiliaryAccountDetails::Type[$item['type']];
  248. // 针对当前 type 的行数进行累加
  249. if($type == AuxiliaryAccountDetails::TYPE_ONE || $type == AuxiliaryAccountDetails::TYPE_TWO|| $type == AuxiliaryAccountDetails::TYPE_THREE){
  250. if (!isset($typeCounters[$type])) {
  251. $typeCounters[$type] = 1;
  252. } else {
  253. $typeCounters[$type]++;
  254. }
  255. }else{
  256. if(empty($item['fee_id'])) return [false, '费用类型id不能为空'];
  257. $fee_t = $fee_map[$item['fee_id']] ?? "";
  258. if(empty($fee_t)) return [false, '费用类型不存在'];
  259. $tabName = $fee_t;
  260. $new_key = $type . $item['fee_id'];
  261. if (!isset($typeCounters[$new_key])) {
  262. $typeCounters[$new_key] = 1;
  263. } else {
  264. $typeCounters[$new_key]++;
  265. }
  266. }
  267. $errorPrefix = "【{$tabName}】第 " . $typeCounters[$type] . " 行:";
  268. if (!isset($item['voucher_date'])) {
  269. return [false, $errorPrefix . "凭证日期缺失"];
  270. }
  271. // 将报销日期转换为时间戳
  272. $claimTime = strtotime($item['voucher_date']);
  273. // 判断:voucher_date 必须早于 month
  274. // 如果 voucher_date 是 2026-02-28,而 month 是 2026-03-01,则校验通过
  275. if ($claimTime < $monthStart || $claimTime > $monthEnd) return [false, $errorPrefix . "凭证日期必须早于当前结算月份(" . date("Y-m", $data['month']) . ")"];
  276. if (!isset($item['voucher_type'])) {
  277. return [false, $errorPrefix . "凭证种类缺失"];
  278. }
  279. if (!isset($item['voucher_no'])) {
  280. return [false, $errorPrefix . "凭证号数缺失"];
  281. }
  282. if (!isset($item['voucher_remark'])) {
  283. return [false, $errorPrefix . "凭证摘要缺失"];
  284. }
  285. if (!isset($item['voucher_amount'])) {
  286. return [false, $errorPrefix . "会计凭证记载金额缺失"];
  287. }
  288. $res = $this->checkNumber($item['voucher_amount'], 2, 'non-negative');
  289. if (! $res['valid']) return [false, $errorPrefix . "会计凭证记载金额" . $res['error']];
  290. if (!isset($item['aggregation_amount'])) {
  291. return [false, $errorPrefix . "税法规定的归集金额缺失"];
  292. }
  293. $res = $this->checkNumber($item['aggregation_amount'], 2, 'non-negative');
  294. if (! $res['valid']) return [false, $errorPrefix . "税法规定的归集金额" . $res['error']];
  295. }
  296. $query = AuxiliaryAccount::where('top_depart_id', $user['top_depart_id'])
  297. ->where('month', $monthStart)
  298. ->where('del_time', 0);
  299. if (!$is_add) {
  300. if (empty($data['id'])) return [false, 'ID不能为空'];
  301. $query->where('id', '<>', $data['id']);
  302. }
  303. if ($query->exists()) return [false, date("Y-m", $monthStart) . '已存在研发支出辅助账单'];
  304. return [true, ''];
  305. }
  306. public function auxiliaryAccountEdit($data,$user){
  307. list($status,$msg) = $this->auxiliaryAccountRule($data, $user, false);
  308. if(!$status) return [$status,$msg];
  309. try {
  310. DB::beginTransaction();
  311. $model = AuxiliaryAccount::where('id',$data['id'])->first();
  312. // $model->save();
  313. $time = time();
  314. AuxiliaryAccountDetails::where('del_time',0)
  315. ->where('auxiliary_account_id', $model->id)
  316. ->update(['del_time' => $time]);
  317. $this->saveDetail($model->id, $time, $data,$user['id']);
  318. DB::commit();
  319. }catch (\Exception $exception){
  320. DB::rollBack();
  321. return [false,$exception->getMessage()];
  322. }
  323. return [true, ''];
  324. }
  325. public function auxiliaryAccountDel($data){
  326. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  327. try {
  328. DB::beginTransaction();
  329. $time = time();
  330. AuxiliaryAccount::where('del_time',0)
  331. ->whereIn('id',$data['id'])
  332. ->update(['del_time' => $time]);
  333. AuxiliaryAccountDetails::where('del_time',0)
  334. ->whereIn('auxiliary_account_id', $data['id'])
  335. ->update(['del_time' => $time]);
  336. DB::commit();
  337. }catch (\Exception $exception){
  338. DB::rollBack();
  339. return [false,$exception->getMessage()];
  340. }
  341. return [true, ''];
  342. }
  343. public function auxiliaryAccountDetail($data, $user){
  344. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  345. $customer = AuxiliaryAccount::where('del_time',0)
  346. ->where('id',$data['id'])
  347. ->first();
  348. if(empty($customer)) return [false,'单据不存在或已被删除'];
  349. $customer = $customer->toArray();
  350. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  351. $customer['crt_time'] =$this->utcTime($customer['crt_time']);
  352. $customer['month'] =$this->utcTime($customer['month']);
  353. $details = $this->getDetail($data['id']);
  354. $customer["details"] = $details;
  355. return [true, $customer];
  356. }
  357. private function getDetail($id){
  358. $data = AuxiliaryAccountDetails::where('del_time',0)
  359. ->where('auxiliary_account_id', $id)
  360. ->get()->toArray();
  361. $map = Fee::whereIn('id', array_unique(array_column($data,'fee_id')))
  362. ->pluck('title','id')
  363. ->all();
  364. foreach ($data as &$v){
  365. $v['voucher_date'] = $this->utcTime($v['voucher_date']);
  366. $v['fee_title'] = $map[$v['fee_id']] ?? "";
  367. }
  368. return $data;
  369. }
  370. private function utcTime($time){
  371. return Carbon::createFromTimestamp($time, 'UTC')
  372. ->toIso8601ZuluString();
  373. }
  374. public function fillDataForExport($data, $column, &$return)
  375. {
  376. if (empty($data)) return;
  377. $mainIds = array_column($data, 'id');
  378. // 获取详情映射 [expense_claims_id => [details...]]
  379. $detailsMap = $this->getDetailsMap($mainIds);
  380. // 默认空行模板
  381. $defaultRow = array_fill_keys($column, '');
  382. foreach ($data as $main) {
  383. $mainId = $main['id'];
  384. $details = $detailsMap[$mainId] ?? [];
  385. // 提取主表信息
  386. $mainInfo = [
  387. 'code' => $main['code'],
  388. 'month' => $main['month'] ? date('Y-m', $main['month']) : '',
  389. ];
  390. if (empty($details)) {
  391. // 如果没有详情,至少导出一行主表信息
  392. $return[] = array_merge($defaultRow, $mainInfo);
  393. } else {
  394. // 遍历明细,每一行明细都带上主表的 code 和 month
  395. foreach ($details as $sub) {
  396. // 合并主表字段 + 详情字段
  397. $fullRow = array_merge($mainInfo, $sub);
  398. // 仅保留 column 配置中要求的列
  399. $return[] = array_merge($defaultRow, array_intersect_key($fullRow, $defaultRow));
  400. }
  401. }
  402. }
  403. }
  404. public function getDetailsMap($main_ids)
  405. {
  406. // 1. 获取详情
  407. $details = AuxiliaryAccountDetails::where('del_time', 0)
  408. ->whereIn('auxiliary_account_id', $main_ids)
  409. ->get();
  410. if ($details->isEmpty()) return [];
  411. // 2. 批量提取所有关联 ID 用于预加载
  412. $feeIds = $details->pluck('fee_id')->unique();
  413. // 3. 建立档案映射 Map
  414. $feeMap = Fee::whereIn('id', $feeIds)->get()->keyBy('id');
  415. $res = [];
  416. foreach ($details as $item) {
  417. $tmpFee = $feeMap[$item->fee_id] ?? null;
  418. $t = $tmpFee ? $tmpFee->title : '';
  419. if($item->type == AuxiliaryAccountDetails::TYPE_ONE || $item->type == AuxiliaryAccountDetails::TYPE_TWO){
  420. $type_title = AuxiliaryAccountDetails::Type[$item->type] ?? "";
  421. }else{
  422. $type_title = $t;
  423. }
  424. // 4. 组装明细行字段 (key 要与模板配置中的 export 对应)
  425. $res[$item->auxiliary_account_id][] = [
  426. 'type_title' => $type_title,
  427. 'voucher_date' => $item->voucher_date ? date('Y-m-d', $item->voucher_date) : '',
  428. 'voucher_type' => $item->voucher_type,
  429. 'voucher_no' => $item->voucher_no,
  430. 'voucher_remark' => $item->voucher_remark,
  431. 'voucher_amount' => $item->voucher_amount,
  432. 'aggregation_amount' => $item->aggregation_amount,
  433. 'total_amount' => $item->total_amount,
  434. 'entrust1_amount' => $item->entrust1_amount,
  435. 'entrust2_amount' => $item->entrust2_amount,
  436. 'remark' => $item->remark,
  437. 'fee_title' => $t,
  438. ];
  439. }
  440. return $res;
  441. }
  442. }