GoodsController.php 127 KB

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