ServicesController.php 139 KB

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