PackagesController.php 135 KB

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