ServicesController.php 136 KB

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