ServicesController.php 131 KB

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