PackagesController.php 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\service\coupon\CouponService;
  4. use app\admin\service\member\MemberService;
  5. use app\admin\service\order\OrderService;
  6. use app\admin\service\order\PayDetailService;
  7. use app\admin\validate\order\OrderValidate;
  8. use app\controller\Curd;
  9. use app\model\Appointment;
  10. use app\model\ClientConfig;
  11. use app\model\Coupon;
  12. use app\model\CouponDetail;
  13. use app\model\Goods;
  14. use app\model\GoodsComponent;
  15. use app\model\GoodsRunning;
  16. use app\model\GoodsSku;
  17. use app\model\Member;
  18. use app\model\MemberAccount;
  19. use app\model\MemberBenefit;
  20. use app\model\MemberRole;
  21. use app\model\Order;
  22. use app\model\OrderExpress;
  23. use app\model\OrderReturn;
  24. use app\model\OrderSheet;
  25. use app\model\PayDetail;
  26. use app\model\Supplier;
  27. use app\model\SysDept;
  28. use app\model\SysUser;
  29. use support\Db;
  30. use support\exception\BusinessException;
  31. use support\Redis;
  32. use support\Request;
  33. use support\Response;
  34. use Webman\Event\Event;
  35. class PackagesController extends Curd
  36. {
  37. public function __construct()
  38. {
  39. $this->model = new Order();
  40. $this->validate = true;
  41. $this->validateClass = new OrderValidate();
  42. }
  43. /**
  44. * @Desc 列表
  45. * @Author Gorden
  46. * @Date 2024/3/28 15:01
  47. *
  48. * @param Request $request
  49. * @return Response
  50. * @throws \support\exception\BusinessException
  51. */
  52. public function select(Request $request): Response
  53. {
  54. $timeType = $request->get('time_type', 'add');
  55. [$where, $format, $limit, $field, $order] = $this->selectInput($request);
  56. $where['order_classify'] = 'PACKAGE';
  57. if (!empty($where['order_addtimes']) && $timeType == 'add') {
  58. $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
  59. $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
  60. }
  61. $order = $request->get('order', 'desc');
  62. $field = $field ?? 'order_addtimes';
  63. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  64. $where['order_is_complete'] = 'N';
  65. }
  66. $orderId = trim($request->get('order_id', ''));
  67. $orderIds = [];
  68. if (!empty($orderId)) {
  69. $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
  70. ->where('order_classify', 'PACKAGE')
  71. ->pluck('order_id')
  72. ->toArray();
  73. }
  74. $goodsName = trim($request->get('goods_name', ''));
  75. if (!empty($goodsName)) {
  76. $goodsIds = Goods::where('goods_classify', 'PACKAGE')
  77. ->where('goods_name', 'like', '%' . $goodsName . '%')
  78. ->pluck('goods_id')
  79. ->toArray();
  80. $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
  81. if (!empty($where['order_id'])) {
  82. $orderIds = array_intersect($orderIds, $goodsOrderIds);
  83. } else {
  84. $orderIds = $goodsOrderIds;
  85. }
  86. }
  87. // 付款时间
  88. if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
  89. $payTimeStart = strtotime($where['order_addtimes'][0]);
  90. $payTimeEnd = strtotime($where['order_addtimes'][1]);
  91. unset($where['order_addtimes']);
  92. $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd);
  93. }
  94. if (!empty($orderIds) && !empty($payOrderIds)) {
  95. $orderIds = array_intersect($orderIds, $payOrderIds);
  96. $where['order_id'] = ['in', implode(',', $orderIds)];
  97. } elseif (!empty($orderIds)) {
  98. $where['order_id'] = ['in', implode(',', $orderIds)];
  99. } elseif (!empty($payOrderIds)) {
  100. $where['order_id'] = ['in', implode(',', $payOrderIds)];
  101. }
  102. if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
  103. if ($where['order_status_system'] == 'SENDING') {
  104. $where['order_express.order_express_type'] = '配送';
  105. }
  106. $where['order_is_complete'] = 'N';
  107. // $where['order_category'] = isset($where['order_category']) ? $where['order_category'] : ['in', 'SYSTEM,NORMAL,DISHES'];
  108. }
  109. // 自提订单
  110. if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') {
  111. $where['order_is_complete'] = 'N';
  112. $where['order_status_system'] = 'SENDING';
  113. $where['order_express.order_express_type'] = '自提';
  114. }
  115. $query = $this->doSelect($where, $field, $order);
  116. return $this->doFormat($query, $format, $limit);
  117. }
  118. protected function doSelect(array $where, string $field = null, string $order = 'desc')
  119. {
  120. $model = $this->model->with([
  121. 'sheets' => function ($query) {
  122. $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
  123. },
  124. 'member' => function ($query) {
  125. $query->select('member_id', 'member_mobile');
  126. },
  127. 'cert' => function ($query) {
  128. $query->select('join_cert_member_id', 'member_cert_name');
  129. },
  130. // 'return' => function ($query) use ($where){
  131. // if (isset($where['return'])){
  132. // dump($where['return']);
  133. // $query = $query->where('order_return_status',$where['return']);
  134. // }
  135. // $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');
  136. // },
  137. 'express' => function ($query) {
  138. $query->select('join_express_order_id', 'order_express_type');
  139. }
  140. ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
  141. ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
  142. // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
  143. if (isset($where['order_status_system']) && $where['order_status_system'] == 'DONE') {
  144. $model = $model->where(function ($query) {
  145. $query->where('order_status_system', 'DONE')
  146. ->orWhere(function ($query2) {
  147. $query2->where('order_status_system', 'CONFIRM')->where('order_is_complete', 'Y');
  148. });
  149. });
  150. unset($where['order_status_system']);
  151. }
  152. foreach ($where as $column => $value) {
  153. if (is_array($value)) {
  154. if ($value[0] === 'like' || $value[0] === 'not like') {
  155. $model = $model->where($column, $value[0], "%$value[1]%");
  156. } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
  157. $model = $model->where($column, $value[0], $value[1]);
  158. } elseif ($value[0] == 'in' && !empty($value[1])) {
  159. $valArr = $value[1];
  160. if (is_string($value[1])) {
  161. $valArr = explode(",", trim($value[1]));
  162. }
  163. $model = $model->whereIn($column, $valArr);
  164. } elseif ($value[0] == 'not in' && !empty($value[1])) {
  165. $valArr = $value[1];
  166. if (is_string($value[1])) {
  167. $valArr = explode(",", trim($value[1]));
  168. }
  169. $model = $model->whereNotIn($column, $valArr);
  170. } elseif ($value[0] == 'null') {
  171. $model = $model->whereNull($column);
  172. } elseif ($value[0] == 'not null') {
  173. $model = $model->whereNotNull($column);
  174. } elseif ($value[0] !== '' || $value[1] !== '') {
  175. $model = $model->whereBetween($column, $value);
  176. }
  177. } else {
  178. $model = $model->where($column, $value);
  179. }
  180. }
  181. if ($field) {
  182. $model = $model->orderBy($field, $order);
  183. }
  184. $model = $model->select('order.*', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_refund_json', 'order_return.order_return_remark');
  185. return $model;
  186. }
  187. public function afterQuery($items)
  188. {
  189. foreach ($items as &$item) {
  190. $sheetDeng = '';
  191. $item['sheet'] = $item['sheets'][0] ?? [];
  192. if (!empty($item['sheet'])) {
  193. $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
  194. if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
  195. $sheetDeng = ' 等餐品';
  196. }
  197. $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
  198. $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
  199. $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
  200. }
  201. unset($item['sheets']);
  202. $item['order_return_amount'] = 0;
  203. if (isset($item['orders_return_id'])) {
  204. $item['return'] = [
  205. 'orders_return_id' => $item['orders_return_id'],
  206. 'join_return_order_id' => $item['join_return_order_id'],
  207. 'order_return_status' => $item['order_return_status'],
  208. 'order_return_apply_json' => $item['order_return_apply_json'],
  209. 'order_return_remark' => $item['order_return_remark']
  210. ];
  211. if (!empty($item['order_return_refund_json'])) {
  212. $refundJson = json_decode($item['order_return_refund_json'], true);
  213. if (isset($refundJson['amount'])) {
  214. $item['order_return_amount'] = $refundJson['amount'];
  215. }
  216. }
  217. }
  218. $item['have_success_paydetail'] = 'N';
  219. if (PayDetail::where('join_pay_order_id', $item['order_groupby'])
  220. ->whereJsonContains('join_pay_object_json->order_id', $item['order_id'])
  221. ->where('pay_status', 'SUCCESS')
  222. ->exists()) {
  223. $item['have_success_paydetail'] = 'Y';
  224. }
  225. $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'],$item['order_id']);
  226. }
  227. return $items;
  228. }
  229. /**
  230. * @Desc 核销套包订单
  231. * @Author Gorden
  232. * @Date 2024/9/10 9:06
  233. *
  234. * @param Request $request
  235. * @return Response
  236. */
  237. public function writeOff(Request $request)
  238. {
  239. $memberId = $request->post('member_id', '');
  240. $benefitId = $request->post('benefit_id', '');
  241. $nbr = $request->post('nbr');
  242. $times = $request->post('times', '');
  243. $code = $request->post('sms_code', '');
  244. if (!$memberId || !$benefitId) {
  245. return json_fail('参数异常');
  246. }
  247. $member = Member::find($memberId);
  248. $mobile = $member->member_mobile;
  249. $key = "SMS:CODE:QUOTA:" . $mobile;
  250. $redisCode = Redis::get($key);
  251. if ($redisCode != $code && $code != '13579') {
  252. return json_fail("验证码错误,请重新输入");
  253. }
  254. Redis::del($key);
  255. $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
  256. ->where('join_benefit_member_id', $memberId)
  257. ->first();
  258. if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
  259. return json_fail('可核销数量不足');
  260. }
  261. if (!$times) {
  262. $times = date('Y-m-d H:i:s');
  263. } else {
  264. $times = date('Y-m-d H:i:s', strtotime($times));
  265. }
  266. Db::beginTransaction();
  267. try {
  268. // 减额度 加使用量
  269. $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
  270. // 此权益用完了
  271. if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) {
  272. // 套包和套包里的产品是否用完了
  273. $result = OrderService::checkPackageBenefit($benefit);
  274. $benefit->member_benefit_status = 'DONE';
  275. if (!empty($benefit->join_benefit_order_id) && $result['order'] === true) {
  276. Order::where('order_id', $benefit->join_benefit_order_id)->update([
  277. 'order_is_complete' => 'Y',
  278. 'order_status_system' => 'DONE'
  279. ]);
  280. }
  281. // sheet
  282. if (!empty($benefit->join_benefit_order_id) && $result['sheet'] === true) {
  283. $sheet = OrderSheet::where('join_sheet_goods_id', $benefit->join_benefit_package_id)
  284. ->where('join_sheet_order_id', $benefit->join_benefit_order_id)
  285. ->first();
  286. $sheet->order_sheet_used_num = $sheet->order_sheet_num;
  287. $sheet->save();
  288. }
  289. }
  290. $benefit->save();
  291. // 记录核销
  292. $params = [
  293. 'dept_premises_id' => $request->post('dept_premises_id'),
  294. 'order_remark' => $request->post('remark'),
  295. 'write_off_member_id' => $request->post('write_off_member_id'),
  296. 'join_order_member_id' => $memberId
  297. ];
  298. $writeOffData = OrderService::generateWriteOffData($params);
  299. $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
  300. ->where('appointment_status', 'INIT')
  301. ->limit($nbr)
  302. ->get();
  303. $appointmentIds = [];
  304. foreach ($appointments as $appointment) {
  305. $appointmentIds[] = $appointment->appointment_id;
  306. Appointment::where('appointment_id', $appointment->appointment_id)->update([
  307. 'appointment_status' => 'DONE',
  308. 'appointment_datetime' => $times,
  309. 'appointment_apply_datetime' => $times,
  310. 'appointment_doing_datetime' => $times,
  311. 'appointment_done_datetime' => $times,
  312. 'appointment_done_json' => json_encode($writeOffData)
  313. ]);
  314. }
  315. // 核销服务回写process
  316. if (!empty($benefit->join_benefit_goods_id) && !empty($benefit->join_benefit_order_id)) {
  317. $dept = [];
  318. if (!empty($params['dept_premises_id'])) {
  319. $dept = SysDept::where('dept_id', $params['dept_premises_id'])
  320. ->orWhere('dept_name', $params['dept_premises_id'])
  321. ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
  322. ->first();
  323. }
  324. $params['charge_amount'] = $nbr;
  325. $params['goods_id'] = $benefit->join_benefit_goods_id;
  326. $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
  327. $params['order_id'] = $benefit->join_benefit_order_id;
  328. $params['appointment_ids'] = $appointmentIds;
  329. $params['dept'] = $dept;
  330. $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
  331. // 触发事件
  332. Event::dispatch('order.write_off', $params);
  333. }
  334. Db::commit();
  335. _syslog("订单", "核销成功");
  336. return json_success('核销成功');
  337. } catch (\Exception $e) {
  338. dump($e->getMessage());
  339. Db::rollBack();
  340. _syslog("订单", "核销失败");
  341. return json_fail('核销失败');
  342. }
  343. }
  344. /**
  345. * @Desc 下单+支付
  346. * @Author Gorden
  347. * @Date 2024/9/23 16:15
  348. *
  349. * @param Request $request
  350. * @return Response
  351. */
  352. public function insert(Request $request): Response
  353. {
  354. $params = $request->post();
  355. // 判断餐品是否连带着服务或实体
  356. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  357. $premises = [];
  358. if (!empty($params['dept_premises_id'])) {
  359. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  360. }
  361. if (in_array('PACKAGE', $goodsClassifys)) {
  362. $params['submit_goods_classify'] = 'PACKAGE';
  363. }
  364. $params['goods_classify'] = $goodsClassifys[0];
  365. Db::beginTransaction();
  366. try {
  367. // 使用优惠券
  368. $couponUseJson = [];
  369. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  370. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  371. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  372. throw new BusinessException("计算优惠后,实付金额错误!");
  373. }
  374. // 组装优惠券使用数据,存主表优惠里
  375. if (!empty($couponResult['use_coupon_json'])) {
  376. $couponUseJson = $couponResult['use_coupon_json'];
  377. }
  378. }
  379. // 存储优惠信息
  380. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  381. // 验证库存
  382. foreach ($params['goodsContentList'] as $goods) {
  383. // 减库存,规格和总库存
  384. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  385. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  386. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  387. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  388. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  389. }
  390. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  391. throw new BusinessException('库存不足');
  392. }
  393. }
  394. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  395. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  396. if ($goodsRunning->goods_running_storage < 0) {
  397. throw new BusinessException('库存不足');
  398. }
  399. }
  400. // 余额、福利、储值卡 验证短信
  401. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE', 'VIP'])) {
  402. $code = $params['sms_code'];
  403. if (!$code) {
  404. throw new BusinessException('验证码错误,请重新输入');
  405. }
  406. $member = Member::find($params['join_order_member_id']);
  407. $mobile = $member->member_mobile;
  408. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  409. $redisCode = Redis::get($key);
  410. if ($redisCode != $code && $code != '123456') {
  411. throw new BusinessException('验证码错误,请重新输入');
  412. }
  413. Redis::del($key);
  414. }
  415. // 验证线下付款密码
  416. if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  417. $password = $params['offline_password'];
  418. if ($password != '666888') {
  419. throw new BusinessException('密码错误,请重新输入');
  420. }
  421. }
  422. // 下单账户
  423. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  424. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  425. throw new BusinessException('会员已存在');
  426. }
  427. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  428. // 创建会员
  429. MemberService::createMember($params);
  430. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  431. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  432. }
  433. if (empty($params['join_order_member_id'])) {
  434. throw new BusinessException('检查下单账户');
  435. }
  436. $qrcodePayAmount = 0;
  437. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  438. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  439. $systemStatus = 'SENDING'; // 待发货
  440. // 立即结算
  441. if ($params['settlement_now'] == 'Y') {
  442. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  443. $params['order_is_complete'] = 'Y';
  444. $systemStatus = 'DONE';
  445. }
  446. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  447. $params['order_is_complete'] = 'N';
  448. $systemStatus = "WAITING";
  449. }
  450. }
  451. if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
  452. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  453. $params['pay_category'] = $params['pay_category_sub'];
  454. }
  455. $params['order_status_system'] = $systemStatus;
  456. $params['order_status_payment'] = 'SUCCESS';
  457. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付
  458. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  459. ->where('member_account_classify', 'CASH')
  460. ->where('member_account_status', 'ACTIVED')
  461. ->first();
  462. if (!$account) {
  463. throw new BusinessException('账户异常');
  464. }
  465. $amount = $account->member_account_surplus + $account->member_account_added;
  466. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  467. throw new BusinessException('账户余额不足');
  468. }
  469. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  470. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  471. $account->member_account_surplus = 0;
  472. $account->member_account_added = $cut;
  473. } else {
  474. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  475. }
  476. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  477. $account->save();
  478. if ($params['pay_constitute'] == 'N') {
  479. $params['order_status_system'] = $systemStatus;
  480. $params['order_status_payment'] = 'SUCCESS';
  481. }
  482. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'VIP') { // 余额支付
  483. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  484. ->where('member_account_classify', 'VIP')
  485. ->where('member_account_status', 'ACTIVED')
  486. ->first();
  487. if (!$account) {
  488. throw new BusinessException('账户异常');
  489. }
  490. $amount = $account->member_account_surplus + $account->member_account_added;
  491. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  492. throw new BusinessException('账户余额不足');
  493. }
  494. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  495. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  496. $account->member_account_surplus = 0;
  497. $account->member_account_added = $cut;
  498. } else {
  499. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  500. }
  501. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  502. $account->save();
  503. if ($params['pay_constitute'] == 'N') {
  504. $params['order_status_system'] = $systemStatus;
  505. $params['order_status_payment'] = 'SUCCESS';
  506. }
  507. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户
  508. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  509. ->where('member_account_classify', 'WELFARE')
  510. ->where('member_account_status', 'ACTIVED')
  511. ->first();
  512. if (!$account) {
  513. throw new BusinessException('账户异常');
  514. }
  515. $account->member_account_surplus = floatval($account->member_account_surplus);
  516. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  517. throw new BusinessException('账户余额不足');
  518. }
  519. if ($params['pay_constitute'] == 'N') {
  520. $params['order_status_system'] = $systemStatus;
  521. $params['order_status_payment'] = 'SUCCESS';
  522. }
  523. // 福利账户 300 、 700
  524. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  525. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  526. ->where('pay_status', 'SUCCESS')
  527. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  528. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  529. ->get()
  530. ->toArray();
  531. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  532. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  533. ->where('pay_status', 'SUCCESS')
  534. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  535. ->where('pay_category', 'REFUND')
  536. ->get()
  537. ->toArray();
  538. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  539. $paySum = 0;
  540. foreach ($payDetailArray as $key => $item) {
  541. if (isset($refundPayDetailArray[$key])) {
  542. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  543. continue;
  544. }
  545. $paySum = $paySum + $item;
  546. }
  547. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  548. Db::rollBack();
  549. return json_fail('超出福利限额');
  550. }
  551. } else {
  552. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  553. ->where('pay_status', 'SUCCESS')
  554. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  555. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  556. ->get()
  557. ->toArray();
  558. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  559. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  560. ->where('pay_status', 'SUCCESS')
  561. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  562. ->where('pay_category', 'REFUND')
  563. ->get()
  564. ->toArray();
  565. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  566. $paySum = 0;
  567. foreach ($payDetailArray as $key => $item) {
  568. if (isset($refundPayDetailArray[$key])) {
  569. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  570. continue;
  571. }
  572. $paySum = $paySum + $item;
  573. }
  574. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  575. throw new BusinessException('超出福利限额');
  576. }
  577. }
  578. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  579. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  580. $account->save();
  581. } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户
  582. $cardNbr = $params['card_nbr'];
  583. if (!$cardNbr) {
  584. throw new BusinessException('账户异常');
  585. }
  586. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  587. ->where('member_account_nbr', $cardNbr)
  588. ->where('member_account_status', 'ACTIVED')
  589. ->first();
  590. if (!$account) {
  591. throw new BusinessException('账户异常');
  592. }
  593. $amount = $account->member_account_surplus + $account->member_account_added;
  594. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  595. throw new BusinessException('账户余额不足');
  596. }
  597. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  598. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  599. $account->member_account_surplus = 0;
  600. $account->member_account_added = $cut;
  601. } else {
  602. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  603. }
  604. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  605. $account->save();
  606. if ($params['pay_constitute'] == 'N') {
  607. $params['order_status_system'] = $systemStatus;
  608. $params['order_status_payment'] = 'SUCCESS';
  609. }
  610. }
  611. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码
  612. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) {
  613. $params['order_status_system'] = $systemStatus;
  614. $params['order_status_payment'] = 'SUCCESS';
  615. }
  616. // 不组合或者组合后需要付款码的金额>0
  617. if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) {
  618. $result = OrderService::qrcodePay($params);
  619. $result = json_encode($result);
  620. $params['pay_json_response'] = $result;
  621. $result = json_decode($result, true);
  622. $prefix = substr($params['qrcode_nbr'], 0, 2);
  623. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  624. $params['pay_category'] = 'WXPAY';
  625. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  626. $params['order_status_system'] = 'PAYING';
  627. $params['order_status_payment'] = 'PENDING';
  628. $params['order_is_complete'] = 'N';
  629. // Db::rollBack();
  630. // return json_fail('支付失败');
  631. } else {
  632. $params['order_status_system'] = $systemStatus;
  633. $params['order_status_payment'] = 'SUCCESS';
  634. }
  635. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  636. $params['pay_category'] = 'ALIPAY';
  637. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  638. $params['order_status_system'] = 'PAYING';
  639. $params['order_status_payment'] = 'PENDING';
  640. $params['order_is_complete'] = 'N';
  641. // Db::rollBack();
  642. // return json_fail('支付失败');
  643. } else {
  644. $params['order_status_system'] = $systemStatus;
  645. $params['order_status_payment'] = 'SUCCESS';
  646. }
  647. } else {
  648. throw new BusinessException('付款码无效');
  649. }
  650. }
  651. }
  652. $orderConfigJson = [];
  653. // 优惠
  654. if (!empty($params['preferential'])) {
  655. $orderConfigJson['preferential'] = $params['preferential'];
  656. }
  657. // 配送方式
  658. if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店
  659. $orderConfigJson['premises'] = $params['dept_premises_id'];
  660. }
  661. if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) {
  662. $params['submit_premises_id'] = $premises->dept_id;
  663. }
  664. $params['order_config_json'] = json_encode($orderConfigJson);
  665. // 写入订单
  666. $this->insertMain($params);
  667. Db::commit();
  668. // 触发事件
  669. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  670. Event::dispatch('order.complete', $params);
  671. }
  672. // 触发事件
  673. if ($params['order_status_payment'] == 'SUCCESS') {
  674. // 上级提成
  675. OrderService::splitOrderCommission($params);
  676. // 入收支明细表
  677. OrderService::splitOrderStatisticsInOut($params);
  678. }
  679. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  680. _syslog("订单", "支付异常,检查是否有轮询");
  681. // 恢复优惠券到已占用
  682. if (!is_array($couponUseJson)) {
  683. $couponUseJson = json_decode($couponUseJson, true);
  684. }
  685. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  686. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  687. }
  688. _syslog("订单", "创建订单成功");
  689. return json_success('创建订单成功');
  690. } catch (BusinessException $e) {
  691. Db::rollBack();
  692. dump($e->getMessage());
  693. dump($e->getTrace());
  694. _syslog("订单", $e->getMessage());
  695. return json_fail($e->getMessage());
  696. } catch (\Exception $e) {
  697. Db::rollBack();
  698. dump($e->getMessage());
  699. dump($e->getTrace());
  700. _syslog("订单", "创建订单失败");
  701. return json_fail('创建订单失败');
  702. }
  703. }
  704. /**
  705. * 组合支付下单
  706. */
  707. public function insertConstitute(Request $request): Response
  708. {
  709. $params = $request->post();
  710. $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
  711. $premises = [];
  712. if (!empty($params['dept_premises_id'])) {
  713. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  714. }
  715. if (in_array('PACKAGE', $goodsClassifys)) {
  716. $params['submit_goods_classify'] = 'PACKAGE';
  717. }
  718. Db::beginTransaction();
  719. try {
  720. // 使用优惠券
  721. $couponUseJson = [];
  722. if (!empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  723. $couponResult = OrderService::payUseCoupon('insert', $params['settlement_now'], $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  724. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  725. throw new BusinessException("计算优惠后,实付金额错误!");
  726. }
  727. // 组装优惠券使用数据,存主表优惠里
  728. if (!empty($couponResult['use_coupon_json'])) {
  729. $couponUseJson = $couponResult['use_coupon_json'];
  730. }
  731. }
  732. // 存储优惠信息
  733. $params['order_discount_json'] = json_encode($this->discountRecord($couponUseJson, $params));
  734. $orderAmountPay = $params['order_amount_pay'];
  735. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');
  736. // 验证金额
  737. $constituteAmount = 0;
  738. foreach ($params['pay_category_constitute_list'] as $item) {
  739. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  740. }
  741. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  742. throw new BusinessException('组合支付金额与应付金额不一致');
  743. }
  744. $params['goods_classify'] = $goodsClassifys[0];
  745. // 验证库存
  746. OrderService::checkGoodsStorage($params);
  747. // 余额、福利、储值卡 验证短信
  748. if (!empty($params['pay_category_constitute'])
  749. && !in_array('OFFLINE', $params['pay_category_constitute'])
  750. && !in_array('MONEY', $params['pay_category_constitute'])
  751. && !in_array('QRCODE', $params['pay_category_constitute'])
  752. && (in_array('CASH', $params['pay_category_constitute'])
  753. || in_array('CARD', $params['pay_category_constitute'])
  754. || in_array('WELFARE', $params['pay_category_constitute']))) {
  755. $code = $params['sms_code'];
  756. if (!$code) {
  757. throw new BusinessException("验证码错误,请重新输入");
  758. }
  759. $member = Member::find($params['join_order_member_id']);
  760. $mobile = $member->member_mobile;
  761. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  762. $redisCode = Redis::get($key);
  763. if ($redisCode != $code && $code != '123456') {
  764. throw new BusinessException("验证码错误,请重新输入");
  765. }
  766. Redis::del($key);
  767. }
  768. // 验证线下付款密码
  769. if (!empty($params['pay_category_constitute'])
  770. && in_array('OFFLINE', $params['pay_category_constitute'])
  771. || (in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']))) {
  772. $password = $params['offline_password'];
  773. if ($password != '666888') {
  774. throw new BusinessException("密码错误,请重新输入");
  775. }
  776. }
  777. // 下单账户
  778. if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
  779. if (Member::where('member_mobile', $params['mobile'])->exists()) {
  780. throw new BusinessException("会员已存在");
  781. }
  782. $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
  783. // 创建会员
  784. MemberService::createMember($params);
  785. } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
  786. $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
  787. }
  788. if (empty($params['join_order_member_id'])) {
  789. throw new BusinessException("检查下单账户");
  790. }
  791. $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  792. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  793. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  794. $systemStatus = 'SENDING'; // 待发货
  795. // 立即结算
  796. if ($params['settlement_now'] == 'Y') {
  797. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  798. $params['order_is_complete'] = 'N';
  799. $systemStatus = "WAITING";
  800. }
  801. }
  802. $params['pay_detail_item'] = [];
  803. $wxAndAliPayStatus = 'Y';
  804. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付
  805. $params['order_status_system'] = $systemStatus;
  806. $params['order_status_payment'] = 'SUCCESS';
  807. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  808. // 线下支付金额
  809. if (isset($constituteList['OFFLINE'])) {
  810. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  811. // 生成支付记录
  812. $params['pay_detail_item'][] = $params;
  813. // OrderService::createPayDetail($params);
  814. }
  815. $params['order_amount_pay'] = $orderAmountPay;
  816. }
  817. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付
  818. $params['order_status_system'] = $systemStatus;
  819. $params['order_status_payment'] = 'SUCCESS';
  820. $params['pay_category'] = 'MONEY';
  821. // 现金支付金额
  822. if (isset($constituteList['MONEY'])) {
  823. $params['order_amount_pay'] = $constituteList['MONEY'];
  824. // 生成支付记录
  825. $params['pay_detail_item'][] = $params;
  826. // OrderService::createPayDetail($params);
  827. }
  828. $params['order_amount_pay'] = $orderAmountPay;
  829. }
  830. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  831. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  832. ->where('member_account_classify', 'CASH')
  833. ->where('member_account_status', 'ACTIVED')
  834. ->first();
  835. if (!$account) {
  836. throw new BusinessException("账户异常");
  837. }
  838. $amount = $account->member_account_surplus + $account->member_account_added;
  839. if (isset($constituteList['CASH'])) {
  840. $params['order_amount_pay'] = $constituteList['CASH'];
  841. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  842. }
  843. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  844. throw new BusinessException("账户余额不足");
  845. }
  846. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  847. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  848. // $params['order_amount_pay'] = $amount;
  849. // }
  850. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  851. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  852. // $account->member_account_surplus = 0;
  853. // $account->member_account_added = $cut;
  854. // } else {
  855. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  856. // }
  857. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  858. // $account->save();
  859. // 余额账户扣款数据
  860. $params['waitToPayAccount']['cash'] = [
  861. 'group_id' => $params['orderGroupId'],
  862. 'member_id' => $params['join_order_member_id'],
  863. 'amount' => $constituteList['CASH'],
  864. 'nbr' => $params['join_order_member_id'] . '-CASH'
  865. ];
  866. $params['order_status_system'] = $systemStatus;
  867. $params['order_status_payment'] = 'SUCCESS';
  868. // 生成支付记录
  869. $params['pay_detail_item'][] = $params;
  870. $params['order_amount_pay'] = $orderAmountPay;
  871. }
  872. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  873. $cardNbr = $params['card_nbr'];
  874. if (!$cardNbr) {
  875. throw new BusinessException("储值卡账户异常");
  876. }
  877. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  878. ->where('member_account_nbr', $cardNbr)
  879. ->where('member_account_status', 'ACTIVED')
  880. ->first();
  881. if (!$account) {
  882. throw new BusinessException("储值卡账户异常");
  883. }
  884. $amount = $account->member_account_surplus + $account->member_account_added;
  885. // 储值卡账户支付金额
  886. if (isset($constituteList['CARD'])) {
  887. $params['order_amount_pay'] = $constituteList['CARD'];
  888. $params['pay_category'] = $cardNbr;
  889. }
  890. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  891. throw new BusinessException("储值卡账户余额不足");
  892. }
  893. // if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  894. // $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  895. // $params['order_amount_pay'] = $amount;
  896. // }
  897. //
  898. // if ($params['order_amount_pay'] > $account->member_account_surplus) {
  899. // $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  900. // $account->member_account_surplus = 0;
  901. // $account->member_account_added = $cut;
  902. // } else {
  903. // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  904. // }
  905. // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  906. // $account->save();
  907. // 储值卡账户扣款数据
  908. $params['waitToPayAccount']['card'] = [
  909. 'group_id' => $params['orderGroupId'],
  910. 'member_id' => $params['join_order_member_id'],
  911. 'amount' => $constituteList['CARD'],
  912. 'nbr' => $params['join_order_member_id'] . '-CARD'
  913. ];
  914. $params['order_status_system'] = $systemStatus;
  915. $params['order_status_payment'] = 'SUCCESS';
  916. // 生成支付记录
  917. $params['pay_detail_item'][] = $params;
  918. $params['order_amount_pay'] = $orderAmountPay;
  919. }
  920. //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute'])
  921. // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码
  922. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  923. // 需要付款码的金额>0
  924. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  925. // 付款码支付金额
  926. $params['order_amount_pay'] = $constituteList['QRCODE'];
  927. // 调支付
  928. $result = OrderService::qrcodePay($params);
  929. $result = json_encode($result);
  930. $params['pay_json_response'] = $result;
  931. $result = json_decode($result, true);
  932. $prefix = substr($params['qrcode_nbr'], 0, 2);
  933. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  934. $params['pay_category'] = 'WXPAY';
  935. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  936. // 标记支付状态
  937. $wxAndAliPayStatus = 'N';
  938. $params['order_status_system'] = 'PAYING';
  939. $params['order_status_payment'] = 'PENDING';
  940. $params['order_is_complete'] = 'N';
  941. // Db::rollBack();
  942. // return json_fail('支付失败');
  943. } else {
  944. $params['order_status_system'] = $systemStatus;
  945. $params['order_status_payment'] = 'SUCCESS';
  946. }
  947. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  948. $params['pay_category'] = 'ALIPAY';
  949. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  950. // 标记支付状态
  951. $wxAndAliPayStatus = 'N';
  952. $params['order_status_system'] = 'PAYING';
  953. $params['order_status_payment'] = 'PENDING';
  954. $params['order_is_complete'] = 'N';
  955. // Db::rollBack();
  956. // return json_fail('支付失败');
  957. } else {
  958. $params['order_status_system'] = $systemStatus;
  959. $params['order_status_payment'] = 'SUCCESS';
  960. }
  961. } else {
  962. throw new BusinessException("二维码错误");
  963. }
  964. // 生成支付记录
  965. $params['pay_detail_item'][] = $params;
  966. // OrderService::createPayDetail($params);
  967. // 账户支付的金额
  968. $params['order_amount_pay'] = $orderAmountPay;
  969. }
  970. }
  971. $orderConfigJson = [];
  972. // 优惠
  973. if (!empty($params['preferential'])) {
  974. $orderConfigJson['preferential'] = $params['preferential'];
  975. }
  976. $params['order_config_json'] = json_encode($orderConfigJson);
  977. // 写入订单
  978. $this->insertMain($params, $wxAndAliPayStatus);
  979. Db::commit();
  980. // 触发事件
  981. if (!empty($params['order_is_complete']) && $params['order_is_complete'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
  982. Event::dispatch('order.complete', $params);
  983. }
  984. // 触发事件
  985. if ($params['order_status_payment'] == 'SUCCESS') {
  986. // 上级提成
  987. OrderService::splitOrderCommission($params);
  988. // 入收支明细表
  989. OrderService::splitOrderStatisticsInOut($params);
  990. }
  991. if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
  992. _syslog("订单", "支付异常,检查是否有轮询");
  993. // 恢复优惠券到已占用
  994. if (!is_array($couponUseJson)) {
  995. $couponUseJson = json_decode($couponUseJson, true);
  996. }
  997. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  998. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  999. }
  1000. _syslog("订单", "创建订单成功");
  1001. return json_success('创建订单成功');
  1002. } catch (BusinessException $e) {
  1003. Db::rollBack();
  1004. dump($e->getMessage());
  1005. _syslog("订单", $e->getMessage());
  1006. return json_fail($e->getMessage());
  1007. } catch (\Exception $e) {
  1008. Db::rollBack();
  1009. dump($e->getMessage());
  1010. _syslog("订单", "创建订单失败");
  1011. return json_fail('创建订单失败');
  1012. }
  1013. }
  1014. public function pay(Request $request)
  1015. {
  1016. $params = $request->post();
  1017. // 余额、福利、储值卡 验证短信
  1018. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) {
  1019. $code = $params['sms_code'];
  1020. if (!$code) {
  1021. return json_fail("验证码错误,请重新输入");
  1022. }
  1023. $member = Member::find($params['join_order_member_id']);
  1024. $mobile = $member->member_mobile;
  1025. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1026. $redisCode = Redis::get($key);
  1027. if ($redisCode != $code && $code != '123456') {
  1028. return json_fail("验证码错误,请重新输入");
  1029. }
  1030. Redis::del($key);
  1031. }
  1032. // 验证线下付款密码
  1033. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
  1034. $password = $params['offline_password'];
  1035. if ($password != '666888') {
  1036. return json_fail("密码错误,请重新输入");
  1037. }
  1038. }
  1039. $order = Order::where('order_id', $params['order_id'])->first();
  1040. $oldOrderStatus = $order->order_status_system;
  1041. if (!$order) {
  1042. return json_fail('订单异常');
  1043. }
  1044. if ($order->order_status_system != 'PAYING') {
  1045. return json_fail('订单不是可支付状态');
  1046. }
  1047. if (!empty($order->order_config_json)) {
  1048. $orderConfigJson = json_decode($order->order_config_json, true);
  1049. if (isset($orderConfigJson['premises'])) {
  1050. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1051. if (!empty($premises)) {
  1052. $params['submit_premises_id'] = $premises->dept_id;
  1053. }
  1054. }
  1055. }
  1056. $params['orderId'] = $params['order_id'];
  1057. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1058. $order->order_groupby = $params['orderGroupId'];
  1059. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1060. ->select('goods_id', 'goods_name', 'goods_classify')
  1061. ->first();
  1062. if (!$goods) {
  1063. return json_fail('产品数据异常');
  1064. }
  1065. $goods = $goods->toArray();
  1066. $params['goods_classify'] = $goods['goods_classify'] ?? '';
  1067. $systemStatus = 'SENDING'; // 待发货
  1068. // 立即结算
  1069. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1070. $order->order_is_complete = 'Y';
  1071. $systemStatus = 'DONE';
  1072. }
  1073. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1074. $params['order_is_complete'] = 'N';
  1075. $systemStatus = "WAITING";
  1076. }
  1077. // if ($params['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') {
  1078. // $systemStatus = "WAITING";
  1079. // }
  1080. Db::beginTransaction();
  1081. try {
  1082. // 使用优惠券
  1083. $couponUseJson = [];
  1084. $discountJson = [];
  1085. if (!empty($order->order_discount_json)) {
  1086. $discountJson = json_decode($order->order_discount_json, true);
  1087. foreach ($discountJson as $item) {
  1088. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1089. throw new BusinessException("计算优惠后,实付金额错误!");
  1090. }
  1091. }
  1092. $couponUseJson = $discountJson;
  1093. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  1094. // 释放下单时选的优惠券
  1095. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  1096. }
  1097. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1098. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1099. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1100. throw new BusinessException("计算优惠后,实付金额错误!");
  1101. }
  1102. // 组装优惠券使用数据,存主表优惠里
  1103. if (!empty($couponResult['use_coupon_json'])) {
  1104. $couponUseJson = $couponResult['use_coupon_json'];
  1105. }
  1106. }
  1107. // 存储优惠信息
  1108. if (empty($discountJson)) {
  1109. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1110. }
  1111. // 组合支付时,付款码应收金额
  1112. $qrcodePayAmount = 0;
  1113. if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
  1114. $order->order_status_system = $systemStatus;
  1115. $order->order_status_payment = 'SUCCESS';
  1116. if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
  1117. $params['pay_category'] = $params['pay_category_sub'];
  1118. }
  1119. } else if ($params['pay_category'] == 'CASH') { // 余额支付
  1120. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1121. ->where('member_account_classify', 'CASH')
  1122. ->where('member_account_status', 'ACTIVED')
  1123. ->first();
  1124. if (!$account) {
  1125. throw new BusinessException('账户异常');
  1126. }
  1127. $amount = $account->member_account_surplus + $account->member_account_added;
  1128. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1129. throw new BusinessException('账户余额不足');
  1130. }
  1131. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1132. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1133. $params['order_amount_pay'] = $amount;
  1134. }
  1135. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1136. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1137. $account->member_account_surplus = 0;
  1138. $account->member_account_added = $cut;
  1139. } else {
  1140. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1141. }
  1142. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1143. $account->save();
  1144. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1145. $order->order_status_system = $systemStatus;
  1146. $order->order_status_payment = 'SUCCESS';
  1147. }
  1148. } else if ($params['pay_category'] == 'VIP') { // 余额支付
  1149. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1150. ->where('member_account_classify', 'VIP')
  1151. ->where('member_account_status', 'ACTIVED')
  1152. ->first();
  1153. if (!$account) {
  1154. throw new BusinessException('账户异常');
  1155. }
  1156. $amount = $account->member_account_surplus + $account->member_account_added;
  1157. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1158. throw new BusinessException('账户余额不足');
  1159. }
  1160. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1161. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1162. $params['order_amount_pay'] = $amount;
  1163. }
  1164. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1165. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1166. $account->member_account_surplus = 0;
  1167. $account->member_account_added = $cut;
  1168. } else {
  1169. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1170. }
  1171. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1172. $account->save();
  1173. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1174. $order->order_status_system = $systemStatus;
  1175. $order->order_status_payment = 'SUCCESS';
  1176. }
  1177. } else if ($params['pay_category'] == 'WELFARE') { // 福利账户
  1178. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1179. ->where('member_account_classify', 'WELFARE')
  1180. ->where('member_account_status', 'ACTIVED')
  1181. ->first();
  1182. if (!$account) {
  1183. throw new BusinessException('账户异常');
  1184. }
  1185. $account->member_account_surplus = floatval($account->member_account_surplus);
  1186. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1187. throw new BusinessException('账户余额不足');
  1188. }
  1189. if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) {
  1190. $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus;
  1191. $params['order_amount_pay'] = $account->member_account_surplus;
  1192. }
  1193. if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) {
  1194. $order->order_status_system = $systemStatus;
  1195. $order->order_status_payment = 'SUCCESS';
  1196. }
  1197. // 福利账户 300 、 700
  1198. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) {
  1199. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1200. ->where('pay_status', 'SUCCESS')
  1201. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1202. ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES'])
  1203. ->get()
  1204. ->toArray();
  1205. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1206. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1207. ->where('pay_status', 'SUCCESS')
  1208. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1209. ->where('pay_category', 'REFUND')
  1210. ->get()
  1211. ->toArray();
  1212. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1213. $paySum = 0;
  1214. foreach ($payDetailArray as $key => $item) {
  1215. if (isset($refundPayDetailArray[$key])) {
  1216. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1217. continue;
  1218. }
  1219. $paySum = $paySum + $item;
  1220. }
  1221. if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) {
  1222. throw new BusinessException('超出福利限额');
  1223. } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) {
  1224. $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum);
  1225. $params['order_amount_pay'] = (700 - $paySum);
  1226. }
  1227. } else {
  1228. $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1229. ->where('pay_status', 'SUCCESS')
  1230. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1231. ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE'])
  1232. ->get()
  1233. ->toArray();
  1234. $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id');
  1235. $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id'])
  1236. ->where('pay_status', 'SUCCESS')
  1237. ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE')
  1238. ->where('pay_category', 'REFUND')
  1239. ->get()
  1240. ->toArray();
  1241. $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id');
  1242. $paySum = 0;
  1243. foreach ($payDetailArray as $key => $item) {
  1244. if (isset($refundPayDetailArray[$key])) {
  1245. $paySum = $paySum + ($item - $refundPayDetailArray[$key]);
  1246. continue;
  1247. }
  1248. $paySum = $paySum + $item;
  1249. }
  1250. if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) {
  1251. throw new BusinessException('超出福利限额');
  1252. } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) {
  1253. $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum);
  1254. $params['order_amount_pay'] = (300 - $paySum);
  1255. }
  1256. }
  1257. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1258. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1259. $account->save();
  1260. } else if ($params['pay_category'] == 'CARD') { // 储值卡账户
  1261. $cardNbr = $params['card_nbr'];
  1262. if (!$cardNbr) {
  1263. throw new BusinessException('账户异常');
  1264. }
  1265. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1266. ->where('member_account_nbr', $cardNbr)
  1267. ->where('member_account_status', 'ACTIVED')
  1268. ->first();
  1269. if (!$account) {
  1270. throw new BusinessException('账户异常');
  1271. }
  1272. $amount = $account->member_account_surplus + $account->member_account_added;
  1273. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1274. throw new BusinessException('账户余额不足');
  1275. }
  1276. if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) {
  1277. $qrcodePayAmount = $params['order_amount_pay'] - $amount;
  1278. $params['order_amount_pay'] = $amount;
  1279. }
  1280. if ($params['order_amount_pay'] > $account->member_account_surplus) {
  1281. $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus);
  1282. $account->member_account_surplus = 0;
  1283. $account->member_account_added = $cut;
  1284. } else {
  1285. $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay'];
  1286. }
  1287. $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay'];
  1288. $account->save();
  1289. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) {
  1290. $order->order_status_system = $systemStatus;
  1291. $order->order_status_payment = 'SUCCESS';
  1292. }
  1293. }
  1294. if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码
  1295. // 提交过来的支付分类
  1296. $submitPayCategory = $params['pay_category'];
  1297. // 账户支付的金额
  1298. $accountAmount = $params['order_amount_pay'];
  1299. if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
  1300. // 组合支付,改成需要付款码需要支付的金额
  1301. $params['order_amount_pay'] = $qrcodePayAmount;
  1302. }
  1303. // 去支付
  1304. $result = OrderService::qrcodePay($params);
  1305. $result = json_encode($result);
  1306. $params['pay_json_response'] = $result;
  1307. $result = json_decode($result, true);
  1308. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1309. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1310. $params['pay_category'] = 'WXPAY';
  1311. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  1312. $order->order_status_system = $oldOrderStatus;
  1313. $order->order_status_payment = 'PENDING';
  1314. $order->order_is_complete = 'N';
  1315. // Db::rollBack();
  1316. // return json_fail('支付失败');
  1317. } else {
  1318. $order->order_status_system = $systemStatus;
  1319. $order->order_status_payment = 'SUCCESS';
  1320. }
  1321. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1322. $params['pay_category'] = 'ALIPAY';
  1323. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1324. $order->order_status_system = $oldOrderStatus;
  1325. $order->order_status_payment = 'PENDING';
  1326. $order->order_is_complete = 'N';
  1327. // Db::rollBack();
  1328. // return json_fail('支付失败');
  1329. } else {
  1330. $order->order_status_system = $systemStatus;
  1331. $order->order_status_payment = 'SUCCESS';
  1332. }
  1333. } else {
  1334. throw new BusinessException('付款码无效');
  1335. }
  1336. // 账户支付的金额
  1337. $params['order_amount_pay'] = $accountAmount;
  1338. }
  1339. $orderConfigJson = [];
  1340. if (!empty($order->order_config_json)) {
  1341. $orderConfigJson = json_decode($order->order_config_json, true);
  1342. }
  1343. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1344. $order->order_config_json = json_encode($orderConfigJson);
  1345. $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount;
  1346. // 主订单
  1347. $order->save();
  1348. // sheet
  1349. if ($order->order_status_payment == 'SUCCESS') {
  1350. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1351. 'order_sheet_status' => $systemStatus,
  1352. ]);
  1353. }
  1354. // payDetail
  1355. // 不组合支付,那就只有一条支付记录 先删,再加
  1356. PayDetail::where('join_pay_order_id', $order->order_groupby)
  1357. ->whereJsonContains('join_pay_object_json->order_id', $params['orderId'])
  1358. ->delete();
  1359. $payData = [
  1360. 'pay_amount' => $params['order_amount_pay']
  1361. ];
  1362. if ($order->order_status_payment == 'SUCCESS') {
  1363. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1364. $payData['pay_status'] = 'SUCCESS';
  1365. }
  1366. if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  1367. $payData['pay_prepayid'] = $params['pay_category'];
  1368. $payData['pay_json_response'] = $params['pay_json_response'];
  1369. } else if ($params['pay_category'] == 'CASH') {
  1370. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH';
  1371. } else if ($params['pay_category'] == 'WELFARE') {
  1372. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE';
  1373. } else if ($params['pay_category'] == 'VIP') {
  1374. $payData['pay_prepayid'] = $params['join_order_member_id'] . '-VIP';
  1375. } else if ($params['pay_category'] == 'CARD') {
  1376. $payData['pay_prepayid'] = $params['card_nbr'];
  1377. } else if ($params['pay_category'] == 'OFFLINE') {
  1378. $payData['pay_prepayid'] = 'OFFLINE';
  1379. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  1380. $payData['pay_prepayid'] = 'OFFLINE_ALIPAY';
  1381. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  1382. $payData['pay_prepayid'] = 'OFFLINE_WXPAY';
  1383. } else if ($params['pay_category'] == 'MONEY') {
  1384. $payData['pay_prepayid'] = 'MONEY';
  1385. }
  1386. $payData['join_pay_member_id'] = $params['join_order_member_id'];
  1387. $payData['join_pay_order_id'] = $order->order_groupby;
  1388. $payData['pay_status'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING';
  1389. $payData['pay_category'] = $params['goods_classify'] ?? '';
  1390. $payData['pay_paytimes'] = date('Y-m-d H:i:s');
  1391. $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"}
  1392. $payData['pay_json_response'] = !empty($payData['pay_status']) && $payData['pay_status'] == 'SUCCESS' ? (!empty($params['pay_json_response']) ? $params['pay_json_response'] : json_encode(['pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')])) : '[]';
  1393. $payData['join_pay_object_json'] = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  1394. $payData['pay_addtimes'] = time();
  1395. PayDetail::insert($payData);
  1396. $writeOffDate = [];
  1397. $applyData = [];
  1398. // // 买的单个服务
  1399. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1400. foreach ($params['goodsContentList'] as $goods) {
  1401. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1402. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1403. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1404. $params['order_sheet_num'] = $goods['nbr'];
  1405. // 预约表
  1406. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1407. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1408. // 入预约记录
  1409. $this->insertAppointment($params, $writeOffDate, $applyData);
  1410. }
  1411. $goods['skuId'] = $goods['sku_id'];
  1412. $goods['category'] = $goods['goods_classify'];
  1413. // 权益表
  1414. $this->insertMemberBenefit($params, $goods);
  1415. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1416. $params['packageId'] = $goods['goods_id'];
  1417. $components = GoodsComponent::with([
  1418. 'goods' => function ($query) {
  1419. $query->select('goods_id', 'goods_name', 'goods_classify');
  1420. }
  1421. ])->where('join_component_master_goods_id', $params['packageId'])
  1422. ->get()
  1423. ->toArray();
  1424. foreach ($components as $component) {
  1425. $componentJson = json_decode($component['goods_component_json'], true);
  1426. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1427. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1428. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1429. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1430. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1431. // 入预约记录
  1432. $this->insertAppointment($params, $writeOffDate);
  1433. }
  1434. $goods['goods_id'] = $component['join_component_goods_id'];
  1435. $goods['goods_name'] = $component['goods']['goods_name'];
  1436. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1437. $goods['skuId'] = $goods['sku_id'];
  1438. $goods['category'] = 'SERVICE';
  1439. // 权益表
  1440. $this->insertMemberBenefit($params, $goods);
  1441. }
  1442. }
  1443. }
  1444. }
  1445. Db::commit();
  1446. // 触发事件
  1447. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1448. // 完成订单
  1449. Event::dispatch('order.complete', $params);
  1450. // 会员升级
  1451. // Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1452. }
  1453. if ($order->order_status_payment == 'SUCCESS') {
  1454. // 上级提成
  1455. Event::dispatch('commission.order', $params);
  1456. }
  1457. // 打小票
  1458. if ($order->order_status_payment == 'SUCCESS') {
  1459. if (!empty($premises) && !empty($premises->dept_id)) {
  1460. $voteData = [
  1461. 'func' => 'procActionToPrinter',
  1462. 'sign' => '',
  1463. 'data' => [
  1464. 'printer_premises' => $premises->dept_id,
  1465. 'printer_device' => ["收银"],
  1466. 'printer_action' => 'ExecPrintOrder',
  1467. 'printer_data' => [
  1468. 'order_id' => $params['orderId'],
  1469. 'order_batch' => ''
  1470. ]
  1471. ]
  1472. ];
  1473. // dump("小票参数", $voteData);
  1474. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1475. }
  1476. }
  1477. if ($order->order_status_payment != 'SUCCESS') {
  1478. _syslog("订单", "支付异常,检查是否有轮询");
  1479. // 恢复优惠券到已占用
  1480. if (!is_array($couponUseJson)) {
  1481. $couponUseJson = json_decode($couponUseJson, true);
  1482. }
  1483. // 如果下单时就填了,不用恢复
  1484. if (empty($discountJson)) {
  1485. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1486. }
  1487. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1488. }
  1489. _syslog("订单", "订单支付成功");
  1490. return json_success('支付成功');
  1491. } catch (BusinessException $e) {
  1492. dump($e->getMessage());
  1493. Db::rollBack();
  1494. _syslog("订单", "订单支付失败:" . $e->getMessage());
  1495. return json_fail("支付失败:" . $e->getMessage());
  1496. } catch (\Exception $e) {
  1497. dump($e->getMessage());
  1498. Db::rollBack();
  1499. _syslog("订单", "订单支付失败");
  1500. return json_fail('支付失败');
  1501. }
  1502. }
  1503. /**
  1504. * 组合支付
  1505. */
  1506. public function payConstitute(Request $request)
  1507. {
  1508. $params = $request->post();
  1509. // 余额、福利、储值卡 验证短信
  1510. if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) {
  1511. $code = $params['sms_code'];
  1512. if (!$code) {
  1513. return json_fail("验证码错误,请重新输入");
  1514. }
  1515. $member = Member::find($params['join_order_member_id']);
  1516. $mobile = $member->member_mobile;
  1517. $key = "SMS:CODE:ORDER_PAY:" . $mobile;
  1518. $redisCode = Redis::get($key);
  1519. if ($redisCode != $code && $code != '123456') {
  1520. return json_fail("验证码错误,请重新输入");
  1521. }
  1522. Redis::del($key);
  1523. }
  1524. // 验证线下付款密码
  1525. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) {
  1526. $password = $params['offline_password'];
  1527. if ($password != '666888') {
  1528. return json_fail("密码错误,请重新输入");
  1529. }
  1530. }
  1531. $order = Order::where('order_id', $params['order_id'])->first();
  1532. if (!$order) {
  1533. return json_fail('订单异常');
  1534. }
  1535. if ($order->order_status_system != 'PAYING') {
  1536. return json_fail('订单不是可支付状态');
  1537. }
  1538. if (!empty($order->order_config_json)) {
  1539. $orderConfigJson = json_decode($order->order_config_json, true);
  1540. if (isset($orderConfigJson['premises'])) {
  1541. $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first();
  1542. if (!empty($premises)) {
  1543. $params['submit_premises_id'] = $premises->dept_id;
  1544. }
  1545. }
  1546. }
  1547. $params['orderId'] = $params['order_id'];
  1548. $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
  1549. $order->order_groupby = $params['orderGroupId'];
  1550. $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
  1551. ->select('goods_id', 'goods_name', 'goods_classify')
  1552. ->first();
  1553. if (!$goods) {
  1554. return json_fail('产品数据异常');
  1555. }
  1556. $goods = $goods->toArray();
  1557. $params['goods_classify'] = $goods['goods_classify'];
  1558. $systemStatus = 'SENDING'; // 待发货
  1559. // 立即结算
  1560. if (in_array($params['goods_classify'], ['MEALS', 'VIP'])) {
  1561. $order->order_is_complete = 'Y';
  1562. $systemStatus = 'DONE';
  1563. }
  1564. if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $params['delivery'] == 'ARRIVAL') {
  1565. $params['order_is_complete'] = 'N';
  1566. $systemStatus = "WAITING";
  1567. }
  1568. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  1569. Db::beginTransaction();
  1570. try {// 使用优惠券
  1571. $couponUseJson = [];
  1572. $discountJson = [];
  1573. if (!empty($order->order_discount_json)) {
  1574. $discountJson = json_decode($order->order_discount_json, true);
  1575. foreach ($discountJson as $item) {
  1576. if (isset($item['coupon_value']) && sprintf('%.2f', (floatval($order->order_amount_total) - floatval($params['order_amount_pay']))) != sprintf('%.2f', $item['coupon_value'])) {
  1577. throw new BusinessException("计算优惠后,实付金额错误!");
  1578. }
  1579. }
  1580. $couponUseJson = $discountJson;
  1581. $this->changeOrderCouponStatus($couponUseJson, 'USED');
  1582. // 释放下单时选的优惠券
  1583. // $order->order_discount_json = $this->releaseCoupon($discountJson);
  1584. }
  1585. if (empty($discountJson) && !empty($params['join_order_member_id']) && !empty($params['preferential'])) {
  1586. $couponResult = OrderService::payUseCoupon('pay', 'Y', $params['join_order_member_id'], $params['goodsContentList'], $params['preferential'], $params['order_amount_total']);
  1587. if (!empty($couponResult['pay_amount']) && $couponResult['pay_amount'] != $params['order_amount_pay']) {
  1588. throw new BusinessException("计算优惠后,实付金额错误!");
  1589. }
  1590. // 组装优惠券使用数据,存主表优惠里
  1591. if (!empty($couponResult['use_coupon_json'])) {
  1592. $couponUseJson = $couponResult['use_coupon_json'];
  1593. }
  1594. }
  1595. // 存储优惠信息
  1596. if (empty($discountJson)) {
  1597. $order->order_discount_json = json_encode($this->discountRecord($couponUseJson, $params));
  1598. }
  1599. $orderAmountPay = $params['order_amount_pay'];
  1600. $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额
  1601. $constituteAmount = 0;
  1602. foreach ($params['pay_category_constitute_list'] as $item) {
  1603. $constituteAmount = sprintf("%.2f", $constituteAmount) + sprintf("%.2f", $item['amount']);
  1604. }
  1605. if (sprintf("%.2f", $params['order_amount_pay']) != sprintf("%.2f", $constituteAmount)) {
  1606. throw new BusinessException('组合支付金额与应付金额不一致');
  1607. }
  1608. $wxAndAliPayStatus = 'Y';
  1609. $waitToPayAccount = [];
  1610. // 清除订单的支付记录,重建
  1611. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->delete();
  1612. if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款
  1613. $order->order_status_system = $systemStatus;
  1614. $order->order_status_payment = 'SUCCESS';
  1615. $params['pay_category'] = $params['pay_category_sub'] ?? 'OFFLINE';
  1616. // 线下支付金额
  1617. if (isset($constituteList['OFFLINE'])) {
  1618. $params['order_amount_pay'] = $constituteList['OFFLINE'];
  1619. // 生成支付记录
  1620. $params['order_status_payment'] = 'PENDING';
  1621. OrderService::createProductPayConstituteDetail($params);
  1622. $params['order_status_payment'] = 'SUCCESS';
  1623. }
  1624. $params['order_amount_pay'] = $orderAmountPay;
  1625. }
  1626. if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //现金付款
  1627. $order->order_status_system = $systemStatus;
  1628. $order->order_status_payment = 'SUCCESS';
  1629. $params['pay_category'] = 'MONEY';
  1630. // 线下支付金额
  1631. if (isset($constituteList['MONEY'])) {
  1632. $params['order_amount_pay'] = $constituteList['MONEY'];
  1633. // 生成支付记录
  1634. $params['order_status_payment'] = 'PENDING';
  1635. OrderService::createProductPayConstituteDetail($params, $payDetail);
  1636. $params['order_status_payment'] = 'SUCCESS';
  1637. }
  1638. $params['order_amount_pay'] = $orderAmountPay;
  1639. }
  1640. if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付
  1641. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1642. ->where('member_account_classify', 'CASH')
  1643. ->where('member_account_status', 'ACTIVED')
  1644. ->first();
  1645. if (!$account) {
  1646. throw new BusinessException('账户异常');
  1647. }
  1648. if (isset($constituteList['CASH'])) {
  1649. $params['order_amount_pay'] = $constituteList['CASH'];
  1650. $params['pay_category'] = $params['join_order_member_id'] . '-CASH';
  1651. }
  1652. $amount = $account->member_account_surplus + $account->member_account_added;
  1653. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1654. throw new BusinessException('账户余额不足');
  1655. }
  1656. // 余额账户扣款数据
  1657. $waitToPayAccount['cash'] = [
  1658. 'group_id' => $params['orderGroupId'],
  1659. 'member_id' => $params['join_order_member_id'],
  1660. 'amount' => $constituteList['CASH'],
  1661. 'nbr' => $params['join_order_member_id'] . '-CASH'
  1662. ];
  1663. // 生成支付记录
  1664. $params['order_status_payment'] = 'PENDING';
  1665. OrderService::createProductPayConstituteDetail($params);
  1666. $params['order_status_payment'] = 'SUCCESS';
  1667. $params['order_amount_pay'] = $orderAmountPay;
  1668. $order->order_status_system = $systemStatus;
  1669. $order->order_status_payment = 'SUCCESS';
  1670. }
  1671. if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户
  1672. $cardNbr = $params['card_nbr'];
  1673. if (!$cardNbr) {
  1674. throw new BusinessException('账户异常');
  1675. }
  1676. $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id'])
  1677. ->where('member_account_nbr', $cardNbr)
  1678. ->where('member_account_status', 'ACTIVED')
  1679. ->first();
  1680. if (!$account) {
  1681. Db::rollBack();
  1682. return json_fail('账户异常');
  1683. }
  1684. // 储值卡账户支付金额
  1685. if (isset($constituteList['CARD'])) {
  1686. $params['order_amount_pay'] = $constituteList['CARD'];
  1687. $params['pay_category'] = $cardNbr;
  1688. }
  1689. $amount = $account->member_account_surplus + $account->member_account_added;
  1690. if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) {
  1691. throw new BusinessException('账户余额不足');
  1692. }
  1693. // 储值卡账户扣款数据
  1694. $waitToPayAccount['card'] = [
  1695. 'group_id' => $params['orderGroupId'],
  1696. 'member_id' => $params['join_order_member_id'],
  1697. 'amount' => $constituteList['CARD'],
  1698. 'nbr' => $params['join_order_member_id'] . '-CARD'
  1699. ];
  1700. // 生成支付记录
  1701. $params['order_status_payment'] = 'PENDING';
  1702. OrderService::createProductPayConstituteDetail($params);
  1703. $params['order_status_payment'] = 'SUCCESS';
  1704. $params['order_amount_pay'] = $orderAmountPay;
  1705. $order->order_status_system = $systemStatus;
  1706. $order->order_status_payment = 'SUCCESS';
  1707. }
  1708. if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码
  1709. if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) {
  1710. // 付款码支付金额
  1711. $params['order_amount_pay'] = $constituteList['QRCODE'];
  1712. // 调支付
  1713. $result = OrderService::qrcodePay($params);
  1714. $result = json_encode($result);
  1715. $params['pay_json_response'] = $result;
  1716. $result = json_decode($result, true);
  1717. $prefix = substr($params['qrcode_nbr'], 0, 2);
  1718. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  1719. $params['pay_category'] = 'WXPAY';
  1720. if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
  1721. // 标记支付状态
  1722. $wxAndAliPayStatus = 'N';
  1723. $order->order_status_system = 'PAYING';
  1724. $order->order_status_payment = 'PENDING';
  1725. $order->order_is_complete = 'N';
  1726. $params['order_status_payment'] = 'PAYING';
  1727. } else {
  1728. $order->order_status_system = $systemStatus;
  1729. $order->order_status_payment = 'SUCCESS';
  1730. $params['order_status_payment'] = 'SUCCESS';
  1731. }
  1732. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  1733. $params['pay_category'] = 'ALIPAY';
  1734. if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
  1735. // 标记支付状态
  1736. $wxAndAliPayStatus = 'N';
  1737. $order->order_status_system = 'PAYING';
  1738. $order->order_status_payment = 'PENDING';
  1739. $order->order_is_complete = 'N';
  1740. $params['order_status_payment'] = 'PAYING';
  1741. } else {
  1742. $order->order_status_system = $systemStatus;
  1743. $order->order_status_payment = 'SUCCESS';
  1744. $params['order_status_payment'] = 'SUCCESS';
  1745. }
  1746. } else {
  1747. throw new BusinessException('付款码无效');
  1748. }
  1749. }
  1750. // 生成支付记录
  1751. OrderService::createProductPayConstituteDetail($params);
  1752. // 账户支付的金额
  1753. $params['order_amount_pay'] = $orderAmountPay;
  1754. }
  1755. $orderConfigJson = [];
  1756. if (!empty($order->order_config_json)) {
  1757. $orderConfigJson = json_decode($order->order_config_json, true);
  1758. }
  1759. $orderConfigJson['preferential'] = $params['preferential'] ?? '';
  1760. $order->order_config_json = json_encode($orderConfigJson);
  1761. $order->order_amount_pay = $params['order_amount_pay'];
  1762. // 主订单
  1763. $order->save();
  1764. // sheet
  1765. if ($order->order_status_payment == 'SUCCESS') {
  1766. OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([
  1767. 'order_sheet_status' => $systemStatus,
  1768. ]);
  1769. }
  1770. if ($wxAndAliPayStatus == 'Y') {
  1771. PayDetail::whereJsonContains('join_pay_object_json->order_id', $params['orderId'])->update([
  1772. 'pay_status' => 'SUCCESS',
  1773. 'pay_paytimes' => date('Y-m-d H:i:s')
  1774. ]);
  1775. // 扣款
  1776. foreach ($waitToPayAccount as $item) {
  1777. $accountNbr = $item['nbr'];
  1778. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  1779. $account->member_account_expend = $account->member_account_expend + $item['amount'];
  1780. if ($account->member_account_surplus < $item['amount'] && strpos($accountNbr, 'CASH') !== false) {
  1781. $account->member_account_added = $account->member_account_added - ($item['amount'] - $account->member_account_surplus);
  1782. $account->member_account_surplus = 0;
  1783. } else {
  1784. $account->member_account_surplus = $account->member_account_surplus - $item['amount'];
  1785. }
  1786. $account->save();
  1787. }
  1788. }
  1789. // 买单个服务
  1790. $writeOffDate = [];
  1791. $applyData = [];
  1792. if ($order->order_status_payment == 'SUCCESS' && empty($appointment)) {
  1793. foreach ($params['goodsContentList'] as $goods) {
  1794. $params['join_sheet_goods_id'] = $goods['goods_id'];
  1795. if (isset($goods['goods_classify']) && in_array($goods['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD'])) {
  1796. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1797. $params['order_sheet_num'] = $goods['nbr'];
  1798. // 预约表
  1799. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1800. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1801. // 入预约记录
  1802. $this->insertAppointment($params, $writeOffDate, $applyData);
  1803. }
  1804. $goods['skuId'] = $goods['sku_id'];
  1805. $goods['category'] = $goods['goods_classify'];
  1806. // 权益表
  1807. $this->insertMemberBenefit($params, $goods);
  1808. } elseif (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个
  1809. $params['packageId'] = $goods['goods_id'];
  1810. $components = GoodsComponent::with([
  1811. 'goods' => function ($query) {
  1812. $query->select('goods_id', 'goods_name', 'goods_classify');
  1813. }
  1814. ])->where('join_component_master_goods_id', $params['packageId'])
  1815. ->get()
  1816. ->toArray();
  1817. foreach ($components as $component) {
  1818. $componentJson = json_decode($component['goods_component_json'], true);
  1819. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  1820. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  1821. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  1822. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  1823. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  1824. // 入预约记录
  1825. $this->insertAppointment($params, $writeOffDate);
  1826. }
  1827. $goods['goods_id'] = $component['join_component_goods_id'];
  1828. $goods['goods_name'] = $component['goods']['goods_name'];
  1829. $goods['goods_classify'] = $component['goods']['goods_classify'];
  1830. $goods['skuId'] = $goods['sku_id'];
  1831. $goods['category'] = 'SERVICE';
  1832. // 权益表
  1833. $this->insertMemberBenefit($params, $goods);
  1834. }
  1835. }
  1836. }
  1837. }
  1838. Db::commit();
  1839. // 触发事件
  1840. if ($order->order_is_complete == 'Y' && $order->order_status_payment == 'SUCCESS') {
  1841. // 完成订单
  1842. Event::dispatch('order.complete', $params);
  1843. // 会员升级
  1844. // Event::dispatch('order_pay.member_level.up', $params['join_order_member_id']);
  1845. }
  1846. if ($order->order_status_payment == 'SUCCESS') {
  1847. // 上级提成
  1848. Event::dispatch('commission.order', $params);
  1849. // 入收支明细表
  1850. $params['inout_category'] = '标准订单收入';
  1851. Event::dispatch('statistics.inout.in', $params);
  1852. }
  1853. // 打小票
  1854. if ($order->order_status_payment == 'SUCCESS') {
  1855. if (!empty($premises) && !empty($premises->dept_id)) {
  1856. $voteData = [
  1857. 'func' => 'procActionToPrinter',
  1858. 'sign' => '',
  1859. 'data' => [
  1860. 'printer_premises' => $premises->dept_id,
  1861. 'printer_device' => ["收银"],
  1862. 'printer_action' => 'ExecPrintOrder',
  1863. 'printer_data' => [
  1864. 'order_id' => $params['orderId'],
  1865. 'order_batch' => ''
  1866. ]
  1867. ]
  1868. ];
  1869. // dump("小票参数", $voteData);
  1870. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  1871. }
  1872. }
  1873. if ($order->order_status_payment != 'SUCCESS') {
  1874. _syslog("订单", "支付异常,检查是否有轮询");
  1875. // 恢复优惠券到已占用
  1876. if (!is_array($couponUseJson)) {
  1877. $couponUseJson = json_decode($couponUseJson, true);
  1878. }
  1879. // 如果下单时就填了,不用恢复
  1880. if (empty($discountJson)) {
  1881. $this->changeOrderCouponStatus($couponUseJson, 'WAITING');
  1882. }
  1883. // 清除支付记录,恢复账户金额
  1884. // $this->restoreAccount($params['pay_detail_item']);
  1885. return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
  1886. }
  1887. _syslog("订单", "订单支付成功");
  1888. return json_success('支付成功');
  1889. } catch (\Exception $e) {
  1890. dump($e->getMessage());
  1891. Db::rollBack();
  1892. _syslog("订单", "订单支付失败");
  1893. return json_fail('支付失败');
  1894. }
  1895. }
  1896. public function restoreAccount($payDetailItem)
  1897. {
  1898. foreach ($payDetailItem as $item) {
  1899. $prepayId = '';
  1900. if ($item['order_status_payment'] == 'SUCCESS') {
  1901. if (in_array($item['pay_category'], ['MONEY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY'])) {
  1902. $prepayId = $item['pay_category'];
  1903. }
  1904. if (strpos($item['pay_category'], 'CASH') !== false || strpos($item['pay_category'], 'CARD') !== false || strpos($item['pay_category'], 'WELFARE') !== false || strpos($item['pay_category'], 'VIP') !== false) {
  1905. $prepayId = $item['pay_category'];
  1906. $account = MemberAccount::where('member_account_nbr', $prepayId)->first();
  1907. $account->member_account_expend = $account->member_account_expend - $item['order_amount_pay'];
  1908. $account->member_account_surplus = $account->member_account_surplus + $item['order_amount_pay'];
  1909. $account->save();
  1910. }
  1911. }
  1912. if (!empty($prepayId)) {
  1913. PayDetail::where('pay_prepayid', $prepayId)
  1914. ->where('join_pay_order_id', $item['orderGroupId'])
  1915. ->whereJsonContains('join_pay_object_json->order_id', $item['orderId'])
  1916. ->update(['pay_status' => 'WAITING']);
  1917. }
  1918. }
  1919. }
  1920. /**
  1921. * @Desc
  1922. * @Author Gorden
  1923. * @Date 2024/6/7 10:30
  1924. *
  1925. * @param $params
  1926. * @return void
  1927. * @throws BusinessException
  1928. */
  1929. public function insertMain($params, $wxAndAliPayStatus = 'Y')
  1930. {
  1931. try {
  1932. if (empty($params['order_extend_json'])) {
  1933. $params['order_extend_json'] = [];
  1934. } else {
  1935. if (is_json($params['order_extend_json'])) {
  1936. $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
  1937. }
  1938. }
  1939. // 账户扣款
  1940. if ($wxAndAliPayStatus == 'Y' && !empty($params['waitToPayAccount'])) {
  1941. foreach ($params['waitToPayAccount'] as $account) {
  1942. $this->deductAmount($account['nbr'], $account['amount']);
  1943. }
  1944. }
  1945. // 推荐人
  1946. $params['order_extend_json']['referee'] = $params['referee'] ?? '';
  1947. foreach ($params['goodsContentList'] as $goods) {
  1948. $discountJson = [];
  1949. if (!empty($params['order_discount_json'])) {
  1950. $discountJson = json_decode($params['order_discount_json'], true);
  1951. foreach ($discountJson as &$item) {
  1952. if (!empty($item['coupon_value'])) {
  1953. $item['coupon_value'] = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $item['coupon_value'], 2);
  1954. }
  1955. }
  1956. }
  1957. $orderId = 'OD' . date('ymdHi') . random_string(4, 'up');
  1958. $amountPay = round((floatval($goods['goods_sales_price']) * $goods['nbr'] / $params['order_amount_total']) * $params['order_amount_pay'], 2);
  1959. // $amountPay = round(floatval($goods['goods_sales_price']) * $goods['nbr'] * $params['order_ratio'], 2);
  1960. $data = [
  1961. 'order_id' => $orderId,
  1962. 'order_groupby' => $params['orderGroupId'],
  1963. 'join_order_member_id' => $params['join_order_member_id'],
  1964. 'order_name' => date('Y-m-d H:i:s') . '-订单',
  1965. 'order_amount_total' => floatval($goods['goods_sales_price']) * $goods['nbr'],
  1966. 'order_amount_pay' => $amountPay,
  1967. 'order_category' => $goods['goods_classify'],
  1968. 'order_classify' => $goods['goods_classify'],
  1969. 'order_is_complete' => $params['order_is_complete'] ?? 'N',
  1970. 'order_status_system' => $params['order_status_system'],
  1971. 'order_status_payment' => $params['order_status_payment'],
  1972. 'order_status_storage' => $params['order_status_storage'],
  1973. 'order_platform' => $params['order_platform'],
  1974. 'order_remark' => $params['order_remark'] ?? '',
  1975. 'order_discount_json' => json_encode($discountJson),
  1976. 'order_config_json' => $params['order_config_json'] ?? '[]',
  1977. 'order_express_json' => $params['order_express_json'] ?? '[]',
  1978. 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
  1979. 'order_addtimes' => time()
  1980. ];
  1981. Order::insert($data);
  1982. $sheetIds = $this->insertSheetOne($params, $goods, $orderId, $amountPay);
  1983. $this->insertPayDetailOne($params, $orderId, $amountPay, $goods);
  1984. $params['order_express_goods'] = json_encode(['sheet' => $sheetIds]);
  1985. $this->insertExpressOne($params, $orderId);
  1986. // 写到权益里
  1987. if ($params['order_status_payment'] == 'SUCCESS') {
  1988. $this->insertBenefitOne($params, $goods, $orderId);
  1989. }
  1990. }
  1991. } catch (\Exception $e) {
  1992. dump($e->getMessage() . '|' . $e->getLine());
  1993. throw new BusinessException('订单创建信息失败');
  1994. }
  1995. }
  1996. /**
  1997. * @Desc 扣除账户金额
  1998. * @Author Gorden
  1999. * @Date 2024/9/26 14:16
  2000. *
  2001. * @param $accountNbr
  2002. * @param $amount
  2003. * @return void
  2004. */
  2005. public function deductAmount($accountNbr, $amount)
  2006. {
  2007. try {
  2008. $account = MemberAccount::where('member_account_nbr', $accountNbr)->first();
  2009. $account->member_account_expend = $account->member_account_expend + $amount;
  2010. if ($account->member_account_surplus < $amount && strpos($accountNbr, 'CASH') !== false) {
  2011. $account->member_account_added = $account->member_account_added - ($amount - $account->member_account_surplus);
  2012. $account->member_account_surplus = 0;
  2013. } else {
  2014. $account->member_account_surplus = $account->member_account_surplus - $amount;
  2015. }
  2016. $account->save();
  2017. } catch (\Exception $e) {
  2018. _syslog("下单扣款", "扣款失败");
  2019. throw new BusinessException("账户扣款失败");
  2020. }
  2021. }
  2022. /**
  2023. * @Desc 打小票
  2024. * @Author Gorden
  2025. * @Date 2024/9/24 9:35
  2026. *
  2027. * @param $params
  2028. * @param $premises
  2029. * @param $orderId
  2030. * @return void
  2031. */
  2032. public function printerTicket($params, $premises, $orderId)
  2033. {
  2034. // 打小票
  2035. if ($params['order_status_payment'] == 'SUCCESS') {
  2036. if (!empty($premises) && !empty($premises->dept_id)) {
  2037. $voteData = [
  2038. 'func' => 'procActionToPrinter',
  2039. 'sign' => '',
  2040. 'data' => [
  2041. 'printer_premises' => $premises->dept_id,
  2042. 'printer_device' => ["收银"],
  2043. 'printer_action' => 'ExecPrintOrder',
  2044. 'printer_data' => [
  2045. 'order_id' => $orderId,
  2046. 'order_batch' => ''
  2047. ]
  2048. ]
  2049. ];
  2050. // dump("小票参数", $voteData);
  2051. http_post_json(getenv('VOTE_MENU_URL'), $voteData);
  2052. }
  2053. }
  2054. }
  2055. /**
  2056. * @Desc 单套包权益
  2057. * @Author Gorden
  2058. * @Date 2024/9/24 8:42
  2059. *
  2060. * @param $params
  2061. * @param $goods
  2062. * @return void
  2063. * @throws BusinessException
  2064. */
  2065. public function insertBenefitOne($params, $goods, $orderId)
  2066. {
  2067. $params['orderId'] = $orderId;
  2068. $writeOffDate = [];
  2069. $applyData = [];
  2070. if (isset($goods['goods_classify']) && $goods['goods_classify'] == 'PACKAGE' && $params['delivery'] == 'ARRIVAL') { // 一个套餐买多个
  2071. $params['packageId'] = $goods['goods_id'];
  2072. $components = GoodsComponent::with([
  2073. 'goods' => function ($query) {
  2074. $query->select('goods_id', 'goods_name', 'goods_classify');
  2075. }
  2076. ])->where('join_component_master_goods_id', $params['packageId'])
  2077. ->get()
  2078. ->toArray();
  2079. foreach ($components as $component) {
  2080. $componentJson = json_decode($component['goods_component_json'], true);
  2081. $params['join_sheet_goods_sku_id'] = $componentJson['sku_id'];
  2082. $params['benefitId'] = 'BF' . date('ymdHi') . random_string(4, 'up');
  2083. $params['order_sheet_num'] = $goods['nbr'] * $componentJson['nbr'];
  2084. $params['join_sheet_goods_id'] = $component['join_component_goods_id'];
  2085. for ($i = 0; $i < intval($params['order_sheet_num']); $i++) {
  2086. $params['appointmentId'] = 'AP' . date('ymdHi') . random_string(4, 'up');
  2087. // 入预约记录
  2088. $this->insertAppointment($params, $writeOffDate);
  2089. }
  2090. $goods['goods_id'] = $component['join_component_goods_id'];
  2091. $goods['goods_name'] = $component['goods']['goods_name'];
  2092. $goods['goods_classify'] = $component['goods']['goods_classify'];
  2093. $goods['skuId'] = $goods['sku_id'];
  2094. $goods['category'] = 'SERVICE';
  2095. // 权益表
  2096. $this->insertMemberBenefit($params, $goods);
  2097. }
  2098. }
  2099. }
  2100. /**
  2101. * @Desc
  2102. * @Author Gorden
  2103. * @Date 2024/6/7 10:25
  2104. *
  2105. * @param $params
  2106. * @return void
  2107. * @throws BusinessException
  2108. */
  2109. public function insertSheet($params)
  2110. {
  2111. try {
  2112. $orderSheetIds = [];
  2113. foreach ($params['goodsContentList'] as $goods) {
  2114. //{"unit": "份", "table": null, "premises": "15"}
  2115. $price = floatval($goods['goods_sales_price']);
  2116. $extendJson['unit'] = $goods['sku_name'];
  2117. if (isset($params['submit_premises_id'])) {
  2118. $extendJson['premises'] = $params['submit_premises_id'];
  2119. }
  2120. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2121. $extendJson['table'] = null;
  2122. }
  2123. $data = [
  2124. 'join_sheet_member_id' => $params['join_order_member_id'],
  2125. 'join_sheet_order_id' => $params['orderId'],
  2126. 'join_sheet_goods_id' => $goods['goods_id'],
  2127. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2128. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2129. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2130. 'order_sheet_num' => $goods['nbr'],
  2131. 'order_sheet_price' => $goods['goods_sales_price'],
  2132. 'order_sheet_amount' => $price * $goods['nbr'],
  2133. 'order_sheet_pay' => $price * $goods['nbr'],
  2134. 'order_sheet_task_status' => 'NONE',
  2135. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2136. 'order_sheet_addtimes' => time(),
  2137. 'order_sheet_extend_json' => json_encode($extendJson)
  2138. ];
  2139. $orderSheetId = OrderSheet::insertGetId($data);
  2140. $orderSheetIds[] = $orderSheetId;
  2141. // 减库存,规格和总库存
  2142. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2143. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2144. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2145. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2146. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2147. }
  2148. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2149. throw new BusinessException('库存不足');
  2150. }
  2151. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2152. $goodsSku->save();
  2153. }
  2154. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2155. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2156. if ($goodsRunning->goods_running_storage < 0) {
  2157. throw new BusinessException('库存不足');
  2158. }
  2159. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2160. $goodsRunning->save();
  2161. }
  2162. // return $orderSheetIds;
  2163. } catch (\support\exception\BusinessException $e) {
  2164. dump($e->getMessage() . '||' . $e->getLine());
  2165. throw new BusinessException($e->getMessage());
  2166. } catch (\Exception $e) {
  2167. dump($e->getMessage() . '||' . $e->getLine());
  2168. throw new BusinessException('订单创建失败');
  2169. }
  2170. }
  2171. /**
  2172. * @Desc 单条入库
  2173. * @Author Gorden
  2174. * @Date 2024/9/23 10:19
  2175. *
  2176. * @param $params
  2177. * @return array
  2178. * @throws BusinessException
  2179. */
  2180. public function insertSheetOne($params, $goods, $orderId, $amountPay)
  2181. {
  2182. try {
  2183. $orderSheetIds = [];
  2184. // foreach ($params['goodsContentList'] as $goods) {
  2185. //{"unit": "份", "table": null, "premises": "15"}
  2186. $price = floatval($goods['goods_sales_price']);
  2187. $extendJson['unit'] = $goods['sku_name'];
  2188. if (isset($params['submit_premises_id'])) {
  2189. $extendJson['premises'] = $params['submit_premises_id'];
  2190. }
  2191. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2192. $extendJson['table'] = null;
  2193. }
  2194. $data = [
  2195. 'join_sheet_member_id' => $params['join_order_member_id'],
  2196. 'join_sheet_order_id' => $orderId,
  2197. 'join_sheet_goods_id' => $goods['goods_id'],
  2198. 'join_sheet_goods_sku_id' => $goods['sku_id'],
  2199. 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
  2200. 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL',
  2201. 'order_sheet_num' => $goods['nbr'],
  2202. 'order_sheet_price' => $goods['goods_sales_price'],
  2203. 'order_sheet_price_pay' => round($amountPay / $goods['nbr'], 2),
  2204. 'order_sheet_amount' => $price * $goods['nbr'],
  2205. 'order_sheet_pay' => $amountPay,
  2206. 'order_sheet_task_status' => 'NONE',
  2207. 'order_sheet_remark' => $params['order_remark'] ?? '',
  2208. 'order_sheet_addtimes' => time(),
  2209. 'order_sheet_extend_json' => json_encode($extendJson)
  2210. ];
  2211. $orderSheetId = OrderSheet::insertGetId($data);
  2212. $orderSheetIds[] = $orderSheetId;
  2213. // 减库存,规格和总库存
  2214. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
  2215. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  2216. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  2217. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  2218. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  2219. }
  2220. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  2221. throw new BusinessException('库存不足');
  2222. }
  2223. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  2224. $goodsSku->save();
  2225. }
  2226. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  2227. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  2228. if ($goodsRunning->goods_running_storage < 0) {
  2229. throw new BusinessException('库存不足');
  2230. }
  2231. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
  2232. $goodsRunning->save();
  2233. // }
  2234. return $orderSheetIds;
  2235. } catch (\support\exception\BusinessException $e) {
  2236. dump($e->getMessage() . '||' . $e->getLine());
  2237. throw new BusinessException($e->getMessage());
  2238. } catch (\Exception $e) {
  2239. dump($e->getMessage() . '||' . $e->getLine());
  2240. throw new BusinessException('订单创建失败');
  2241. }
  2242. }
  2243. /**
  2244. * @Desc
  2245. * @Author Gorden
  2246. * @Date 2024/6/7 10:35
  2247. *
  2248. * @param $params
  2249. * @return void
  2250. * @throws BusinessException
  2251. */
  2252. public function insertPayDetail($params)
  2253. {
  2254. try {
  2255. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2256. $payPrepayid = $params['pay_category'];
  2257. } else if ($params['pay_category'] == 'OFFLINE') {
  2258. $payPrepayid = 'OFFLINE';
  2259. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2260. $payPrepayid = 'OFFLINE_ALIPAY';
  2261. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2262. $payPrepayid = 'OFFLINE_WXPAY';
  2263. } else if ($params['pay_category'] == 'MONEY') {
  2264. $payPrepayid = 'MONEY';
  2265. } else {
  2266. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2267. }
  2268. $data = [
  2269. 'join_pay_member_id' => $params['join_order_member_id'],
  2270. 'join_pay_order_id' => $params['orderGroupId'],
  2271. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2272. 'pay_category' => $params['goods_classify'],
  2273. 'pay_amount' => $params['order_amount_pay'],
  2274. 'pay_prepayid' => $payPrepayid,
  2275. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2276. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  2277. 'pay_json_request' => json_encode($params),
  2278. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2279. 'pay_remark' => $params['order_remark'] ?? '',
  2280. 'pay_addtimes' => time(),
  2281. ];
  2282. PayDetail::insert($data);
  2283. } catch (\Exception $e) {
  2284. dump($e->getMessage());
  2285. throw new BusinessException('创建支付记录失败');
  2286. }
  2287. }
  2288. /**
  2289. * @Desc 单条入库
  2290. * @Author Gorden
  2291. * @Date 2024/6/7 10:35
  2292. *
  2293. * @param $params
  2294. * @return void
  2295. * @throws BusinessException
  2296. */
  2297. public function insertPayDetailOne($params, $orderId, $amountPay, $goods)
  2298. {
  2299. try {
  2300. if (!empty($params['pay_detail_item'])) {
  2301. foreach ($params['pay_detail_item'] as $item) {
  2302. $data = [
  2303. 'join_pay_member_id' => $item['join_order_member_id'],
  2304. 'join_pay_order_id' => $item['orderGroupId'],
  2305. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2306. 'pay_category' => $goods['goods_classify'],
  2307. 'pay_amount' => round(($amountPay / $params['order_amount_pay']) * $item['order_amount_pay'], 2),
  2308. 'pay_prepayid' => $item['pay_category'],
  2309. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2310. 'join_pay_object_json' => !empty($item['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2311. 'pay_json_request' => json_encode($item),
  2312. 'pay_json_response' => $item['pay_json_response'] ?? '[]',
  2313. 'pay_remark' => $item['order_remark'] ?? '',
  2314. 'pay_addtimes' => time(),
  2315. ];
  2316. PayDetail::insert($data);
  2317. }
  2318. } else {
  2319. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  2320. $payPrepayid = $params['pay_category'];
  2321. } else if ($params['pay_category'] == 'OFFLINE') {
  2322. $payPrepayid = 'OFFLINE';
  2323. } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
  2324. $payPrepayid = 'OFFLINE_ALIPAY';
  2325. } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
  2326. $payPrepayid = 'OFFLINE_WXPAY';
  2327. } else if ($params['pay_category'] == 'MONEY') {
  2328. $payPrepayid = 'MONEY';
  2329. } else {
  2330. $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
  2331. }
  2332. $data = [
  2333. 'join_pay_member_id' => $params['join_order_member_id'],
  2334. 'join_pay_order_id' => $params['orderGroupId'],
  2335. 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  2336. 'pay_category' => $goods['goods_classify'],
  2337. 'pay_amount' => $amountPay,
  2338. 'pay_prepayid' => $payPrepayid,
  2339. 'pay_paytimes' => date('Y-m-d H:i:s'),
  2340. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $orderId]) : '[]',
  2341. 'pay_json_request' => json_encode($params),
  2342. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  2343. 'pay_remark' => $params['order_remark'] ?? '',
  2344. 'pay_addtimes' => time(),
  2345. ];
  2346. PayDetail::insert($data);
  2347. }
  2348. } catch (\Exception $e) {
  2349. dump($e->getMessage());
  2350. throw new BusinessException('创建支付记录失败');
  2351. }
  2352. }
  2353. /**
  2354. * @Desc
  2355. * @Author Gorden
  2356. * @Date 2024/6/7 10:50
  2357. *
  2358. * @param $params
  2359. * @return void
  2360. * @throws BusinessException
  2361. */
  2362. public function insertAppointment($params, $writeOffDate, $applyData = [])
  2363. {
  2364. try {
  2365. $data = [
  2366. 'appointment_id' => $params['appointmentId'],
  2367. 'join_appointment_member_id' => $params['join_order_member_id'],
  2368. 'join_appointment_goods_id' => $params['join_sheet_goods_id'],
  2369. 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'],
  2370. 'join_appointment_order_id' => $params['orderId'],
  2371. 'join_appointment_member_benefit_id' => $params['benefitId'],
  2372. 'appointment_classify' => $params['goods_classify'],
  2373. 'appointment_status' => 'INIT',
  2374. 'appointment_category' => 'NORMAL',
  2375. 'appointment_platform' => 'SYSTEM',
  2376. 'appointment_addtimes' => time(),
  2377. 'appointment_datetime' => '',
  2378. 'appointment_apply_datetime' => '',
  2379. 'appointment_apply_json' => '[]',
  2380. 'appointment_done_datetime' => '',
  2381. 'appointment_remark' => $params['order_remark'] ?? '',
  2382. 'appointment_done_json' => '[]'
  2383. ];
  2384. Appointment::insert($data);
  2385. } catch (\Exception $e) {
  2386. dump($e->getMessage());
  2387. throw new BusinessException("创建权益记录失败");
  2388. }
  2389. }
  2390. /**
  2391. * @Desc
  2392. * @Author Gorden
  2393. * @Date 2024/6/7 11:05
  2394. *
  2395. * @param $params
  2396. * @param $goods
  2397. * @return void
  2398. * @throws BusinessException
  2399. */
  2400. public function insertMemberBenefit($params, $goods)
  2401. {
  2402. try {
  2403. $data = [
  2404. 'member_benefit_id' => $params['benefitId'],
  2405. 'join_benefit_member_id' => $params['join_order_member_id'],
  2406. 'join_benefit_package_id' => $params['packageId'] ?? '',
  2407. 'join_benefit_goods_id' => $goods['goods_id'],
  2408. 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '',
  2409. 'join_benefit_order_id' => $params['orderId'],
  2410. 'member_benefit_status' => 'ACTIVED',
  2411. 'member_benefit_category' => $goods['category'],
  2412. 'member_benefit_name' => $goods['goods_name'],
  2413. 'member_benefit_limit_count' => $params['order_sheet_num'],
  2414. 'member_benefit_used_count' => 0,
  2415. 'member_benefit_remark' => $params['order_remark'] ?? '',
  2416. 'member_benefit_addtimes' => time()
  2417. ];
  2418. MemberBenefit::insert($data);
  2419. } catch (\Exception $e) {
  2420. dump($e->getMessage());
  2421. throw new BusinessException('创建会员权益失败');
  2422. }
  2423. }
  2424. public function saveExpress($params, $orderId)
  2425. {
  2426. try {
  2427. $express = new OrderExpress();
  2428. $express->order_express_type = $params['order_express_type'];
  2429. $express->join_express_order_id = $orderId;
  2430. $express->join_express_dept_id = $params['submit_premises_id'] ?? 0;
  2431. $express->order_express_goods = $params['order_express_goods'];
  2432. $express->order_express_city = $params['order_express_city'];
  2433. $express->order_express_address = $params['order_express_address'];
  2434. $express->order_express_mobile = $params['order_express_mobile'] ?? '';
  2435. $express->order_express_telephone = $params['order_express_telephone'] ?? '';
  2436. $express->order_express_person = $params['order_express_person'] ?? '';
  2437. $express->order_express_company = $params['dept_premises_id'] ?? '';
  2438. $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]';
  2439. $express->order_express_addtimes = time();
  2440. $express->save();
  2441. } catch (\Exception $e) {
  2442. dump($e->getMessage());
  2443. throw new BusinessException('物流信息保存失败');
  2444. }
  2445. }
  2446. /**
  2447. * @Desc 修改优惠券状态
  2448. * @Author Gorden
  2449. * @Date 2024/9/19 9:03
  2450. *
  2451. * @param $coupon
  2452. * @param $status
  2453. * @return void
  2454. */
  2455. private function changeOrderCouponStatus($coupon, $status)
  2456. {
  2457. if (!empty($coupon) && is_array($coupon)) {
  2458. $updateData['coupon_detail_status'] = $status;
  2459. if ($status == 'ACTIVED' || $status == 'WAITING') {
  2460. $updateData['coupon_detail_used_datetime'] = '';
  2461. } elseif ($status == 'USED') {
  2462. $updateData['coupon_detail_used_datetime'] = date('Y-m-d H:i:s');
  2463. }
  2464. foreach ($coupon as $item) {
  2465. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2466. foreach ($item['coupon_detail_id'] as $detailId) {
  2467. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2468. ->where('coupon_detail_id', $detailId)->update($updateData);
  2469. }
  2470. }
  2471. }
  2472. }
  2473. }
  2474. private function discountRecord($orderDiscountJson, $params)
  2475. {
  2476. $json = [];
  2477. if (!empty($orderDiscountJson)) {
  2478. $json = json_decode($orderDiscountJson, true);
  2479. }
  2480. try {
  2481. if (!empty($params['preferential']) && in_array('wipe', $params['preferential'])) {
  2482. if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) {
  2483. throw new BusinessException("抹零后实际支付金额错误");
  2484. }
  2485. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2486. $couponClassifyDesc = $couponClassify = '抹零';
  2487. } elseif (!empty($params['preferential']) && in_array('custom', $params['preferential'])) {
  2488. if (sprintf("%.2f", $params['order_amount_total'] - $params['order_discount_amount']) != sprintf("%.2f", $params['order_amount_pay'])) {
  2489. throw new BusinessException("餐厅前台优惠后实际支付金额错误");
  2490. }
  2491. $couponClassifyDesc = $couponClassify = '餐厅前台优惠';
  2492. } else if (!empty($params['preferential']) && intval($params['preferential'][0]) < 100 && intval($params['preferential'][0]) >= 50) {
  2493. if (($params['order_amount_total'] * intval($params['preferential'][0])) / 100 != $params['order_amount_pay']) {
  2494. throw new BusinessException("折扣后实际支付金额错误");
  2495. }
  2496. $couponClassify = '折扣';
  2497. $couponClassifyDesc = intval($params['preferential'][0]) / 10 . '折';
  2498. $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay'];
  2499. } else {
  2500. return $json;
  2501. }
  2502. $json[date('Y-m-d H:i:s')] = [
  2503. 'coupon_id' => $params['coupon_id'] ?? null,
  2504. 'coupon_value' => $params['order_discount_amount'] ?? '',
  2505. 'coupon_classify' => $couponClassify,
  2506. 'coupon_detail_id' => [$couponClassifyDesc],
  2507. 'coupon_classify_en' => $params['preferential']
  2508. ];
  2509. return $json;
  2510. } catch (BusinessException $e) {
  2511. throw new BusinessException($e->getMessage());
  2512. } catch (\Exception $e) {
  2513. dump($e->getMessage());
  2514. throw new BusinessException("优惠数据错误");
  2515. }
  2516. }
  2517. /**
  2518. * @Desc 入配送记录
  2519. * @Author Gorden
  2520. * @Date 2024/9/23 10:45
  2521. *
  2522. * @param $params
  2523. * @return void
  2524. * @throws BusinessException
  2525. */
  2526. public function insertExpressOne($params, $orderId)
  2527. {
  2528. if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') {
  2529. $params['order_express_type'] = '配送';
  2530. // 入配送
  2531. $this->saveExpress($params, $orderId);
  2532. } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') {
  2533. $params['order_express_type'] = '自提';
  2534. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2535. if (!$premises) {
  2536. throw new BusinessException('自提门店不存在');
  2537. }
  2538. $params['order_express_city'] = $premises->dept_city;
  2539. $params['order_express_address'] = $premises->dept_address;
  2540. $params['order_express_telephone'] = $premises->dept_telephone;
  2541. $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]);
  2542. $this->saveExpress($params, $orderId);
  2543. } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') {
  2544. $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first();
  2545. $params['order_express_type'] = '到店';
  2546. if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
  2547. $params['order_express_type'] = '堂食';
  2548. }
  2549. if (!$premises) {
  2550. throw new BusinessException('门店不存在');
  2551. }
  2552. $params['order_express_city'] = $premises->dept_city;
  2553. $params['order_express_address'] = $premises->dept_address;
  2554. $params['order_express_telephone'] = $premises->dept_telephone;
  2555. $this->saveExpress($params, $orderId);
  2556. }
  2557. }
  2558. /**
  2559. * @Desc 释放下单时选的优惠券
  2560. * @Author Gorden
  2561. * @Date 2024/9/19 9:56
  2562. *
  2563. * @param $coupon
  2564. * @return false|string
  2565. */
  2566. private function releaseCoupon($coupon)
  2567. {
  2568. if (!empty($coupon) && is_array($coupon)) {
  2569. $updateData = [
  2570. 'coupon_detail_status' => 'ACTIVED',
  2571. 'coupon_detail_used_datetime' => ''
  2572. ];
  2573. foreach ($coupon as $key => $item) {
  2574. if (!empty($item['coupon_id']) && !empty($item['coupon_detail_id'])) {
  2575. foreach ($item['coupon_detail_id'] as $detailId) {
  2576. if (substr($detailId, 0, 4) == 'CUDT') {
  2577. CouponDetail::where('join_detail_coupon_id', $item['coupon_id'])
  2578. ->where('coupon_detail_id', $detailId)
  2579. ->where('coupon_detail_status', 'WAITING')
  2580. ->update($updateData);
  2581. }
  2582. }
  2583. unset($coupon[$key]);
  2584. }
  2585. }
  2586. }
  2587. return json_encode($coupon);
  2588. }
  2589. }