AuxiliaryAccountService.php 20 KB

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