PackagesController.php 134 KB

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