AuxiliaryAccountService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 = $user['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. if (empty($data['month'])) return [false, '月份不能为空'];
  228. $data['month'] = $this->changeDateToDate($data['month']);
  229. $monthStart = $data['month'];
  230. $monthEnd = strtotime('+1 month', $monthStart) - 1;
  231. if(empty($data['details'])) return [false, '研发支出辅助账单明细不能为空'];
  232. // 初始化各类型的计数器
  233. $typeCounters = [];
  234. foreach ($data['details'] as $item) {
  235. if(empty($item['type']) || ! isset(AuxiliaryAccountDetails::Type[$item['type']])) return [false, 'type类型不能为空或错误'];
  236. $type = $item['type'];
  237. $tabName = AuxiliaryAccountDetails::Type[$item['type']];
  238. // 针对当前 type 的行数进行累加
  239. if (!isset($typeCounters[$type])) {
  240. $typeCounters[$type] = 1;
  241. } else {
  242. $typeCounters[$type]++;
  243. }
  244. $errorPrefix = "【{$tabName}】第 " . $typeCounters[$type] . " 行:";
  245. if (!isset($item['voucher_date'])) {
  246. return [false, $errorPrefix . "凭证日期缺失"];
  247. }
  248. // 将报销日期转换为时间戳
  249. $claimTime = strtotime($item['voucher_date']);
  250. // 判断:voucher_date 必须早于 month
  251. // 如果 voucher_date 是 2026-02-28,而 month 是 2026-03-01,则校验通过
  252. if ($claimTime < $monthStart || $claimTime > $monthEnd) return [false, $errorPrefix . "凭证日期必须早于当前结算月份(" . date("Y-m", $data['month']) . ")"];
  253. if (!isset($item['voucher_type'])) {
  254. return [false, $errorPrefix . "凭证种类缺失"];
  255. }
  256. if (!isset($item['voucher_no'])) {
  257. return [false, $errorPrefix . "凭证号数缺失"];
  258. }
  259. if (!isset($item['voucher_remark'])) {
  260. return [false, $errorPrefix . "凭证摘要缺失"];
  261. }
  262. if (!isset($item['voucher_amount'])) {
  263. return [false, $errorPrefix . "会计凭证记载金额缺失"];
  264. }
  265. $res = $this->checkNumber($item['voucher_amount'], 2, 'non-negative');
  266. if (! $res['valid']) return [false, $errorPrefix . "会计凭证记载金额" . $res['error']];
  267. if (!isset($item['aggregation_amount'])) {
  268. return [false, $errorPrefix . "税法规定的归集金额缺失"];
  269. }
  270. $res = $this->checkNumber($item['aggregation_amount'], 2, 'non-negative');
  271. if (! $res['valid']) return [false, $errorPrefix . "税法规定的归集金额" . $res['error']];
  272. }
  273. $query = AuxiliaryAccount::where('top_depart_id', $user['top_depart_id'])
  274. ->where('month', $monthStart)
  275. ->where('del_time', 0);
  276. if (!$is_add) {
  277. if (empty($data['id'])) return [false, 'ID不能为空'];
  278. $query->where('id', '<>', $data['id']);
  279. }
  280. if ($query->exists()) return [false, date("Y-m", $monthStart) . '已存在研发支出辅助账单'];
  281. return [true, ''];
  282. }
  283. public function auxiliaryAccountEdit($data,$user){
  284. list($status,$msg) = $this->auxiliaryAccountRule($data, $user, false);
  285. if(!$status) return [$status,$msg];
  286. try {
  287. DB::beginTransaction();
  288. $model = AuxiliaryAccount::where('id',$data['id'])->first();
  289. // $model->save();
  290. $time = time();
  291. AuxiliaryAccountDetails::where('del_time',0)
  292. ->where('auxiliary_account_id', $model->id)
  293. ->update(['del_time' => $time]);
  294. $this->saveDetail($model->id, $time, $data,$user['id']);
  295. DB::commit();
  296. }catch (\Exception $exception){
  297. DB::rollBack();
  298. return [false,$exception->getMessage()];
  299. }
  300. return [true, ''];
  301. }
  302. public function auxiliaryAccountDel($data){
  303. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  304. try {
  305. DB::beginTransaction();
  306. $time = time();
  307. AuxiliaryAccount::where('del_time',0)
  308. ->whereIn('id',$data['id'])
  309. ->update(['del_time' => $time]);
  310. AuxiliaryAccountDetails::where('del_time',0)
  311. ->whereIn('auxiliary_account_id', $data['id'])
  312. ->update(['del_time' => $time]);
  313. DB::commit();
  314. }catch (\Exception $exception){
  315. DB::rollBack();
  316. return [false,$exception->getMessage()];
  317. }
  318. return [true, ''];
  319. }
  320. public function auxiliaryAccountDetail($data, $user){
  321. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  322. $customer = AuxiliaryAccount::where('del_time',0)
  323. ->where('id',$data['id'])
  324. ->first();
  325. if(empty($customer)) return [false,'单据不存在或已被删除'];
  326. $customer = $customer->toArray();
  327. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  328. $customer['crt_time'] =$this->utcTime($customer['crt_time']);
  329. $customer['month'] =$this->utcTime($customer['month']);
  330. $details = $this->getDetail($data['id']);
  331. $customer["details"] = $details;
  332. return [true, $customer];
  333. }
  334. private function getDetail($id){
  335. $data = AuxiliaryAccountDetails::where('del_time',0)
  336. ->where('auxiliary_account_id', $id)
  337. ->get()->toArray();
  338. $map = Fee::whereIn('id', array_unique(array_column($data,'fee_id')))
  339. ->pluck('title','id')
  340. ->all();
  341. foreach ($data as &$v){
  342. $v['voucher_date'] = $this->utcTime($v['voucher_date']);
  343. $v['fee_title'] = $map[$v['fee_id']] ?? "";
  344. }
  345. return $data;
  346. }
  347. private function utcTime($time){
  348. return Carbon::createFromTimestamp($time, 'UTC')
  349. ->toIso8601ZuluString();
  350. }
  351. }