PackagesController.php 137 KB

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