PackagesController.php 135 KB

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