PackagesController.php 134 KB

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