ComonOrder.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\admin\controller;
  4. use app\admin\model\CgdInfo;
  5. use app\admin\model\CompanyInfo;
  6. use app\admin\model\InvoicePay;
  7. use app\admin\model\InvoicePool;
  8. use app\admin\model\InvoicePoolInfo;
  9. use app\admin\model\OrderCategory;use app\admin\model\Pay;
  10. use app\admin\model\PayInfo;
  11. use app\admin\model\QrdInfo;
  12. use app\admin\model\ReportCode;
  13. use app\admin\model\SupplierInfo;
  14. use app\admin\model\TagLog;
  15. use think\App;
  16. use think\Exception;
  17. use think\facade\Config;
  18. use think\facade\Db;
  19. use think\facade\Validate;
  20. //通用订单处理
  21. class ComonOrder extends Base
  22. {
  23. public $model=null;
  24. protected $typename;
  25. protected $invoiceType;
  26. protected $invName;
  27. protected $kingInvoice;
  28. public function __construct(App $app) {
  29. parent::__construct($app);
  30. $this->model = new \app\admin\model\ComonOrder();
  31. $invoice =Config::get('invoiceType');
  32. $this->invoiceType = $invoice['invoiceName'];
  33. $this->invName = $invoice['invoiceType'];
  34. $this->typename = $invoice['KingName'];
  35. $this->kingInvoice = $invoice['KingInvoice'];
  36. }
  37. public function list(){
  38. $post = $this->request->only(["start"=>"","end"=>"","cxCode"=>"","orderCode"=>[],"customerNo"=>"",
  39. 'cgd_status'=>'',"companyNo"=>"",'status'=>[],'relaComNo'=>'','platform_type'=>'','inv_status'=>'',
  40. 'pay_status'=>'',"good_status"=>"", 'page'=>1,'size'=>15],"post","trim");
  41. $where=[["qrd.is_del","=",0],['cgd.is_del','=',0],['qrd.totalPrice','<>',0],['cgd.totalPrice','<>',0]];
  42. $post['start']==''?:$where[]=["comon_order.addtime",">=",date("Y-m-d 00:00:00",strtotime($post['start']))];
  43. $post['end']==''?:$where[]=["comon_order.addtime","<=",date("Y-m-d 23:59:59",strtotime($post['end']))];
  44. $post['cxCode']==''?:$where[]=["comon_order.cxCode","like","%{$post['cxCode']}%"];
  45. $post['customerNo']==''?:$where[]=["comon_order.customerNo","=",$post['customerNo']];
  46. empty($post['status'])?:$where[]=['comon_order.status','in',$post['status']];
  47. empty($post['orderCode'])?:$where[]=['comon_order.orderCode','in',$post['orderCode']];
  48. $post['inv_status']==''?:$where[]=["qrd.inv_status","=",$post['inv_status']];
  49. $post['pay_status']==''?:$where[]=["qrd.pay_status","=",$post['pay_status']];
  50. $post['platform_type']==''?:$where[]=["comon_order.platform_type","=",$post['platform_type']];
  51. $post['cgd_status']===''?:$where[]=['cgd.cgd_status','=',$post['cgd_status']];
  52. $post['companyNo']==''?:$where[]=["comon_order.companyNo|comon_order.supplierNo","=",$post['companyNo']];
  53. $post['relaComNo']==''?:$where[]=["comon_order.companyNo|comon_order.supplierNo|comon_order.customerNo","=", $post['relaComNo']];
  54. $post['good_status']===''?:$where[]=["good.status","=",$post['good_status']];
  55. $list=$this->model->withJoin(["qrd","cgd","good"],"left")->where($where)
  56. ->order("id desc")->paginate (["page"=>$post['page'],"list_rows"=>$post['size']]);
  57. $this->success("0",["list"=>$list->items(),"count"=>$list->total()]);
  58. }
  59. //通用订单创建对账单
  60. public function PayCreate(){
  61. $param=$this->request->only(["common_ids"=>[]],"post","trim");
  62. $valid=Validate::rule(["common_ids|通用订单id集合"=>"require|array"]);
  63. if($valid->check($param)==false)$this->error($valid->getError());
  64. $obj = $this->model->with(['cgd'])->where(["id"=>$param['common_ids']])->select();
  65. if($obj->isEmpty())$this->error("未找到相关数据");
  66. $list = $obj->toArray();
  67. $status = array_unique(array_column($list,"status"));
  68. $supplierNo = array_unique(array_column($list,"supplierNo"));
  69. $customerNo = array_unique(array_column($list,"customerNo"));
  70. $goodNo = array_unique(array_column($list,"goodNo"));
  71. if(in_array(1,$status)|| in_array(2,$status))$this->error('提交数据存在已对账或对账中的数据');
  72. $supplierName = \app\admin\model\SupplierInfo::whereIn("code",$supplierNo)->value("name",'');
  73. $customerName = \app\admin\model\CompanyInfo::whereIn("companyNo",$customerNo)->value("company_name",'');
  74. if(count($supplierNo)>1)$this->error('提交数据采购供应商存在不一致');
  75. if(count($customerNo)>1)$this->error('提交数据销售客户存在不一致');
  76. $good_info = \app\admin\model\Good::where(['spuCode'=>$goodNo])->column('status','spuCode');
  77. if(empty($good_info))$this->error('商品开票类目信息不存在');
  78. if(in_array(0,$good_info)){
  79. $key = array_search(0,$good_info);
  80. $this->error("商品 $key 采购未确认开票类目");
  81. }
  82. if(in_array(1,$good_info)){
  83. $key = array_search(1,$good_info);
  84. $this->error("商品 $key 财务未确认开票类目");
  85. }
  86. $payNo= makeNo("PAY");
  87. $this->model->startTrans();
  88. try {
  89. $paydata=[
  90. 'payNo'=>$payNo,
  91. 'apply_id'=>$this->uid,
  92. 'apply_name'=>$this->uname,
  93. 'total_fee'=>"0",
  94. 'supplierNo'=>$supplierNo[0],
  95. 'supplierName'=>$supplierName,
  96. 'companyNo'=>$customerNo[0],
  97. 'companyName'=>$customerName,
  98. 'wpay_fee'=>"0",
  99. 'apay_fee'=>'0',
  100. 'ainv_fee'=>'0',
  101. 'winv_fee'=>'0',
  102. 'remark'=>'',
  103. 'is_comon'=>1,
  104. 'status'=>1,
  105. 'addtime'=>date('Y-m-d H:i:s'),
  106. 'updatetime'=>date('Y-m-d H:i:s'),
  107. ];
  108. foreach ($list as $item){
  109. if(!isset($item['cgd']) || empty($item['cgd'])) throw new Exception("采购单信息未找到");
  110. $value= $item['cgd'];
  111. $temp=[];
  112. $temp['cgdNo']=$value['sequenceNo'];
  113. $temp['total_fee']=$value['totalPrice'];
  114. $temp['apay_fee']=$value['apay_fee'];
  115. $temp['wpay_fee']=$value['wpay_fee'];
  116. $temp['winv_fee']=$value['winv_fee'];
  117. $temp['ainv_fee']=$value['ainv_fee'];
  118. $temp['payNo']=$payNo;
  119. $temp['addtime']=date('Y-m-d H:i:s');
  120. $temp['updatetime']=date('Y-m-d H:i:s');
  121. $data[]=$temp;
  122. $paydata['total_fee']= bcadd($paydata['total_fee'],$temp['total_fee'],2);
  123. $paydata['apay_fee']= bcadd($paydata['apay_fee'],$temp['apay_fee'],2);
  124. $paydata['wpay_fee']= bcadd($paydata['wpay_fee'],$temp['wpay_fee'],2);
  125. $paydata['ainv_fee']=bcadd($paydata['ainv_fee'],$temp['ainv_fee'],2);
  126. $paydata['winv_fee']= bcadd($paydata['winv_fee'],$temp['winv_fee'],2);
  127. }
  128. if(empty($data))throw new Exception('采购单对账信息不能为空');
  129. $save= (new \app\admin\model\PayInfo)->saveAll($data);
  130. if($save->count()==0)throw new Exception('采购单对账信息录入失败');
  131. $payIn =Pay::create($paydata);
  132. if($payIn->id>0){
  133. $this->model->where(['id'=>$param['common_ids']])->save(["status"=>1]);
  134. CgdInfo::where(["sequenceNo"=>array_column($list,"cgdNo")])->save(['status'=>1]);
  135. $report =ReportCode::where(['cgdNo'=>array_column($list,'cgdNo')])->select();
  136. if($report->isEmpty()==false)$report->update(['payNo'=>Db::raw("CONCAT(payNo,',','{$payNo}')")]);
  137. $this->model->commit();
  138. }else throw new Exception('采购单对账单创建失败');
  139. }catch (\Exception $exception){
  140. $this->model->rollback();
  141. $this->error($exception->getMessage());
  142. }
  143. $this->success("对账单创建成功");
  144. }
  145. //通用订单修改对账单
  146. public function PaySave(){
  147. $param=$this->request->only(['common_ids'=>[],"payNo"=>""],'post','trim');
  148. $valid=Validate::rule([
  149. 'common_ids|通用订单id集合'=>'require|array',
  150. 'payNo|通用订单对账单编号'=>'require',
  151. ]);
  152. if($valid->check($param)==false)$this->error($valid->getError());
  153. $obj = $this->model->with(['cgd'])->where(['id'=>$param['common_ids']])->select();
  154. if($obj->isEmpty())$this->error('未找到相关数据');
  155. $payinfo = Pay::where(['payNo'=>$param['payNo'],'is_del'=>0])->findOrEmpty();
  156. if($payinfo->isEmpty())$this->error('未找到对账单数据');
  157. if($payinfo->status!=1)$this->error('对账单数据已提交审核');
  158. $cgdNo =payInfo::where([['payNo','=',$param['payNo']],['is_del','=',0]])->column('cgdNo');
  159. $list = $obj->toArray();
  160. $cgdArr=array_column($list,'cgdNo');
  161. $status = array_unique(array_column($list,'status'));
  162. $supplierNo = array_unique(array_column($list,'supplierNo'));
  163. $customerNo = array_unique(array_column($list,'customerNo'));
  164. $goodNo = array_unique(array_column($list,'goodNo'));
  165. $supplierName = \app\admin\model\SupplierInfo::whereIn('code',$supplierNo)->value('name','');
  166. $customerName = \app\admin\model\CompanyInfo::whereIn('companyNo',$customerNo)->value('company_name','');
  167. if(count($supplierNo)>1)$this->error('提交数据采购供应商存在不一致');
  168. if(count($customerNo)>1)$this->error('提交数据销售客户存在不一致');
  169. $good_info = \app\admin\model\Good::where(['spuCode'=>$goodNo])->column('status','spuCode');
  170. if(empty($good_info))$this->error("商品开票类目信息不存在");
  171. if(in_array(0,$good_info)){
  172. $key = array_search(0,$good_info);
  173. $this->error("商品 $key 采购未确认开票类目");
  174. }
  175. if(in_array(1,$good_info)){
  176. $key = array_search(1,$good_info);
  177. $this->error("商品 $key 财务未确认开票类目");
  178. }
  179. $add=[];
  180. $remove=[];
  181. if(!empty($cgdNo)){
  182. $remove = array_diff($cgdNo,$cgdArr);
  183. $add = array_diff($cgdArr,$cgdNo);
  184. }
  185. $data=[];
  186. $this->model->startTrans();
  187. try {
  188. $paydata=[
  189. 'total_fee'=>'0',
  190. 'supplierNo'=>$supplierNo,
  191. 'supplierName'=>$supplierName,
  192. 'companyNo'=>$customerNo,
  193. 'companyName'=>$customerName,
  194. 'wpay_fee'=>'0',
  195. 'apay_fee'=>'0',
  196. 'ainv_fee'=>'0',
  197. 'winv_fee'=>'0',
  198. 'remark'=>'',
  199. 'is_comon'=>1,
  200. 'status'=>1,
  201. 'updatetime'=>date('Y-m-d H:i:s'),
  202. ];
  203. foreach ($list as $item){
  204. if(!isset($item['cgd']) || empty($item['cgd'])) throw new Exception('采购单信息未找到');
  205. $value= $item['cgd'];
  206. if(!empty($add)&& in_array($value['sequenceNo'],$add)){
  207. $temp=[];
  208. $temp['cgdNo']=$value['sequenceNo'];
  209. $temp['total_fee']=$value['totalPrice'];
  210. $temp['apay_fee']=$value['apay_fee'];
  211. $temp['wpay_fee']=$value['wpay_fee'];
  212. $temp['winv_fee']=$value['winv_fee'];
  213. $temp['ainv_fee']=$value['ainv_fee'];
  214. $temp['payNo']=$param['payNo'];
  215. $temp['addtime']=date('Y-m-d H:i:s');
  216. $temp['updatetime']=date('Y-m-d H:i:s');
  217. $data[]=$temp;
  218. }
  219. $paydata['total_fee']= bcadd($paydata['total_fee'],$temp['total_fee'],2);
  220. $paydata['apay_fee']= bcadd($paydata['apay_fee'],$temp['apay_fee'],2);
  221. $paydata['wpay_fee']= bcadd($paydata['wpay_fee'],$temp['wpay_fee'],2);
  222. $paydata['ainv_fee']=bcadd($paydata['ainv_fee'],$temp['ainv_fee'],2);
  223. $paydata['winv_fee']= bcadd($paydata['winv_fee'],$temp['winv_fee'],2);
  224. }
  225. if(!empty($data)){
  226. $save= (new \app\admin\model\PayInfo)->saveAll($data);
  227. if($save->count()==0)throw new Exception('采购单对账信息录入失败');
  228. }
  229. $payIn =Pay::where($payinfo)->save($paydata);
  230. if($payIn){
  231. $this->model->where(['id'=>$param['common_ids']])->save(['status'=>1]);
  232. $this->model->where(['cgdNo'=>$remove])->save(['status'=>0]);
  233. CgdInfo::where(['sequenceNo'=>$add])->save(['status'=>1]);
  234. CgdInfo::where(['sequenceNo'=>$remove])->save(['status'=>0]);
  235. $report =ReportCode::where(['cgdNo'=>$add])->select();
  236. if($report->isEmpty()==false)$report->update(['payNo'=>Db::raw("CONCAT(payNo,',','{$param['payNo']}')")]);
  237. $reports =ReportCode::where(['cgdNo'=>$remove])->select();
  238. if($reports->isEmpty()==false)$reports->update(['payNo'=>Db::raw("REPLACE(payNo,',{$param['payNo']}','')")]);
  239. $this->model->commit();
  240. }else throw new Exception('采购单对账单创建失败');
  241. }catch (\Exception $exception){
  242. $this->model->rollback();
  243. $this->error($exception->getMessage());
  244. }
  245. $this->success('对账单创建成功');
  246. }
  247. //通用对账单信息
  248. public function PayInfo()
  249. {
  250. $param=$this->request->only(['payNo'=>''],"post","trim");
  251. $valid=Validate::rule(['payNo|通用订单对账单编号'=>'require']);
  252. if($valid->check($param)==false)$this->error($valid->getError());
  253. $payinfo =Pay::where(['payNo'=>$param['payNo'],'is_del'=>0])->append(["cgdlist","qrdlist"])->findOrEmpty();
  254. if($payinfo->isEmpty())$this->error("对账单数据未找到");
  255. if($payinfo->is_comon==0)$this->error('非通用对账单数据无法访问数据');
  256. $pay = PayInfo::where(['payNo'=>$param['payNo'],'is_del'=>0])->select();
  257. if($pay->isEmpty())$this->error('对账单订单数据未找到');
  258. $cgdlist = [];
  259. $qrdlist = [];
  260. $list=$this->model->with(['qrd','cgd'])->where(['cgdNo'=>array_column($pay->toArray(),"cgdNo")])->select()
  261. ->toArray();
  262. $qrdArr= array_column($list,"qrd","cgdNo");
  263. $cgdArr= array_column($list,"cgd","cgdNo");
  264. array_walk($qrdArr,function (&$item){
  265. $item['catInfo'] = json_decode($item['catInfo'],true);
  266. $item['orderTax'] = OrderCategory::where(['code' => $item['sequenceNo'], 'spuCode' => $item['goodNo']])
  267. ->field(['cat_code', 'cat_name', 'merge_code', 'short_name', 'tax', 'inv_good_name'])->findOrEmpty();
  268. });
  269. array_walk($cgdArr,function (&$item){
  270. $item['catInfo'] = json_decode($item['catInfo'],true);
  271. $item['orderTax'] = OrderCategory::where(['code' => $item['sequenceNo'], 'spuCode' => $item['goodNo']])
  272. ->field(['cat_code', 'cat_name', 'merge_code', 'short_name', 'tax', 'inv_good_name'])->findOrEmpty();
  273. });
  274. foreach ($pay as $item){
  275. if(isset($qrdArr[$item['cgdNo']])==false)continue;
  276. $cgdlist[] =$cgdArr[$item['cgdNo']];
  277. $invArr = Db::name('assoc')
  278. ->alias('a')
  279. ->leftJoin('invoice_good b', 'a.viceCode=b.invNo AND b.orderCode =a.orderCode')
  280. ->where(['a.status' => [1, 2], 'a.is_del' => 0, 'a.type' => 1, 'a.orderCode' => $qrdArr[$item['cgdNo']]['sequenceNo']])->group
  281. ('a.status')->column('sum(b.goodNum) as goodNum', 'a.status');
  282. $qrdArr[$item['cgdNo']]['goodNum'] -= $qrdArr[$item['cgdNo']]['thNum'];
  283. $qrdArr[$item['cgdNo']]['inv_num'] = $invArr[1]??0;
  284. $qrdArr[$item['cgdNo']]['ainv_num'] = $invArr[2]??0;
  285. $qrdArr[$item['cgdNo']]['winv_num'] = $qrdArr[$item['cgdNo']]['goodNum']-$qrdArr[$item['cgdNo']]['inv_num']-$qrdArr[$item['cgdNo']]['ainv_num'];
  286. $qrdlist[] =$qrdArr[$item['cgdNo']];
  287. }
  288. $payinfo->cgdlist =$cgdlist;
  289. $payinfo->qrdlist =$qrdlist;
  290. $payinfo['pay_type']=SupplierInfo::where('code',$payinfo['supplierNo'])->value('pay_method','');
  291. $tag =TagLog::alias('a')->leftJoin('order_tag b','a.tag_id=b.id')->where
  292. (['code'=>$param['payNo'],'a.status'=>1])->column('b.tag_name,a.tag_img,a.tag_remark','b.type');
  293. $payinfo['inv_tag_name']=$tag[2]['tag_name']??'';
  294. $payinfo['pay_tag_name']=$tag[1]['tag_name']??'';
  295. $payinfo['pay_tag_img']=$tag[1]['tag_img']??'';
  296. $payinfo['pay_tag_remark']=$tag[1]['tag_remark']??'';
  297. $payinfo['inv_tag_img']=$tag[2]['tag_img']??'';
  298. $payinfo['inv_tag_remark']=$tag[2]['tag_remark']??'';
  299. $this->success('获取成功',$payinfo);
  300. }
  301. /**
  302. * 对账单开票申请
  303. */
  304. public function invAdd(){
  305. $param=$this->request->only(["payNo"=>"","orderArr"=>[],"invtype"=>"","email"=>"","remark"=>"",
  306. 'exam_remark'=>''],"post","trim");
  307. $valid =Validate::rule([
  308. "payNo|对账单编号"=>"require",
  309. "orderArr|订单数据"=>"require|array",
  310. "invtype|开票类型"=>["require","in"=>$this->invName],
  311. "email|邮箱"=>"email",
  312. ]);
  313. if($valid->check($param)==false) $this->error($valid->getError());
  314. $valide = Validate::rule([
  315. "sequenceNo|销售订单号"=>"require",
  316. "inv_fee|商品开票金额"=>"require|float|gt:0",
  317. ]);
  318. $qrdinfo = QrdInfo::whereIn('sequenceNo',array_column($param['orderArr'],"sequenceNo"))
  319. ->column("id,sequenceNo,customerNo,customerName,companyNo,companyName,goodNo,goodNum,goodPrice,thNum,inv_fee,winv_fee,
  320. status,goodUnit,goodName,thirdCat,totalPrice,tax,platform_type","sequenceNo");
  321. if(empty($qrdinfo))$this->error("订单信息不存在");
  322. $goodInfo= \app\admin\model\Good::whereIn("spuCode",array_unique(array_column($qrdinfo,"goodNo")))
  323. ->column("inv_good_name,inv_cat_name,inv_cat_code,inv_tax,is_discount,addTax,inv_tag,status","spuCode");
  324. if(empty($goodInfo))$this->error('商品类目信息不存在');
  325. $assoc=[];
  326. $invoiceGood=[];
  327. $invNo=makeNo('INV');
  328. $invfee=array_sum(array_column($param['orderArr'],'inv_fee'));
  329. $companyArr = array_unique(array_column($qrdinfo,'companyName','companyNo'));
  330. $customerArr = array_unique(array_column($qrdinfo,'customerName','customerNo'));
  331. if(count($companyArr)>1)$this->error("订单业务公司不一致");
  332. if(count($customerArr)>1)$this->error("订单客户公司不一致");
  333. $company = CompanyInfo::whereIn("companyNo",array_keys($companyArr))->findOrEmpty();
  334. if($company->isEmpty())$this->error('订单业务公司开票信息未找到');
  335. $customer = CompanyInfo::whereIn('companyNo',array_keys($customerArr))->findOrEmpty();
  336. if($customer->isEmpty())$this->error('订单客户公司开票信息未找到');
  337. if (in_array($param['invtype'] ,
  338. [
  339. 'fully_digitalized_special_electronic' ,
  340. 'fully_digitalized_normal_electronic'
  341. ]
  342. )) {
  343. //全电发票限制金额
  344. if ($invfee > 10000000) {
  345. $this->error('开票面额不能超过一千万元');
  346. }
  347. }
  348. else {//全电发票
  349. if ($company['denomination'] != '' && $invfee > intval($company['denomination']) * 10000) {
  350. $this->error( "开票面额不能超过{$company['denomination']}万元");
  351. }
  352. }
  353. $platform = array_column($qrdinfo,'platform_type');
  354. if(count(array_unique($platform))!=1){
  355. $this->error("订单平台类型不一致");
  356. }
  357. foreach ($param['orderArr'] as $i=>$item){
  358. if($valide->check($item)==false) $this->error($valide->getError());
  359. if(!isset($qrdinfo[$item['sequenceNo']]))$this->error("订单 {$item['sequenceNo']} 信息不存在");
  360. if($qrdinfo[$item['sequenceNo']]['status']==2)$this->error("订单 {$item['sequenceNo']} 不参与对账");
  361. if($qrdinfo[$item['sequenceNo']]['winv_fee']<$item['inv_fee'])$this->error("订单 {$item['sequenceNo']} 待开票金额不足");
  362. // $total = InvoicePool::alias("a")->leftJoin('invoice_good b', 'a.invNo=b.invNo and b.is_del=0')
  363. // ->where(['a.status' => [0, 1, 2, 3, 4], 'b.orderCode' => $item['sequenceNo']])
  364. // ->sum('b.goodNum');
  365. //if($total+$item['num']>($qrdinfo[$item['sequenceNo']]['goodNum']-$qrdinfo[$item['sequenceNo']]['thNum']))$this->error("订单 {$item['sequenceNo']} 待开票数量不足");
  366. if(!isset($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]))$this->error("订单 {$item['sequenceNo']} 商品类目信息不存在");
  367. if($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['status']!=2)$this->error("订单 {$item['sequenceNo']} 未确认开票类目信息");
  368. // $num = \app\admin\model\Assoc::alias('a')
  369. // ->leftJoin('invoice_good b', 'a.viceCode=b.invNo AND b.orderCode=a.orderCode')
  370. // ->where(['a.status' => [1, 2], 'a.is_del' => 0, 'a.type' => 1, 'a.orderCode' => $item['sequenceNo']])
  371. // ->sum('b.goodNum');
  372. //if($num+$item['num']>($qrdinfo[$item['sequenceNo']]['goodNum']-$qrdinfo[$item['sequenceNo']]['thNum']))$this->error("订单 {$item['sequenceNo']} 待开票数量不足");
  373. $assoc[]=[
  374. 'assocNo'=>substr(makeNo('AS'),0,-4).str_pad(strval($i+1),4,'0',STR_PAD_LEFT),
  375. 'apply_id'=>$this->uid,
  376. 'apply_name'=>$this->uname,
  377. 'type'=>1,
  378. 'orderCode'=>$item['sequenceNo'],
  379. 'customerNo'=>$qrdinfo[$item['sequenceNo']]['customerNo'],
  380. 'viceCode'=>$invNo,
  381. 'order_total'=>$qrdinfo[$item['sequenceNo']]['totalPrice'],
  382. 'vice_total'=>$invfee,
  383. 'cancel_fee'=>$item['inv_fee'],
  384. 'status'=>1,
  385. 'addtime'=>date('Y-m-d H:i:s'),
  386. 'updatetime'=>date('Y-m-d H:i:s')
  387. ];
  388. $invoiceGood[]=[
  389. 'invNo'=>$invNo,
  390. 'orderCode'=>$item['sequenceNo'],
  391. 'goodNo'=>$qrdinfo[$item['sequenceNo']]['goodNo'],
  392. 'goodName'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_good_name']??$qrdinfo[$item['sequenceNo']]['goodName'] ,
  393. 'catName'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_cat_name']??$qrdinfo[$item['sequenceNo']]['thirdCat'],
  394. 'catNo'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_cat_code'],
  395. 'goodPrice'=>$qrdinfo[$item['sequenceNo']]['goodPrice'],
  396. 'unitName'=>$qrdinfo[$item['sequenceNo']]['goodUnit'],
  397. 'goodNum'=>bcdiv($item['inv_fee'],$qrdinfo[$item['sequenceNo']]['goodPrice'],8),
  398. 'specInfo'=>$item['sequenceNo'],
  399. 'totalPrice'=>$item['inv_fee'],
  400. 'totalTax'=>$item['inv_fee'],
  401. 'tax'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tax']??$qrdinfo[$item['sequenceNo']]['tax'],
  402. 'is_discount'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['is_discount'],
  403. 'addTax'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['addTax'],
  404. 'inv_tag'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tag'],
  405. 'taxPrice'=>round($item['inv_fee']*($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tax']??$qrdinfo[$item['sequenceNo']]['tax']),2),
  406. 'addtime'=>date('Y-m-d H:i:s'),
  407. 'updatetime'=>date('Y-m-d H:i:s')
  408. ];
  409. $qrdinfo[$item['sequenceNo']]["inv_fee"] = $qrdinfo[$item['sequenceNo']]['inv_fee']+$item['inv_fee'];
  410. $qrdinfo[$item['sequenceNo']]["winv_fee"] = $qrdinfo[$item['sequenceNo']]['winv_fee']-$item['inv_fee'];
  411. $qrdinfo[$item['sequenceNo']]["inv_status"] = 2;
  412. $qrdinfo[$item['sequenceNo']]["status"] = 1;
  413. }
  414. $inv=[
  415. 'invNo'=>$invNo,
  416. 'inv_value'=>$invfee,
  417. 'inv_out'=> array_keys($companyArr)[0],
  418. 'inv_company'=> $company['invoice_title']??'',
  419. 'apply_id'=>$this->uid,
  420. 'is_comon'=>1,
  421. 'apply_name'=>$this->uname,
  422. 'inv_type'=>$param['invtype'],//发票类型 专用 普通 电子专用 电子普通 全电子票
  423. 'open_type'=>0, //开票类型 金税开票 金税线下 纯线下
  424. 'platform_type'=>$platform[0]??0, //开票类型 金税开票 金税线下 纯线下
  425. 'is_ticket'=>$company['out_ticket'], //是否支持金税开票
  426. 'company_type'=> $customer['company_type']??'01', //类型01 企业,02 机关事业单位,03 个人, 04 其他
  427. 'remark'=>$param['remark'], //申请备注
  428. 'exam_remark'=>$param['exam_remark'], //审核备注
  429. 'ainv_fee'=>0,//已核销金额
  430. 'winv_fee'=>$invfee,//未核销金额
  431. 'status'=>1,// 带财务审核
  432. 'is_del'=>0,
  433. 'email'=>$param['email'],
  434. 'addtime'=>date('Y-m-d H:i:s'),
  435. 'updatetime'=>date('Y-m-d H:i:s')
  436. ];
  437. $invinfo=[
  438. 'buyer_title'=>$customer['invoice_title'],
  439. 'buyer_code'=>$customer['company_license'],
  440. 'buyer_addr'=>$customer['company_address'],
  441. 'buyer_mobile'=>$customer['mobile'],
  442. 'buyer_bank'=>$customer['bank_name'],
  443. 'buyer_bankNo'=>$customer['bankNo'],
  444. 'seller_title'=>$company['invoice_title'],
  445. 'seller_code'=>$company['company_license'],
  446. 'seller_addr'=>$company['company_address'],
  447. 'seller_mobile'=>$company['mobile'],
  448. 'seller_bank'=>$company['bank_name'],
  449. 'seller_bankNo'=>$company['bankNo'],
  450. 'invNo'=>$invNo,
  451. 'voider'=>$company['voider'],
  452. 'payee'=>$company['payee'],
  453. 'drawer'=>$company['drawer'],
  454. 'reviewer'=>$company['reviewer'],
  455. 'ownerPlace'=>$company['ownerPlace'],
  456. 'addtime'=>date('Y-m-d H:i:s')
  457. ];
  458. $this->model->startTrans();
  459. try{
  460. $assocSa=(new \app\admin\model\Assoc)->saveAll($assoc);
  461. if($assocSa->isEmpty()) throw new Exception("开票关联数据生成失败");
  462. $goodInv = (new \app\admin\model\InvoiceGood)->saveAll($invoiceGood);
  463. if($goodInv->isEmpty()) throw new Exception('开票商品明细数据生成失败');
  464. $qrdSave = (new \app\admin\model\QrdInfo)->saveAll($qrdinfo);
  465. if($qrdSave->isEmpty()) throw new Exception('销售单信息更新失败');
  466. $invoice = InvoicePool::create($inv);
  467. if($invoice->isEmpty()) throw new Exception('开票信息创建失败');
  468. $invoiceinf = InvoicePoolInfo::create($invinfo);
  469. if($invoiceinf->isEmpty()) throw new Exception('开票信息创建失败');
  470. $payIn = InvoicePay::create(["invNo"=>$invNo,"payNo"=>$param["payNo"]]);
  471. if($payIn->isEmpty()) throw new Exception('开票信息创建失败');
  472. $report =ReportCode::where(['qrdNo'=>array_column($param['orderArr'],'sequenceNo')])->select();
  473. if($report->isEmpty()==false)$report->update(["invNo"=>Db::raw("CONCAT(invNo,',','{$invNo}')")]);
  474. $this->model->commit();
  475. }catch (\Exception $exception){
  476. $this->model->rollback();
  477. $this->error($exception->getMessage());
  478. }
  479. $this->success("开票申请创建成功");
  480. }
  481. /**
  482. * 对账单开票申请
  483. */
  484. public function invAddT(){
  485. $param=$this->request->only(['payNo'=>'','orderArr'=>[],'invtype'=>'','email'=>'','remark'=>'',
  486. 'exam_remark'=>''],'post','trim');
  487. $valid =Validate::rule([
  488. 'payNo|对账单编号'=>'require',
  489. 'orderArr|订单数据'=>'require|array',
  490. 'invtype|开票类型'=>['require','in'=>$this->invName],
  491. 'email|邮箱'=>'email',
  492. ]);
  493. if($valid->check($param)==false) $this->error($valid->getError());
  494. $valide = Validate::rule([
  495. 'sequenceNo|销售订单号'=>'require',
  496. 'num|商品开票数量'=>'require|float|gt:0',
  497. 'inv_fee|商品开票金额'=>'require|float|gt:0',
  498. ]);
  499. $qrdinfo = QrdInfo::whereIn('sequenceNo',array_column($param['orderArr'],'sequenceNo'))
  500. ->column('id,sequenceNo,customerNo,customerName,companyNo,companyName,goodNo,goodNum,thNum,inv_fee,winv_fee,
  501. status,goodUnit,goodName,thirdCat,totalPrice,tax,platform_type','sequenceNo');
  502. if(empty($qrdinfo))$this->error('订单信息不存在');
  503. $goodInfo= \app\admin\model\Good::whereIn('spuCode',array_unique(array_column($qrdinfo,'goodNo')))
  504. ->column('inv_good_name,inv_cat_name,inv_cat_code,inv_tax,is_discount,addTax,inv_tag,status','spuCode');
  505. if(empty($goodInfo))$this->error('商品类目信息不存在');
  506. $assoc=[];
  507. $invoiceGood=[];
  508. $invNo=makeNo('INV');
  509. $invfee=array_sum(array_column($param['orderArr'],'inv_fee'));
  510. $companyArr = array_unique(array_column($qrdinfo,'companyName','companyNo'));
  511. $customerArr = array_unique(array_column($qrdinfo,'customerName','customerNo'));
  512. if(count($companyArr)>1)$this->error('订单业务公司不一致');
  513. if(count($customerArr)>1)$this->error('订单客户公司不一致');
  514. $company = CompanyInfo::whereIn('companyNo',array_keys($companyArr))->findOrEmpty();
  515. if($company->isEmpty())$this->error('订单业务公司开票信息未找到');
  516. $customer = CompanyInfo::whereIn('companyNo',array_keys($customerArr))->findOrEmpty();
  517. if($customer->isEmpty())$this->error('订单客户公司开票信息未找到');
  518. if (in_array($param['invtype'] ,
  519. [
  520. 'fully_digitalized_special_electronic' ,
  521. 'fully_digitalized_normal_electronic'
  522. ]
  523. )) {
  524. //全电发票限制金额
  525. if ($invfee > 10000000) {
  526. $this->error('开票面额不能超过一千万元');
  527. }
  528. }
  529. else {//全电发票
  530. if ($company['denomination'] != '' && $invfee > intval($company['denomination']) * 10000) {
  531. $this->error( "开票面额不能超过{$company['denomination']}万元");
  532. }
  533. }
  534. $platform = array_column($qrdinfo,'platform_type');
  535. if(count(array_unique($platform))!=1){
  536. $this->error('订单平台类型不一致');
  537. }
  538. foreach ($param['orderArr'] as $i=>$item){
  539. if($valide->check($item)==false) $this->error($valide->getError());
  540. if(!isset($qrdinfo[$item['sequenceNo']]))$this->error("订单 {$item['sequenceNo']} 信息不存在");
  541. if($qrdinfo[$item['sequenceNo']]['status']==2)$this->error("订单 {$item['sequenceNo']} 不参与对账");
  542. if($qrdinfo[$item['sequenceNo']]['winv_fee']<$item['inv_fee'])$this->error("订单 {$item['sequenceNo']} 待开票金额不足");
  543. $total = InvoicePool::alias('a')->leftJoin('invoice_good b', 'a.invNo=b.invNo and b.is_del=0')
  544. ->where(['a.status' => [0, 1, 2, 3, 4], 'b.orderCode' => $item['sequenceNo']])
  545. ->sum('b.goodNum');
  546. if($total+$item['num']>($qrdinfo[$item['sequenceNo']]['goodNum']-$qrdinfo[$item['sequenceNo']]['thNum']))$this->error("订单 {$item['sequenceNo']} 待开票数量不足");
  547. if(!isset($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]))$this->error("订单 {$item['sequenceNo']} 商品类目信息不存在");
  548. if($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['status']!=2)$this->error("订单 {$item['sequenceNo']} 未确认开票类目信息");
  549. $num = \app\admin\model\Assoc::alias('a')
  550. ->leftJoin('invoice_good b', 'a.viceCode=b.invNo AND b.orderCode=a.orderCode')
  551. ->where(['a.status' => [1, 2], 'a.is_del' => 0, 'a.type' => 1, 'a.orderCode' => $item['sequenceNo']])
  552. ->sum('b.goodNum');
  553. if($num+$item['num']>($qrdinfo[$item['sequenceNo']]['goodNum']-$qrdinfo[$item['sequenceNo']]['thNum']))$this->error("订单 {$item['sequenceNo']} 待开票数量不足");
  554. $assoc[]=[
  555. 'assocNo'=>substr(makeNo('AS'),0,-4).str_pad(strval($i+1),4,'0',STR_PAD_LEFT),
  556. 'apply_id'=>$this->uid,
  557. 'apply_name'=>$this->uname,
  558. 'type'=>1,
  559. 'orderCode'=>$item['sequenceNo'],
  560. 'customerNo'=>$qrdinfo[$item['sequenceNo']]['customerNo'],
  561. 'viceCode'=>$invNo,
  562. 'order_total'=>$qrdinfo[$item['sequenceNo']]['totalPrice'],
  563. 'vice_total'=>$invfee,
  564. 'cancel_fee'=>$item['inv_fee'],
  565. 'status'=>1,
  566. 'addtime'=>date('Y-m-d H:i:s'),
  567. 'updatetime'=>date('Y-m-d H:i:s')
  568. ];
  569. $invoiceGood[]=[
  570. 'invNo'=>$invNo,
  571. 'orderCode'=>$item['sequenceNo'],
  572. 'goodNo'=>$qrdinfo[$item['sequenceNo']]['goodNo'],
  573. 'goodName'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_good_name']??$qrdinfo[$item['sequenceNo']]['goodName'] ,
  574. 'catName'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_cat_name']??$qrdinfo[$item['sequenceNo']]['thirdCat'],
  575. 'catNo'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_cat_code'],
  576. 'goodPrice'=>round($item['inv_fee']/$item['num'],8),
  577. 'unitName'=>$qrdinfo[$item['sequenceNo']]['goodUnit'],
  578. 'goodNum'=>$item['num'],
  579. 'specInfo'=>$item['sequenceNo'],
  580. 'totalPrice'=>$item['inv_fee'],
  581. 'totalTax'=>$item['inv_fee'],
  582. 'tax'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tax']??$qrdinfo[$item['sequenceNo']]['tax'],
  583. 'is_discount'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['is_discount'],
  584. 'addTax'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['addTax'],
  585. 'inv_tag'=>$goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tag'],
  586. 'taxPrice'=>round($item['inv_fee']*($goodInfo[$qrdinfo[$item['sequenceNo']]['goodNo']]['inv_tax']??$qrdinfo[$item['sequenceNo']]['tax']),2),
  587. 'addtime'=>date('Y-m-d H:i:s'),
  588. 'updatetime'=>date('Y-m-d H:i:s')
  589. ];
  590. $qrdinfo[$item['sequenceNo']]['inv_fee'] = $qrdinfo[$item['sequenceNo']]['inv_fee']+$item['inv_fee'];
  591. $qrdinfo[$item['sequenceNo']]['winv_fee'] = $qrdinfo[$item['sequenceNo']]['winv_fee']-$item['inv_fee'];
  592. $qrdinfo[$item['sequenceNo']]['inv_status'] = 2;
  593. $qrdinfo[$item['sequenceNo']]['status'] = 1;
  594. }
  595. $inv=[
  596. 'invNo'=>$invNo,
  597. 'inv_value'=>$invfee,
  598. 'inv_out'=> array_keys($companyArr)[0],
  599. 'inv_company'=> $company['invoice_title']??'',
  600. 'apply_id'=>$this->uid,
  601. 'is_comon'=>1,
  602. 'apply_name'=>$this->uname,
  603. 'inv_type'=>$param['invtype'],//发票类型 专用 普通 电子专用 电子普通 全电子票
  604. 'open_type'=>0, //开票类型 金税开票 金税线下 纯线下
  605. 'platform_type'=>$platform[0]??0, //开票类型 金税开票 金税线下 纯线下
  606. 'is_ticket'=>$company['out_ticket'], //是否支持金税开票
  607. 'company_type'=> $customer['company_type']??'01', //类型01 企业,02 机关事业单位,03 个人, 04 其他
  608. 'remark'=>$param['remark'], //申请备注
  609. 'exam_remark'=>$param['exam_remark'], //审核备注
  610. 'ainv_fee'=>0,//已核销金额
  611. 'winv_fee'=>$invfee,//未核销金额
  612. 'status'=>1,// 带财务审核
  613. 'is_del'=>0,
  614. 'email'=>$param['email'],
  615. 'addtime'=>date('Y-m-d H:i:s'),
  616. 'updatetime'=>date('Y-m-d H:i:s')
  617. ];
  618. $invinfo=[
  619. 'buyer_title'=>$customer['invoice_title'],
  620. 'buyer_code'=>$customer['company_license'],
  621. 'buyer_addr'=>$customer['company_address'],
  622. 'buyer_mobile'=>$customer['mobile'],
  623. 'buyer_bank'=>$customer['bank_name'],
  624. 'buyer_bankNo'=>$customer['bankNo'],
  625. 'seller_title'=>$company['invoice_title'],
  626. 'seller_code'=>$company['company_license'],
  627. 'seller_addr'=>$company['company_address'],
  628. 'seller_mobile'=>$company['mobile'],
  629. 'seller_bank'=>$company['bank_name'],
  630. 'seller_bankNo'=>$company['bankNo'],
  631. 'invNo'=>$invNo,
  632. 'voider'=>$company['voider'],
  633. 'payee'=>$company['payee'],
  634. 'drawer'=>$company['drawer'],
  635. 'reviewer'=>$company['reviewer'],
  636. 'ownerPlace'=>$company['ownerPlace'],
  637. 'addtime'=>date('Y-m-d H:i:s')
  638. ];
  639. $this->model->startTrans();
  640. try{
  641. $assocSa=(new \app\admin\model\Assoc)->saveAll($assoc);
  642. if($assocSa->isEmpty()) throw new Exception('开票关联数据生成失败');
  643. $goodInv = (new \app\admin\model\InvoiceGood)->saveAll($invoiceGood);
  644. if($goodInv->isEmpty()) throw new Exception('开票商品明细数据生成失败');
  645. $qrdSave = (new \app\admin\model\QrdInfo)->saveAll($qrdinfo);
  646. if($qrdSave->isEmpty()) throw new Exception('销售单信息更新失败');
  647. $invoice = InvoicePool::create($inv);
  648. if($invoice->isEmpty()) throw new Exception('开票信息创建失败');
  649. $invoiceinf = InvoicePoolInfo::create($invinfo);
  650. if($invoiceinf->isEmpty()) throw new Exception('开票信息创建失败');
  651. $payIn = InvoicePay::create(['invNo'=>$invNo,'payNo'=>$param['payNo']]);
  652. if($payIn->isEmpty()) throw new Exception('开票信息创建失败');
  653. $report =ReportCode::where(['qrdNo'=>array_column($param['orderArr'],'sequenceNo')])->select();
  654. if($report->isEmpty()==false)$report->update(['invNo'=>Db::raw("CONCAT(invNo,',','{$invNo}')")]);
  655. $this->model->commit();
  656. }catch (\Exception $exception){
  657. $this->model->rollback();
  658. $this->error($exception->getMessage());
  659. }
  660. $this->success('开票申请创建成功');
  661. }
  662. }