StoreOrder.php 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2017/12/20
  6. */
  7. namespace app\models\store;
  8. use app\admin\model\system\ShippingTemplatesFree;
  9. use app\admin\model\system\ShippingTemplatesRegion;
  10. use app\phpPay\AopClient;
  11. use crmeb\basic\BaseModel;
  12. use think\db\exception\DataNotFoundException;
  13. use think\db\exception\DbException;
  14. use think\db\exception\ModelNotFoundException;
  15. use think\facade\Cache;
  16. use crmeb\traits\ModelTrait;
  17. use think\facade\Log;
  18. use app\models\system\SystemStore;
  19. use app\models\store\StoreProduct;
  20. use app\models\routine\RoutineTemplate;
  21. use app\models\user\{User, UserAddress, UserBill, UserSpread, WechatUser};
  22. use crmeb\services\{
  23. SystemConfigService, WechatTemplateService, workerman\ChannelService
  24. };
  25. use crmeb\repositories\{
  26. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  27. };
  28. use app\admin\model\system\ShippingTemplates;
  29. /**
  30. * TODO 订单Model
  31. * Class StoreOrder
  32. * @package app\models\store
  33. */
  34. class StoreOrder extends BaseModel
  35. {
  36. /**
  37. * 数据表主键
  38. * @var string
  39. */
  40. protected $pk = 'id';
  41. /**
  42. * 模型名称
  43. * @var string
  44. */
  45. protected $name = 'store_order';
  46. use ModelTrait;
  47. protected $insert = ['add_time'];
  48. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付'];
  49. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  50. protected function setAddTimeAttr()
  51. {
  52. return time();
  53. }
  54. protected function setCartIdAttr($value)
  55. {
  56. return is_array($value) ? json_encode($value) : $value;
  57. }
  58. protected function getCartIdAttr($value)
  59. {
  60. return json_decode($value, true);
  61. }
  62. /**获取订单组信息
  63. * @param $cartInfo
  64. * @return array
  65. */
  66. public static function getOrderPriceGroup($cartInfo, $addr)
  67. {
  68. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  69. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  70. $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总积分
  71. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  72. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  73. //如果满额包邮等于0
  74. if (!$storeFreePostage) {
  75. $storePostage = 0;
  76. } else {
  77. if ($addr) {
  78. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  79. $temp_num = [];
  80. foreach ($cartInfo as $cart) {
  81. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  82. if (!$temp) $temp = ShippingTemplates::get(1);
  83. if ($temp->getData('type') == 1) {
  84. $num = $cart['cart_num'];
  85. } elseif ($temp->getData('type') == 2) {
  86. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  87. } else {
  88. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  89. }
  90. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  91. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  92. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  93. if (!$region) {
  94. return self::setErrorInfo('运费模板不存在');
  95. }
  96. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  97. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  98. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  99. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  100. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  101. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  102. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  103. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  104. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  105. } else {
  106. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  107. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  108. }
  109. }
  110. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  111. $type = $storePostage = 0;
  112. foreach ($temp_num as $k => $v) {
  113. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  114. unset($temp_num[$k]);
  115. }
  116. }
  117. foreach ($temp_num as $v) {
  118. if ($type == 0) {
  119. if ($v['number'] <= $v['first']) {
  120. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  121. } else {
  122. if ($v['continue'] <= 0) {
  123. $storePostage = $storePostage;
  124. } else {
  125. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  126. }
  127. }
  128. $type = 1;
  129. } else {
  130. if ($v['continue'] <= 0) {
  131. $storePostage = $storePostage;
  132. } else {
  133. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  134. }
  135. }
  136. }
  137. } else {
  138. $storePostage = 0;
  139. }
  140. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  141. }
  142. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
  143. }
  144. /**获取某个字段总金额
  145. * @param $cartInfo
  146. * @param $key 键名
  147. * @return int|string
  148. */
  149. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  150. {
  151. $SumPrice = 0;
  152. foreach ($cartInfo as $cart) {
  153. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  154. }
  155. return $SumPrice;
  156. }
  157. /**
  158. * 拼团
  159. * @param $cartInfo
  160. * @return array
  161. */
  162. public static function getCombinationOrderPriceGroup($cartInfo)
  163. {
  164. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  165. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  166. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  167. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  168. if (!$storeFreePostage) {
  169. $storePostage = 0;
  170. } else {
  171. foreach ($cartInfo as $cart) {
  172. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  173. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  174. }
  175. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  176. }
  177. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  178. }
  179. /**
  180. * 拼团价格
  181. * @param $cartInfo
  182. * @return float
  183. */
  184. public static function getCombinationOrderTotalPrice($cartInfo)
  185. {
  186. $totalPrice = 0;
  187. foreach ($cartInfo as $cart) {
  188. if ($cart['combination_id']) {
  189. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  190. }
  191. }
  192. return (float)$totalPrice;
  193. }
  194. /**
  195. * 缓存订单信息
  196. * @param $uid
  197. * @param $cartInfo
  198. * @param $priceGroup
  199. * @param array $other
  200. * @param int $cacheTime
  201. * @return string
  202. * @throws \Psr\SimpleCache\InvalidArgumentException
  203. */
  204. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  205. {
  206. do {
  207. $key = md5(time() . rand(100000, 999999));
  208. } while (Cache::has('user_order_' . $uid . $key));
  209. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  210. return $key;
  211. }
  212. /**
  213. * 获取订单缓存信息
  214. * @param $uid
  215. * @param $key
  216. * @return mixed|null
  217. * @throws \Psr\SimpleCache\InvalidArgumentException
  218. */
  219. public static function getCacheOrderInfo($uid, $key)
  220. {
  221. $cacheName = 'user_order_' . $uid . $key;
  222. if (!Cache::has($cacheName)) return null;
  223. return Cache::get($cacheName);
  224. }
  225. /**
  226. * 删除订单缓存
  227. * @param $uid
  228. * @param $key
  229. */
  230. public static function clearCacheOrderInfo($uid, $key)
  231. {
  232. Cache::delete('user_order_' . $uid . $key);
  233. }
  234. /**
  235. * 生成订单
  236. * @param $uid
  237. * @param $key
  238. * @param $addressId
  239. * @param $payType
  240. * @param bool $useIntegral
  241. * @param int $couponId
  242. * @param string $mark
  243. * @param int $combinationId
  244. * @param int $pinkId
  245. * @param int $seckill_id
  246. * @param int $bargain_id
  247. * @param bool $test
  248. * @param int $isChannel
  249. * @param int $shipping_type
  250. * @param string $real_name
  251. * @param string $phone
  252. * @return StoreOrder|bool|\think\Model
  253. * @throws \think\Exception
  254. * @throws DataNotFoundException
  255. * @throws ModelNotFoundException
  256. * @throws \think\exception\DbException
  257. */
  258. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0)
  259. {
  260. self::beginTrans();
  261. try {
  262. $shipping_type = (int)$shipping_type;
  263. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  264. if ($offlinePayStatus == 2) unset(self::$payType['offline']);
  265. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  266. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  267. $userInfo = User::getUserInfo($uid);
  268. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  269. $cartGroup = self::getCacheOrderInfo($uid, $key);
  270. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  271. $cartInfo = $cartGroup['cartInfo'];
  272. $priceGroup = $cartGroup['priceGroup'];
  273. $other = $cartGroup['other'];
  274. $payPrice = (float)$priceGroup['totalPrice'];
  275. $payIntegral = (float)$priceGroup['totalIntegral'];
  276. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  277. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  278. $payPostage = 0;
  279. } else {
  280. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  281. }
  282. if ($shipping_type === 1) {
  283. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  284. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  285. return self::setErrorInfo('地址选择有误!', true);
  286. } else {
  287. if ((!$real_name || !$phone) && !$test) return self::setErrorInfo('请填写姓名和电话', true);
  288. $addressInfo['real_name'] = $real_name;
  289. $addressInfo['phone'] = $phone;
  290. $addressInfo['province'] = '';
  291. $addressInfo['city'] = '';
  292. $addressInfo['district'] = '';
  293. $addressInfo['detail'] = '';
  294. }
  295. $cartIds = [];
  296. $totalNum = 0;
  297. $gainIntegral = 0;
  298. $whiteIntegral = 0;
  299. $businessIntegral = 0;
  300. foreach ($cartInfo as $cart) {
  301. $cartIds[] = $cart['id'];
  302. $totalNum += $cart['cart_num'];
  303. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  304. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  305. if (!$combinationId) $combinationId = $cart['combination_id'];
  306. $storeProduct = StoreProduct::where('id',$cart['productInfo']['id'])->find();
  307. if($storeProduct['cate_id'] == 4 and $useIntegral)return self::setErrorInfo('该商品不能抵扣', true);
  308. // if ($cart['productInfo']['cate_id'] == 4 and $useIntegral) return self::setErrorInfo('该商品不能抵扣', true);
  309. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  310. $whiteInfoGainIntegral = isset($cart['productInfo']['white_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['white_integral'], 2) : 0;
  311. $businessGainIntegral = isset($cart['productInfo']['business_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['business_integral'], 2) : 0;
  312. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  313. $whiteIntegral = bcadd($whiteIntegral, $whiteInfoGainIntegral, 2);
  314. $businessIntegral = bcadd($businessIntegral, $businessGainIntegral, 2);
  315. }
  316. $deduction = $seckill_id || $bargain_id || $combinationId;
  317. if ($deduction) {
  318. $couponId = 0;
  319. $useIntegral = false;
  320. if (!$test) {
  321. unset(self::$payType['offline']);
  322. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  323. }
  324. }
  325. //使用优惠劵
  326. $res1 = true;
  327. if ($couponId) {
  328. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  329. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  330. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  331. $flag = false;
  332. foreach ($coupons as $coupon) {
  333. if ($coupon['id'] == $couponId) {
  334. $flag = true;
  335. continue;
  336. }
  337. }
  338. if (!$flag)
  339. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  340. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  341. $res1 = StoreCouponUser::useCoupon($couponId);
  342. $couponPrice = $couponInfo['coupon_price'];
  343. } else {
  344. $couponId = 0;
  345. $couponPrice = 0;
  346. }
  347. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  348. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  349. $store_self_mention = sys_config('store_self_mention') ?? 0;
  350. if (!$store_self_mention) $shipping_type = 1;
  351. if ($shipping_type === 1) {
  352. //是否包邮
  353. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  354. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  355. } else if ($shipping_type === 2) {
  356. //门店自提没有邮费支付
  357. $priceGroup['storePostage'] = 0;
  358. $payPostage = 0;
  359. if (!$storeId && !$test) {
  360. return self::setErrorInfo('请选择门店', true);
  361. }
  362. }
  363. //积分抵扣
  364. $res2 = true;
  365. $SurplusIntegral = $userInfo['integral'];
  366. if ($payIntegral > 0) {
  367. if ($userInfo['integral'] < $payIntegral) {
  368. return self::setErrorInfo('积分不足', true);
  369. } else {
  370. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $payIntegral, 'uid');
  371. }
  372. $SurplusIntegral = bcsub($userInfo['integral'], $payIntegral, 2);
  373. $res2 = $res2 && false != UserBill::expend('积分商品', $uid, 'integral', 'integral_product', $payIntegral, $key, $SurplusIntegral, '购买积分商品使用' . $payIntegral . '积分');
  374. }
  375. //积分抵扣
  376. if ($useIntegral && $SurplusIntegral > 0) {
  377. $deductionPrice = (float)bcmul($SurplusIntegral, $other['integralRatio'], 2);
  378. if ($deductionPrice < $payPrice) {
  379. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  380. $usedIntegral = $SurplusIntegral;
  381. $SurplusIntegral = 0;
  382. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  383. } else {
  384. $deductionPrice = $payPrice;
  385. $usedIntegral = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  386. $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
  387. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  388. $payPrice = 0;
  389. }
  390. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral) . '积分抵扣' . floatval($deductionPrice) . '元');
  391. } else {
  392. $deductionPrice = 0;
  393. $usedIntegral = 0;
  394. }
  395. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  396. if ($payPrice <= 0) $payPrice = 0;
  397. if ($test) {
  398. self::rollbackTrans();
  399. return [
  400. 'total_price' => $priceGroup['totalPrice'],
  401. 'pay_price' => $payPrice,
  402. 'pay_postage' => $payPostage,
  403. 'coupon_price' => $couponPrice,
  404. 'deduction_price' => $deductionPrice,
  405. 'totalIntegral' => $payIntegral,
  406. 'SurplusIntegral' => $SurplusIntegral,
  407. ];
  408. }
  409. $orderDate = StoreOrder::where('uid', $uid)->where('paid', 1)->where('pay_type', '<>', 'integral')->where('add_time', '>=', strtotime('2020-8-5'))->where('cumulative', '<', 2000)->find();
  410. if ($payPrice < 2000 and $orderDate){
  411. $orderDate['order_id'] = self::getNewOrderId();
  412. $orderDate['pay_price'] = $payPrice;
  413. $orderDate['gain_integral'] = $gainIntegral;
  414. $orderDate['white_integral'] = $whiteIntegral;
  415. $orderDate['business_integral'] = $businessIntegral;
  416. $orderDate->save();
  417. StoreOrderStatus::status($orderDate['id'], 'cache_key_create_order', '订单累计'.$payPrice);
  418. $order = $orderDate;
  419. $res4 = true;
  420. }else{
  421. $orderInfo = [
  422. 'uid' => $uid,
  423. 'order_id' => $test ? 0 : self::getNewOrderId(),
  424. 'real_name' => $addressInfo['real_name'],
  425. 'user_phone' => $addressInfo['phone'],
  426. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  427. 'cart_id' => $cartIds,
  428. 'total_num' => $totalNum,
  429. 'total_price' => $priceGroup['totalPrice'],
  430. 'total_postage' => $priceGroup['storePostage'],
  431. 'coupon_id' => $couponId,
  432. 'coupon_price' => $couponPrice,
  433. 'pay_price' => $payPrice,
  434. 'pay_postage' => $payPostage,
  435. 'deduction_price' => $deductionPrice,
  436. 'paid' => 0,
  437. 'pay_type' => $payType,
  438. 'use_integral' => $usedIntegral + $payIntegral,
  439. 'gain_integral' => $gainIntegral,
  440. 'white_integral' => $whiteIntegral,
  441. 'business_integral' => $businessIntegral,
  442. 'mark' => htmlspecialchars($mark),
  443. 'combination_id' => $combinationId,
  444. 'pink_id' => $pinkId,
  445. 'seckill_id' => $seckill_id,
  446. 'bargain_id' => $bargain_id,
  447. 'cost' => $priceGroup['costPrice'],
  448. 'is_channel' => $isChannel,
  449. 'add_time' => time(),
  450. 'unique' => $key,
  451. 'shipping_type' => $shipping_type,
  452. 'freight_price' => 0,
  453. 'refund_price' => 0,
  454. 'cumulative' => 0
  455. ];
  456. if ($shipping_type === 2) {
  457. $orderInfo['verify_code'] = self::getStoreCode();
  458. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  459. if (!$orderInfo['store_id']) return self::setErrorInfo('暂无门店无法选择门店自提!', true);
  460. }
  461. $order = self::create($orderInfo);
  462. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  463. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  464. //保存购物车商品信息
  465. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  466. }
  467. $res5 = true;
  468. foreach ($cartInfo as $cart) {
  469. //减库存加销量
  470. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  471. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  472. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  473. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  474. }
  475. //购物车状态修改
  476. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  477. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  478. //自动设置默认地址
  479. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  480. self::clearCacheOrderInfo($uid, $key);
  481. self::commitTrans();
  482. return $order;
  483. } catch (\PDOException $e) {
  484. self::rollbackTrans();
  485. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  486. } catch (\Exception $e) {
  487. self::rollbackTrans();
  488. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  489. }
  490. }
  491. /**
  492. * 回退积分
  493. * @param $order 订单信息
  494. * @return bool
  495. */
  496. public static function RegressionIntegral($order)
  497. {
  498. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  499. if ($order['use_integral'] <= 0) return true;
  500. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  501. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  502. if (!$res) return self::setErrorInfo('回退积分增加失败');
  503. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  504. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  505. }
  506. /**
  507. * 回退库存和销量
  508. * @param $order 订单信息
  509. * @return bool
  510. * @throws DataNotFoundException
  511. * @throws ModelNotFoundException
  512. * @throws \think\exception\DbException
  513. */
  514. public static function RegressionStock($order)
  515. {
  516. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  517. $combinationId = $order['combination_id'];
  518. $seckill_id = $order['seckill_id'];
  519. $bargain_id = $order['bargain_id'];
  520. $res5 = true;
  521. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  522. foreach ($cartInfo as $cart) {
  523. //增库存减销量
  524. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  525. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  526. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  527. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  528. }
  529. return $res5;
  530. }
  531. /**
  532. * 回退优惠卷
  533. * @param $order 订单信息
  534. * @return bool
  535. */
  536. public static function RegressionCoupon($order)
  537. {
  538. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  539. $res = true;
  540. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  541. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  542. }
  543. return $res;
  544. }
  545. /**
  546. * 取消订单
  547. * @param string order_id 订单id
  548. * @param $uid
  549. * @return bool
  550. * @throws DataNotFoundException
  551. * @throws ModelNotFoundException
  552. * @throws \think\exception\DbException
  553. */
  554. public static function cancelOrder($order_id, $uid)
  555. {
  556. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  557. if (!$order) return self::setErrorInfo('没有查到此订单');
  558. self::beginTrans();
  559. try {
  560. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  561. $order->is_del = 1;
  562. if ($res && $order->save()) {
  563. self::commitTrans();
  564. return true;
  565. } else
  566. return false;
  567. } catch (\Exception $e) {
  568. self::rollbackTrans();
  569. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  570. }
  571. }
  572. /**
  573. * 生成订单唯一id
  574. * @param $uid 用户uid
  575. * @return string
  576. */
  577. public static function getNewOrderId()
  578. {
  579. do {
  580. list($msec, $sec) = explode(' ', microtime());
  581. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  582. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  583. } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  584. return $orderId;
  585. }
  586. /**
  587. * 修改订单号
  588. * @param $orderId
  589. * @return string
  590. */
  591. public static function changeOrderId($orderId)
  592. {
  593. $ymd = substr($orderId, 2, 8);
  594. $key = substr($orderId, 16);
  595. return 'wx' . $ymd . date('His') . $key;
  596. }
  597. /**
  598. * 查找购物车里的所有产品标题
  599. * @param $cartId 购物车id
  600. * @return bool|string
  601. */
  602. public static function getProductTitle($cartId)
  603. {
  604. $title = '';
  605. try {
  606. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  607. foreach ($orderCart as $item) {
  608. if (isset($item['cart_info']['productInfo']['store_name'])) {
  609. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  610. }
  611. }
  612. unset($item);
  613. if (!$title) {
  614. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  615. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  616. foreach ($productlist as $item) {
  617. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  618. }
  619. }
  620. if ($title) $title = substr($title, 0, strlen($title) - 1);
  621. unset($item);
  622. } catch (\Exception $e) {
  623. }
  624. return $title;
  625. }
  626. /**
  627. * 获取门店自提唯一核销码
  628. * @return bool|string
  629. */
  630. public static function getStoreCode()
  631. {
  632. list($msec, $sec) = explode(' ', microtime());
  633. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  634. if (strlen($num) < 12)
  635. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  636. else
  637. $num = substr($num, 0, 12);
  638. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  639. return $num;
  640. }
  641. /**
  642. * 余额支付
  643. * @param $order_id
  644. * @param $uid
  645. * @param string $formId
  646. * @return bool
  647. * @throws \think\Exception
  648. * @throws DataNotFoundException
  649. * @throws ModelNotFoundException
  650. * @throws \think\exception\DbException
  651. */
  652. public static function yuePay($order_id, $uid, $formId = '')
  653. {
  654. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  655. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  656. // if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  657. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  658. $userInfo = User::getUserInfo($uid);
  659. if ($userInfo['now_money'] < $orderInfo['pay_price'])
  660. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])]);
  661. self::beginTrans();
  662. $res1 = false !== User::bcDec($uid, 'now_money', $orderInfo['pay_price'], 'uid');
  663. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  664. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  665. try {
  666. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  667. } catch (\Exception $e) {
  668. self::rollbackTrans();
  669. return self::setErrorInfo($e->getMessage());
  670. }
  671. $res = $res1 && $res2 && $res3;
  672. self::checkTrans($res);
  673. return $res;
  674. }
  675. /**
  676. * 微信支付 为 0元时
  677. * @param $order_id
  678. * @param $uid
  679. * @param string $formId
  680. * @return bool
  681. * @throws \think\Exception
  682. * @throws DataNotFoundException
  683. * @throws ModelNotFoundException
  684. * @throws \think\exception\DbException
  685. */
  686. public static function appPay($order, $uid, $formId = '')
  687. {
  688. $privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL8qMJyWMB0irskcrt6cZ1iCu8F0jwIXMlK3julf8oRjkzh0DS14f3YtVPJSjcIQE/5HxFE6q0zybzw6HeF5PdfLgqkxBHbUpVzQOxl/VlHlsID3TH4RA3/VMJlwb0gvf8jBhZLGW2RB8fs5wB/9oihsNUEMC/hheucET0sPUdKjAgMBAAECgYAk0eyBDJCB3B9MT0EDUZ66NpwRW/D7lxozQnW9T6S3iTJfCkNLgc0TJxIYhnwVZ+Fh9dLDToiWDpAMSqlct2yIocRgHQGuTVcHTcHgy7OAYBTByduOv2wyW3k04c6jFlBGjq6n5vzJ2d4PWo2LRUTEd6y3g9P+uH/p7hNZENs6iQJBAOLIt8E/7SPp/EI5HNPlUvttFu7+9Jdi0KYaA7VtHUiWaJBdOTXF6jYqI7+kzs0F5C0ndSS4Xq1cS/upKqREw7UCQQDXysINwawLhVEVyBhr/4Zv/WikEeZ2GZnLdZI98uDWvaIqRzmhXLHdYXtZzVJ4qoJBQr6wo+EpbdUjML2WYmP3AkEAiJlj7XgG69H9ixoBnjSMZjtQTAav5xuzF8mloDsoH1fRhdtRIW2j5Jo/TCkGE4JP7U7OBZ80D/H/Joe/0pBE3QJAHfM+S7p9rnuqbWOAQD0O46xAQcVaPzn+ZobC7WYwXp2jTErmbMb4yMkm3afpsmW3/mbNIKceMSnVUzUImz68sQJBAML2F+TD/OG0BH2d4LbyjSuHp/MZlQeZkogrkJ3rBPd6Alz9YGAMWDiI+lptAAMIM8Ih8LT5VzDiuqN2L+4eoz4=";
  689. $sxfPublic = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjo1+KBcvwDSIo+nMYLeOJ19Ju4ii0xH66ZxFd869EWFWk/EJa3xIA2+4qGf/Ic7m7zi/NHuCnfUtUDmUdP0JfaZiYwn+1Ek7tYAOc1+1GxhzcexSJLyJlR2JLMfEM+rZooW4Ei7q3a8jdTWUNoak/bVPXnLEVLrbIguXABERQ0Ze0X9Fs0y/zkQFg8UjxUN88g2CRfMC6LldHm7UBo+d+WlpOYH7u0OTzoLLiP/04N1cfTgjjtqTBI7qkOGxYs6aBZHG1DJ6WdP+5w+ho91sBTVajsCxAaMoExWQM2ipf/1qGdsWmkZScPflBqg7m0olOD87ymAVP/3Tcbvi34bDfwIDAQAB";
  690. $aopClient = new AopClient();
  691. $array = [
  692. //业务参数
  693. "mno"=> $order['order_id'], //商户编号
  694. "ordNo"=> $order['order_id'], //商户订单号
  695. ];
  696. $reqBean = [
  697. "orgId" => "46706760",
  698. "reqData"=>$array,
  699. "reqId" => $order['order_id'],
  700. "signType" => "RSA",
  701. "timestamp" => date("Y-m-d h:i:s"),
  702. "version" => "1.0",
  703. ];
  704. $signContent = $aopClient->generateSign($reqBean,$privateKey);
  705. $sign =["sign" => $signContent];
  706. $reqStr = array_merge($reqBean, $sign);
  707. $reqStr = json_encode($reqStr,320);
  708. $requestUrl = 'https://openapi-test.tianquetech.com/order/jsapiScan';
  709. $resp = $aopClient->curl($requestUrl, $reqStr);
  710. $result = json_decode($resp,320);
  711. halt($result);
  712. $signResult = $result["sign"];
  713. // result.remove("sign");
  714. unset($result["sign"]);
  715. // String resultStr = RSASignature.getOrderContent(result);
  716. //sign
  717. /// String resultSign = RSASignature.encryptBASE64(RSASignature.sign(signContent, privateKey));
  718. $signContent = $aopClient->getSignContent($result);
  719. $verify = $aopClient->verify($signContent, $signResult,$sxfPublic);
  720. //组装加密串
  721. if ($verify) {
  722. echo("验签成功");
  723. }else{
  724. echo("验签失败");
  725. }
  726. }
  727. /**
  728. * 微信支付 为 0元时
  729. * @param $order_id
  730. * @param $uid
  731. * @param string $formId
  732. * @return bool
  733. * @throws \think\Exception
  734. * @throws DataNotFoundException
  735. * @throws ModelNotFoundException
  736. * @throws \think\exception\DbException
  737. */
  738. public static function jsPayPrice($order_id, $uid, $formId = '')
  739. {
  740. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  741. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  742. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  743. $userInfo = User::getUserInfo($uid);
  744. self::beginTrans();
  745. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  746. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  747. $res = $res1 && $res2;
  748. self::checkTrans($res);
  749. return $res;
  750. }
  751. /**
  752. * 用户申请退款
  753. * @param $uni
  754. * @param $uid
  755. * @param string $refundReasonWap
  756. * @return bool
  757. */
  758. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  759. {
  760. $order = self::getUserOrderDetail($uid, $uni);
  761. if (!$order) return self::setErrorInfo('支付订单不存在!');
  762. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  763. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  764. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  765. self::beginTrans();
  766. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  767. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  768. $res = $res1 && $res2;
  769. self::checkTrans($res);
  770. if (!$res)
  771. return self::setErrorInfo('申请退款失败!');
  772. else {
  773. try {
  774. if (in_array($order['is_channel'], [0, 2])) {
  775. //公众号发送模板消息通知客服
  776. WechatTemplateService::sendAdminNoticeTemplate([
  777. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  778. 'keyword1' => '退款申请',
  779. 'keyword2' => '已支付',
  780. 'keyword3' => date('Y/m/d H:i', time()),
  781. 'remark' => '请及时处理'
  782. ]);
  783. }
  784. if (in_array($order['is_channel'], [1, 2])) {
  785. //小程序 发送模板消息
  786. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  787. }
  788. //通知后台消息提醒
  789. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  790. } catch (\Exception $e) {
  791. }
  792. //发送短信
  793. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  794. return true;
  795. }
  796. }
  797. /**
  798. * //TODO 支付成功后
  799. * @param $orderId
  800. * @param string $paytype
  801. * @param string $formId
  802. * @return bool
  803. * @throws DataNotFoundException
  804. * @throws DbException
  805. * @throws ModelNotFoundException
  806. */
  807. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  808. {
  809. $order = self::where('order_id', $orderId)->find();
  810. $resPink = true;
  811. $paid = $order['paid'];
  812. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time(), 'is_del' => 0, 'is_system_del' => 0, 'mark' => '', 'cumulative' => $order['pay_price']+$order['cumulative'], 're_order_id' => $orderId]);//订单改为支付
  813. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  814. $oid = self::where('order_id', $orderId)->value('id');
  815. if ($paid == 1){
  816. StoreOrderStatus::status($oid, 'pay_success', '用户累计订单付款成功'.$order['pay_price']);
  817. }else{
  818. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  819. }
  820. $now_money = User::where('uid', $order['uid'])->value('now_money');
  821. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
  822. //支付成功后
  823. event('OrderPaySuccess', [$order, $formId]);
  824. $res3 = StoreOrder::gainWhiteIntegral($order);
  825. $res4 = StoreOrder::gainBusinessIntegral($order);
  826. User::where('uid', $order['uid'])->update(['effective' => 1]);
  827. $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  828. return false !== $res;
  829. }
  830. /*
  831. * 线下支付消息通知
  832. * 待完善
  833. *
  834. * */
  835. public static function createOrderTemplate($order)
  836. {
  837. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  838. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  839. // 'first'=>'亲,您购买的商品已支付成功',
  840. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  841. // 'keyword2'=>implode(',',$goodsName),
  842. // 'keyword3'=>$order['order_id'],
  843. // 'remark'=>'点击查看订单详情'
  844. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  845. // RoutineTemplateService::sendAdminNoticeTemplate([
  846. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  847. // 'keyword1'=>'新订单',
  848. // 'keyword2'=>'线下支付',
  849. // 'keyword3'=>date('Y/m/d H:i',time()),
  850. // 'remark'=>'请及时处理'
  851. // ]);
  852. }
  853. /**
  854. * 获取订单详情
  855. * @param $uid
  856. * @param $key
  857. * @return array|\think\Model|null
  858. * @throws DataNotFoundException
  859. * @throws ModelNotFoundException
  860. * @throws \think\exception\DbException
  861. */
  862. public static function getUserOrderDetail($uid, $key)
  863. {
  864. return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
  865. }
  866. /**
  867. * TODO 订单发货
  868. * @param array $postageData 发货信息
  869. * @param string $oid orderID
  870. */
  871. public static function orderPostageAfter($postageData, $oid)
  872. {
  873. $order = self::where('id', $oid)->find();
  874. if ($postageData['delivery_type'] == 'send') {//送货
  875. RoutineTemplate::sendOrderPostage($order);
  876. } else if ($postageData['delivery_type'] == 'express') {//发货
  877. RoutineTemplate::sendOrderPostage($order, 1);
  878. }
  879. }
  880. /** 收货后发送模版消息
  881. * @param $order
  882. */
  883. public static function orderTakeAfter($order)
  884. {
  885. $title = self::getProductTitle($order['cart_id']);
  886. if ($order['is_channel'] == 1) {//小程序
  887. RoutineTemplate::sendOrderTakeOver($order, $title);
  888. } else {
  889. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  890. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  891. 'first' => '亲,您的订单已收货',
  892. 'keyword1' => $order['order_id'],
  893. 'keyword2' => '已收货',
  894. 'keyword3' => date('Y-m-d H:i:s', time()),
  895. 'keyword4' => $title,
  896. 'remark' => '感谢您的光临!'
  897. ]);
  898. }
  899. }
  900. /**
  901. * 删除订单
  902. * @param $uni
  903. * @param $uid
  904. * @return bool
  905. */
  906. public static function removeOrder($uni, $uid)
  907. {
  908. $order = self::getUserOrderDetail($uid, $uni);
  909. if (!$order) return self::setErrorInfo('订单不存在!');
  910. $order = self::tidyOrder($order);
  911. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  912. return self::setErrorInfo('该订单无法删除!');
  913. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  914. //未支付和已退款的状态下才可以退积分退库存退优惠券
  915. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  916. event('StoreOrderRegressionAllAfter', [$order]);
  917. }
  918. event('UserOrderRemoved', $uni);
  919. return true;
  920. } else
  921. return self::setErrorInfo('订单删除失败!');
  922. }
  923. /**
  924. * //TODO 用户确认收货
  925. * @param $uni
  926. * @param $uid
  927. */
  928. public static function takeOrder($uni, $uid)
  929. {
  930. $order = self::getUserOrderDetail($uid, $uni);
  931. if (!$order) return self::setErrorInfo('订单不存在!');
  932. $order = self::tidyOrder($order);
  933. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  934. self::beginTrans();
  935. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  936. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  937. try {
  938. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  939. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  940. } catch (\Exception $e) {
  941. self::rollbackTrans();
  942. return self::setErrorInfo($e->getMessage());
  943. }
  944. self::commitTrans();
  945. event('UserLevelAfter', [User::get($uni)]);
  946. event('UserOrderTake', $uni);
  947. //短信通知
  948. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  949. return true;
  950. } else {
  951. self::rollbackTrans();
  952. return false;
  953. }
  954. }
  955. /**
  956. * 获取订单状态购物车等信息
  957. * @param $order
  958. * @param bool $detail 是否获取订单购物车详情
  959. * @param bool $isPic 是否获取订单状态图片
  960. * @return mixed
  961. * @throws DataNotFoundException
  962. * @throws ModelNotFoundException
  963. * @throws \think\exception\DbException
  964. */
  965. public static function tidyOrder($order, $detail = false, $isPic = false)
  966. {
  967. if ($detail == true && isset($order['id'])) {
  968. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  969. $info = [];
  970. foreach ($cartInfo as $k => $cart) {
  971. $cart = json_decode($cart, true);
  972. $cart['unique'] = $k;
  973. //新增是否评价字段
  974. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  975. array_push($info, $cart);
  976. unset($cart);
  977. }
  978. $order['cartInfo'] = $info;
  979. }
  980. $status = [];
  981. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  982. $status['_type'] = 9;
  983. $status['_title'] = '线下付款';
  984. $status['_msg'] = '商家处理中,请耐心等待';
  985. $status['_class'] = 'nobuy';
  986. } else if (!$order['paid']) {
  987. $status['_type'] = 0;
  988. $status['_title'] = '未支付';
  989. //系统预设取消订单时间段
  990. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  991. //获取配置
  992. $systemValue = SystemConfigService::more($keyValue);
  993. //格式化数据
  994. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  995. if ($order['pink_id'] || $order['combination_id']) {
  996. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  997. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  998. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  999. } else if ($order['seckill_id']) {
  1000. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1001. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  1002. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1003. } else if ($order['bargain_id']) {
  1004. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1005. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  1006. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1007. } else {
  1008. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1009. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1010. }
  1011. $status['_class'] = 'nobuy';
  1012. } else if ($order['refund_status'] == 1) {
  1013. $status['_type'] = -1;
  1014. $status['_title'] = '申请退款中';
  1015. $status['_msg'] = '商家审核中,请耐心等待';
  1016. $status['_class'] = 'state-sqtk';
  1017. } else if ($order['refund_status'] == 2) {
  1018. $status['_type'] = -2;
  1019. $status['_title'] = '已退款';
  1020. $status['_msg'] = '已为您退款,感谢您的支持';
  1021. $status['_class'] = 'state-sqtk';
  1022. } else if (!$order['status']) {
  1023. if ($order['pink_id']) {
  1024. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1025. $status['_type'] = 1;
  1026. $status['_title'] = '拼团中';
  1027. $status['_msg'] = '等待其他人参加拼团';
  1028. $status['_class'] = 'state-nfh';
  1029. } else {
  1030. $status['_type'] = 1;
  1031. $status['_title'] = '未发货';
  1032. $status['_msg'] = '商家未发货,请耐心等待';
  1033. $status['_class'] = 'state-nfh';
  1034. }
  1035. } else {
  1036. if ($order['shipping_type'] === 1) {
  1037. $status['_type'] = 1;
  1038. $status['_title'] = '未发货';
  1039. $status['_msg'] = '商家未发货,请耐心等待';
  1040. $status['_class'] = 'state-nfh';
  1041. } else {
  1042. $status['_type'] = 1;
  1043. $status['_title'] = '待核销';
  1044. $status['_msg'] = '待核销,请到核销点进行核销';
  1045. $status['_class'] = 'state-nfh';
  1046. }
  1047. }
  1048. } else if ($order['status'] == 1) {
  1049. if ($order['delivery_type'] == 'send') {//TODO 送货
  1050. $status['_type'] = 2;
  1051. $status['_title'] = '待收货';
  1052. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  1053. $status['_class'] = 'state-ysh';
  1054. } else {//TODO 发货
  1055. $status['_type'] = 2;
  1056. $status['_title'] = '待收货';
  1057. if ($order['delivery_type'] == 'fictitious')
  1058. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1059. else
  1060. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1061. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  1062. $status['_class'] = 'state-ysh';
  1063. }
  1064. } else if ($order['status'] == 2) {
  1065. $status['_type'] = 3;
  1066. $status['_title'] = '待评价';
  1067. $status['_msg'] = '已收货,快去评价一下吧';
  1068. $status['_class'] = 'state-ypj';
  1069. } else if ($order['status'] == 3) {
  1070. $status['_type'] = 4;
  1071. $status['_title'] = '交易完成';
  1072. $status['_msg'] = '交易完成,感谢您的支持';
  1073. $status['_class'] = 'state-ytk';
  1074. }
  1075. if (isset($order['pay_type']))
  1076. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1077. if (isset($order['delivery_type']))
  1078. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1079. $order['_status'] = $status;
  1080. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  1081. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  1082. $order['status_pic'] = '';
  1083. //获取产品状态图片
  1084. if ($isPic) {
  1085. $order_details_images = sys_data('order_details_images') ?: [];
  1086. foreach ($order_details_images as $image) {
  1087. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1088. $order['status_pic'] = $image['pic'];
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1094. return $order;
  1095. }
  1096. /**
  1097. * 设置订单查询状态
  1098. * @param $status
  1099. * @param int $uid
  1100. * @param null $model
  1101. * @return StoreOrder|null
  1102. */
  1103. public static function statusByWhere($status, $uid = 0, $model = null)
  1104. {
  1105. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1106. if ($model == null) $model = new self;
  1107. if ('' === $status)
  1108. return $model;
  1109. else if ($status == 0)//未支付
  1110. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1111. else if ($status == 1)//待发货
  1112. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1113. else if ($status == 2)//待收货
  1114. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1115. else if ($status == 3)//待评价
  1116. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1117. else if ($status == 4)//已完成
  1118. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1119. else if ($status == -1)//退款中
  1120. return $model->where('paid', 1)->where('refund_status', 1);
  1121. else if ($status == -2)//已退款
  1122. return $model->where('paid', 1)->where('refund_status', 2);
  1123. else if ($status == -3)//退款
  1124. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1125. // else if($status == 11){
  1126. // return $model->where('order_id','IN',implode(',',$orderId));
  1127. // }
  1128. else
  1129. return $model;
  1130. }
  1131. /**
  1132. * 获取订单并分页
  1133. * @param $uid
  1134. * @param string $status
  1135. * @param int $page
  1136. * @param int $limit
  1137. * @return mixed
  1138. * @throws DataNotFoundException
  1139. * @throws ModelNotFoundException
  1140. * @throws \think\exception\DbException
  1141. */
  1142. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1143. {
  1144. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1145. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,cumulative')
  1146. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1147. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid', $uid)
  1148. ->field('add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,cumulative')
  1149. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1150. foreach ($list as $k => $order) {
  1151. $list[$k] = self::tidyOrder($order, true);
  1152. }
  1153. return $list;
  1154. }
  1155. /**
  1156. * 获取推广人地下用户的订单金额
  1157. * @param string $uid
  1158. * @param string $status
  1159. * @return array
  1160. */
  1161. public static function getUserOrderCount($uid = '', $status = '')
  1162. {
  1163. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1164. return $res;
  1165. }
  1166. /**
  1167. * 搜索某个订单详细信息
  1168. * @param $uid
  1169. * @param $order_id
  1170. * @return bool|mixed
  1171. * @throws DataNotFoundException
  1172. * @throws ModelNotFoundException
  1173. * @throws \think\exception\DbException
  1174. */
  1175. public static function searchUserOrder($uid, $order_id)
  1176. {
  1177. $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
  1178. ->order('add_time DESC')->find();
  1179. if (!$order)
  1180. return false;
  1181. else
  1182. return self::tidyOrder($order->toArray(), true);
  1183. }
  1184. /**
  1185. * 订单评价信息记录
  1186. * @param $oid
  1187. * @return StoreOrderStatus|\think\Model
  1188. * @throws \Exception
  1189. */
  1190. public static function orderOver($oid)
  1191. {
  1192. $res = self::edit(['status' => '3'], $oid, 'id');
  1193. if (!$res) exception('评价后置操作失败!');
  1194. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1195. }
  1196. /**
  1197. * 设置订单产品评价完毕事件
  1198. * @param $oid
  1199. * @return StoreOrderStatus|\think\Model
  1200. * @throws \Exception
  1201. */
  1202. public static function checkOrderOver($oid)
  1203. {
  1204. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1205. //订单产品全部评价完成
  1206. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1207. event('StoreProductOrderOver', [$oid]);
  1208. return self::orderOver($oid);
  1209. }
  1210. }
  1211. public static function getOrderStatusNum($uid)
  1212. {
  1213. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1214. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1215. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1216. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1217. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1218. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1219. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1220. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1221. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1222. }
  1223. /**
  1224. * 购买商品赠送积分
  1225. * @param $order
  1226. * @return bool
  1227. * @throws \think\Exception
  1228. * @throws DataNotFoundException
  1229. * @throws ModelNotFoundException
  1230. * @throws \think\exception\DbException
  1231. */
  1232. public static function gainUserIntegral($order)
  1233. {
  1234. if ($order['gain_integral'] > 0) {
  1235. $userInfo = User::getUserInfo($order['uid']);
  1236. BaseModel::beginTrans();
  1237. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1238. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1239. $res = $res1 && $res2;
  1240. BaseModel::checkTrans($res);
  1241. return $res;
  1242. }
  1243. return true;
  1244. }
  1245. /**
  1246. * 购买商品赠送积分
  1247. * @param $order
  1248. * @return bool
  1249. * @throws \think\Exception
  1250. * @throws DataNotFoundException
  1251. * @throws ModelNotFoundException
  1252. * @throws \think\exception\DbException
  1253. */
  1254. public static function gainWhiteIntegral($order)
  1255. {
  1256. if ($order['white_integral'] > 0) {
  1257. $userInfo = User::getUserInfo($order['uid']);
  1258. BaseModel::beginTrans();
  1259. $res1 = false != User::where('uid', $userInfo['uid'])->update(['white_integral' => bcadd($userInfo['white_integral'], $order['white_integral'], 2)]);
  1260. $res2 = false != UserBill::income('购买商品赠送红积分', $order['uid'], 'white_integral', 'gain_white_integral', $order['white_integral'], $order['id'], bcadd($userInfo['white_integral'], $order['white_integral'], 2), '购买商品赠送' . floatval($order['white_integral']) . '红积分');
  1261. $res = $res1 && $res2;
  1262. BaseModel::checkTrans($res);
  1263. return $res;
  1264. }
  1265. return true;
  1266. }
  1267. /**
  1268. * 购买商品赠送积分
  1269. * @param $order
  1270. * @return bool
  1271. * @throws \think\Exception
  1272. * @throws DataNotFoundException
  1273. * @throws ModelNotFoundException
  1274. * @throws \think\exception\DbException
  1275. */
  1276. public static function gainBusinessIntegral($order)
  1277. {
  1278. if ($order['business_integral'] > 0) {
  1279. $userInfo = User::getUserInfo($order['uid']);
  1280. BaseModel::beginTrans();
  1281. $res1 = false != User::where('uid', $userInfo['uid'])->update(['business_integral' => bcadd($userInfo['business_integral'], $order['business_integral'], 2)]);
  1282. $res2 = false != UserBill::income('购买商品赠送喜嗨积分', $order['uid'], 'business_integral', 'gain_business_integral',$order['business_integral'], $order['id'], bcadd($userInfo['business_integral'], $order['business_integral'], 2), '购买商品赠送' . floatval($order['business_integral']) . '喜嗨积分');
  1283. $res = $res1 && $res2;
  1284. BaseModel::checkTrans($res);
  1285. return $res;
  1286. }
  1287. return true;
  1288. }
  1289. /**
  1290. * 获取当前订单中有没有拼团存在
  1291. * @param $pid
  1292. * @return int|string
  1293. */
  1294. public static function getIsOrderPink($pid = 0, $uid = 0)
  1295. {
  1296. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1297. }
  1298. /**
  1299. * 获取order_id
  1300. * @param $pid
  1301. * @return mixed
  1302. */
  1303. public static function getStoreIdPink($pid = 0, $uid = 0)
  1304. {
  1305. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1306. }
  1307. /**
  1308. * 删除当前用户拼团未支付的订单
  1309. */
  1310. public static function delCombination()
  1311. {
  1312. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1313. }
  1314. public static function getUserPrice($uid = 0)
  1315. {
  1316. if (!$uid) return 0;
  1317. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1318. $count = 0;
  1319. if ($price) {
  1320. foreach ($price as $v) {
  1321. $count = bcadd($count, $v, 2);
  1322. }
  1323. }
  1324. return $count;
  1325. }
  1326. /**
  1327. * 个人中心获取个人订单列表和订单搜索
  1328. * @param int $uid 用户uid
  1329. * @param int | string 查找订单类型
  1330. * @param int $first 分页
  1331. * @param int 每页显示多少条
  1332. * @param string $search 订单号
  1333. * @return array
  1334. * */
  1335. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1336. {
  1337. if ($search) {
  1338. $order = self::searchUserOrder($uid, $search) ?: [];
  1339. $list = $order == false ? [] : [$order];
  1340. } else {
  1341. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1342. }
  1343. foreach ($list as $k => $order) {
  1344. $list[$k] = self::tidyOrder($order, true);
  1345. if ($list[$k]['_status']['_type'] == 3) {
  1346. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1347. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1348. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1349. }
  1350. }
  1351. }
  1352. return $list;
  1353. }
  1354. /**
  1355. * 获取用户下级的订单
  1356. * @param int $xuid 下级用户用户uid
  1357. * @param int $uid 用户uid
  1358. * @param int $type 订单类型
  1359. * @param int $first 截取行数
  1360. * @param int $limit 展示条数
  1361. * @return array
  1362. * */
  1363. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1364. {
  1365. $list = [];
  1366. if (!$xUid) {
  1367. $arr = User::getOneSpreadUid($uid);
  1368. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1369. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1370. foreach ($list as $k => $order) {
  1371. $list[$k] = self::tidyOrder($order, true);
  1372. if ($list[$k]['_status']['_type'] == 3) {
  1373. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1374. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1375. }
  1376. }
  1377. }
  1378. return $list;
  1379. }
  1380. /**
  1381. * 获取 今日 昨日 本月 订单金额
  1382. * @return mixed
  1383. */
  1384. public static function getOrderTimeData()
  1385. {
  1386. $to_day = strtotime(date('Y-m-d'));//今日
  1387. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1388. $now_month = strtotime(date('Y-m'));//本月
  1389. //今日成交额
  1390. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1391. $data['todayPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1392. //今日订单数
  1393. $data['todayCount'] = self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1394. //昨日成交额
  1395. $data['proPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1396. //昨日订单数
  1397. $data['proCount'] = self::where('is_del', 0)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1398. //本月成交额
  1399. $data['monthPrice'] = number_format(self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1400. //本月订单数
  1401. $data['monthCount'] = self::where('is_del', 0)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1402. return $data;
  1403. }
  1404. /**
  1405. * 获取某个用户的订单统计数据
  1406. * @param $uid
  1407. * @return mixed
  1408. */
  1409. public static function getOrderData($uid)
  1410. {
  1411. //订单支付没有退款 数量
  1412. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->count();
  1413. //订单支付没有退款 支付总金额
  1414. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1415. //订单待支付 数量
  1416. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1417. //订单待发货 数量
  1418. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1419. //订单待收货 数量
  1420. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1421. //订单待评价 数量
  1422. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1423. //订单已完成 数量
  1424. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1425. //订单退款
  1426. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid', $uid)->count();
  1427. return $data;
  1428. }
  1429. /**
  1430. * 获取订单统计数据
  1431. * @param $uid
  1432. * @return mixed
  1433. */
  1434. public static function getOrderDataAdmin()
  1435. {
  1436. //订单支付没有退款 数量
  1437. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->count();
  1438. //订单支付没有退款 支付总金额
  1439. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1440. //订单待支付 数量
  1441. $data['unpaid_count'] = self::statusByWhere(0, 0)->where('is_del', 0)->count();
  1442. //订单待发货 数量
  1443. $data['unshipped_count'] = self::statusByWhere(1, 0)->where('is_del', 0)->count();
  1444. //订单待收货 数量
  1445. $data['received_count'] = self::statusByWhere(2, 0)->where('is_del', 0)->count();
  1446. //订单待评价 数量
  1447. $data['evaluated_count'] = self::statusByWhere(3, 0)->where('is_del', 0)->count();
  1448. //订单已完成 数量
  1449. $data['complete_count'] = self::statusByWhere(4, 0)->where('is_del', 0)->count();
  1450. //订单退款 数量
  1451. $data['refund_count'] = self::statusByWhere(-3, 0)->where('is_del', 0)->count();
  1452. return $data;
  1453. }
  1454. /**
  1455. * 累计消费
  1456. * @param $uid
  1457. * @return float
  1458. */
  1459. public static function getOrderStatusSum($uid)
  1460. {
  1461. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  1462. }
  1463. public static function getPinkOrderId($id)
  1464. {
  1465. return self::where('id', $id)->value('order_id');
  1466. }
  1467. /**
  1468. * 未支付订单自动取消
  1469. * @param int $limit 分页截取条数
  1470. * @param string $prefid 缓存名称
  1471. * @param int $expire 缓存时间
  1472. * @return string|null
  1473. * @throws \Psr\SimpleCache\InvalidArgumentException
  1474. */
  1475. public static function orderUnpaidCancel()
  1476. {
  1477. //系统预设取消订单时间段
  1478. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1479. //获取配置
  1480. $systemValue = SystemConfigService::more($keyValue);
  1481. //格式化数据
  1482. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1483. //检查是否有未支付的订单 未支付查询条件
  1484. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1485. if (!$unPidCount) return null;
  1486. try {
  1487. $res = true;
  1488. // 未支付查询条件
  1489. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  1490. foreach ($orderList as $order) {
  1491. if ($order['seckill_id']) {
  1492. //优先使用单独配置的过期时间
  1493. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1494. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1495. unset($order_seckill_time);
  1496. } else if ($order['bargain_id']) {
  1497. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1498. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1499. unset($order_bargain_time);
  1500. } else if ($order['pink_id'] || $order['combination_id']) {
  1501. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1502. $res = $res && self::RegressionAll($order_pink_time, $order);
  1503. unset($order_pink_time);
  1504. } else {
  1505. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1506. }
  1507. }
  1508. if (!$res) throw new \Exception('更新错误');
  1509. unset($orderList, $res, $pages);
  1510. return null;
  1511. } catch (PDOException $e) {
  1512. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1513. throw new \Exception($e->getMessage());
  1514. } catch (\think\Exception $e) {
  1515. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1516. throw new \Exception($e->getMessage());
  1517. }
  1518. }
  1519. /**
  1520. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1521. * @param $time 预设时间
  1522. * @param $order 订单详情
  1523. * @return bool
  1524. * @throws DataNotFoundException
  1525. * @throws ModelNotFoundException
  1526. * @throws \think\exception\DbException
  1527. */
  1528. protected static function RegressionAll($time, $order)
  1529. {
  1530. if ($time == 0) return true;
  1531. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1532. $res1 = self::RegressionStock($order);
  1533. $res2 = self::RegressionIntegral($order);
  1534. $res3 = self::RegressionCoupon($order);
  1535. $res = $res1 && $res2 && $res3;
  1536. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1537. unset($res1, $res2, $res3);
  1538. return $res;
  1539. } else
  1540. return true;
  1541. }
  1542. /**
  1543. * 格式化数据
  1544. * @param array $array 原本数据键
  1545. * @param $value 需要格式化的数据
  1546. * @param int $default 默认值
  1547. * @return mixed
  1548. */
  1549. protected static function setValeTime(array $array, $value, $default = 0)
  1550. {
  1551. foreach ($array as $item) {
  1552. if (!isset($value[$item]))
  1553. $value[$item] = $default;
  1554. else if (is_string($value[$item]))
  1555. $value[$item] = (float)$value[$item];
  1556. }
  1557. return $value;
  1558. }
  1559. public static function getOrderTotalPrice($cartInfo)
  1560. {
  1561. $totalPrice = 0;
  1562. foreach ($cartInfo as $cart) {
  1563. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1564. }
  1565. return $totalPrice;
  1566. }
  1567. public static function getOrderCostPrice($cartInfo)
  1568. {
  1569. $costPrice = 0;
  1570. foreach ($cartInfo as $cart) {
  1571. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1572. }
  1573. return $costPrice;
  1574. }
  1575. public static function getCombinationOrderCostPrice($cartInfo)
  1576. {
  1577. $costPrice = 0;
  1578. foreach ($cartInfo as $cart) {
  1579. if ($cart['combination_id']) {
  1580. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1581. }
  1582. }
  1583. return (float)$costPrice;
  1584. }
  1585. public static function yueRefundAfter($order)
  1586. {
  1587. }
  1588. /**
  1589. * 获取余额支付的金额
  1590. * @param $uid
  1591. * @return float|int
  1592. */
  1593. public static function getOrderStatusYueSum($uid)
  1594. {
  1595. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1596. }
  1597. /**
  1598. * 砍价支付成功订单数量
  1599. * @param $bargain
  1600. * @return int
  1601. */
  1602. public static function getBargainPayCount($bargain)
  1603. {
  1604. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1605. }
  1606. /**
  1607. * 7天自动收货
  1608. * @return bool
  1609. */
  1610. public static function startTakeOrder()
  1611. {
  1612. //7天前时间戳
  1613. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1614. //0为取消自动收货功能
  1615. if ($systemDeliveryTime == 0) return true;
  1616. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1617. $model = new self;
  1618. $model = $model->alias('o');
  1619. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1620. $model = $model->where('o.paid', 1);
  1621. $model = $model->where('s.change_type', 'delivery_goods');
  1622. $model = $model->where('s.change_time', '<', $sevenDay);
  1623. $model = $model->where('o.status', 1);
  1624. $model = $model->where('o.refund_status', 0);
  1625. $model = $model->where('o.is_del', 0);
  1626. $orderInfo = $model->column('id', 'id');
  1627. if (!count($orderInfo)) return true;
  1628. $res = true;
  1629. foreach ($orderInfo as $key => &$item) {
  1630. $order = self::get($item);
  1631. if ($order['status'] == 2) continue;
  1632. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1633. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1634. else continue;
  1635. if (!self::edit($data, $item, 'id')) continue;
  1636. try {
  1637. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1638. $res = $res && true;
  1639. } catch (\Exception $e) {
  1640. $res = $res && false;
  1641. }
  1642. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1643. }
  1644. if (!$res) {
  1645. throw new \Exception('');
  1646. }
  1647. }
  1648. /**
  1649. * 获取订单信息
  1650. * @param $id
  1651. * @param string $field
  1652. * @return array|null|\think\Model
  1653. * @throws DataNotFoundException
  1654. * @throws ModelNotFoundException
  1655. * @throws \think\exception\DbException
  1656. */
  1657. public static function getOrderInfo($id, $field = 'order_id')
  1658. {
  1659. return self::where('id', $id)->field($field)->find();
  1660. }
  1661. /**
  1662. * 订单每月统计数据
  1663. * @param $page
  1664. * @param $limit
  1665. * @return array
  1666. */
  1667. public static function getOrderDataPriceCount($page, $limit, $start, $stop)
  1668. {
  1669. if (!$limit) return [];
  1670. $model = new self;
  1671. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1672. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1673. $model = $model->where('is_del', 0);
  1674. $model = $model->where('paid', 1);
  1675. $model = $model->where('refund_status', 0);
  1676. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1677. $model = $model->order('pay_time DESC');
  1678. if ($page) $model = $model->page($page, $limit);
  1679. return $model->select();
  1680. }
  1681. /**
  1682. * 前台订单管理订单列表获取
  1683. * @param $where
  1684. * @return mixed
  1685. */
  1686. public static function orderList($where)
  1687. {
  1688. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.id,a.order_id,a.add_time,a.status,a.total_num,a.total_price,a.total_postage,a.pay_price,a.pay_postage,a.paid,a.refund_status,a.remark,a.pay_type');
  1689. if ($where['order'] != '') {
  1690. $model = $model->order(self::setOrder($where['order']));
  1691. } else {
  1692. $model = $model->order('a.id desc');
  1693. }
  1694. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1695. return self::tidyAdminOrder($data);
  1696. }
  1697. /**
  1698. * 前台订单管理 订单信息设置
  1699. * @param $data
  1700. * @param bool $status
  1701. * @return mixed
  1702. * @throws DataNotFoundException
  1703. * @throws ModelNotFoundException
  1704. * @throws \think\exception\DbException
  1705. */
  1706. public static function tidyAdminOrder($data, $status = false)
  1707. {
  1708. foreach ($data as &$item) {
  1709. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1710. foreach ($_info as $k => $v) {
  1711. if (!is_array($v['cart_info']))
  1712. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1713. }
  1714. foreach ($_info as $k => $v) {
  1715. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  1716. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1717. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1718. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1719. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1720. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1721. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1722. }
  1723. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1724. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1725. }
  1726. }
  1727. $item['_info'] = $_info;
  1728. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1729. // if($item['pink_id'] || $item['combination_id']){
  1730. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1731. // switch ($pinkStatus){
  1732. // case 1:
  1733. // $item['pink_name'] = '[拼团订单]正在进行中';
  1734. // $item['color'] = '#f00';
  1735. // break;
  1736. // case 2:
  1737. // $item['pink_name'] = '[拼团订单]已完成';
  1738. // $item['color'] = '#00f';
  1739. // break;
  1740. // case 3:
  1741. // $item['pink_name'] = '[拼团订单]未完成';
  1742. // $item['color'] = '#f0f';
  1743. // break;
  1744. // default:
  1745. // $item['pink_name'] = '[拼团订单]历史订单';
  1746. // $item['color'] = '#457856';
  1747. // break;
  1748. // }
  1749. // }elseif ($item['seckill_id']){
  1750. // $item['pink_name'] = '[秒杀订单]';
  1751. // $item['color'] = '#32c5e9';
  1752. // }elseif ($item['bargain_id']){
  1753. // $item['pink_name'] = '[砍价订单]';
  1754. // $item['color'] = '#12c5e9';
  1755. // }else{
  1756. // $item['pink_name'] = '[普通订单]';
  1757. // $item['color'] = '#895612';
  1758. // }
  1759. // if($item['paid']==1){
  1760. // switch ($item['pay_type']){
  1761. // case 'weixin':
  1762. // $item['pay_type_name']='微信支付';
  1763. // break;
  1764. // case 'yue':
  1765. // $item['pay_type_name']='余额支付';
  1766. // break;
  1767. // case 'offline':
  1768. // $item['pay_type_name']='线下支付';
  1769. // break;
  1770. // default:
  1771. // $item['pay_type_name']='其他支付';
  1772. // break;
  1773. // }
  1774. // }else{
  1775. // switch ($item['pay_type']){
  1776. // default:
  1777. // $item['pay_type_name']='未支付';
  1778. // break;
  1779. // case 'offline':
  1780. // $item['pay_type_name']='线下支付';
  1781. // $item['pay_type_info']=1;
  1782. // break;
  1783. // }
  1784. // }
  1785. if ($status) {
  1786. $status = [];
  1787. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1788. $status['_type'] = 9;
  1789. $status['_title'] = '线下付款';
  1790. $status['_msg'] = '商家处理中,请耐心等待';
  1791. $status['_class'] = 'nobuy';
  1792. } else if (!$item['paid']) {
  1793. $status['_type'] = 0;
  1794. $status['_title'] = '未支付';
  1795. //系统预设取消订单时间段
  1796. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1797. //获取配置
  1798. $systemValue = SystemConfigService::more($keyValue);
  1799. //格式化数据
  1800. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1801. if ($item['pink_id'] || $item['combination_id']) {
  1802. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1803. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1804. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1805. } else if ($item['seckill_id']) {
  1806. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1807. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1808. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1809. } else if ($item['bargain_id']) {
  1810. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1811. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1812. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1813. } else {
  1814. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1815. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1816. }
  1817. $status['_class'] = 'nobuy';
  1818. } else if ($item['refund_status'] == 1) {
  1819. $status['_type'] = -1;
  1820. $status['_title'] = '申请退款中';
  1821. $status['_msg'] = '商家审核中,请耐心等待';
  1822. $status['_class'] = 'state-sqtk';
  1823. } else if ($item['refund_status'] == 2) {
  1824. $status['_type'] = -2;
  1825. $status['_title'] = '已退款';
  1826. $status['_msg'] = '已为您退款,感谢您的支持';
  1827. $status['_class'] = 'state-sqtk';
  1828. } else if (!$item['status']) {
  1829. if ($item['pink_id']) {
  1830. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1831. $status['_type'] = 11;
  1832. $status['_title'] = '拼团中';
  1833. $status['_msg'] = '等待其他人参加拼团';
  1834. $status['_class'] = 'state-nfh';
  1835. } else {
  1836. $status['_type'] = 1;
  1837. $status['_title'] = '未发货';
  1838. $status['_msg'] = '商家未发货,请耐心等待';
  1839. $status['_class'] = 'state-nfh';
  1840. }
  1841. } else {
  1842. $status['_type'] = 1;
  1843. $status['_title'] = '未发货';
  1844. $status['_msg'] = '商家未发货,请耐心等待';
  1845. $status['_class'] = 'state-nfh';
  1846. }
  1847. } else if ($item['status'] == 1) {
  1848. if ($item['delivery_type'] == 'send') {//TODO 送货
  1849. $status['_type'] = 2;
  1850. $status['_title'] = '待收货';
  1851. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1852. $status['_class'] = 'state-ysh';
  1853. } else {//TODO 发货
  1854. $status['_type'] = 2;
  1855. $status['_title'] = '待收货';
  1856. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1857. $status['_class'] = 'state-ysh';
  1858. }
  1859. } else if ($item['status'] == 2) {
  1860. $status['_type'] = 3;
  1861. $status['_title'] = '待评价';
  1862. $status['_msg'] = '已收货,快去评价一下吧';
  1863. $status['_class'] = 'state-ypj';
  1864. } else if ($item['status'] == 3) {
  1865. $status['_type'] = 4;
  1866. $status['_title'] = '交易完成';
  1867. $status['_msg'] = '交易完成,感谢您的支持';
  1868. $status['_class'] = 'state-ytk';
  1869. }
  1870. if (isset($item['pay_type']))
  1871. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1872. if (isset($item['delivery_type']))
  1873. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1874. $item['_status'] = $status;
  1875. } else {
  1876. if ($item['paid'] == 0 && $item['status'] == 0) {
  1877. $item['status_name'] = '未支付';
  1878. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1879. $item['status_name'] = '未发货';
  1880. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1881. $item['status_name'] = '待收货';
  1882. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1883. $item['status_name'] = '待评价';
  1884. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1885. $item['status_name'] = '已完成';
  1886. }
  1887. }
  1888. // unset($item['refund_status']);
  1889. // else if($item['paid']==1 && $item['refund_status']==1){
  1890. // $item['status_name']=<<<HTML
  1891. //<b style="color:#f124c7">申请退款</b><br/>
  1892. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1893. //HTML;
  1894. // }else if($item['paid']==1 && $item['refund_status']==2){
  1895. // $item['status_name']='已退款';
  1896. // }
  1897. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1898. // $item['_status']=1;
  1899. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1900. // $item['_status']=2;
  1901. // }else if($item['paid']==1 && $item['refund_status']==1){
  1902. // $item['_status']=3;
  1903. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1904. // $item['_status']=4;
  1905. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1906. // $item['_status']=5;
  1907. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1908. // $item['_status']=6;
  1909. // }else if($item['paid']==1 && $item['refund_status']==2){
  1910. // $item['_status']=7;
  1911. // }
  1912. }
  1913. return $data;
  1914. }
  1915. /**
  1916. * 处理where条件
  1917. * @param $where
  1918. * @param $model
  1919. * @param string $aler
  1920. * @param string $join
  1921. * @return StoreOrder|null
  1922. */
  1923. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1924. {
  1925. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1926. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1927. if (isset($where['combination_id'])) {
  1928. if ($where['combination_id'] == '普通订单') {
  1929. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1930. }
  1931. if ($where['combination_id'] == '拼团订单') {
  1932. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1933. }
  1934. if ($where['combination_id'] == '秒杀订单') {
  1935. $model = $model->where($aler . 'seckill_id', ">", 0);
  1936. }
  1937. if ($where['combination_id'] == '砍价订单') {
  1938. $model = $model->where($aler . 'bargain_id', ">", 0);
  1939. }
  1940. }
  1941. if (isset($where['type'])) {
  1942. switch ($where['type']) {
  1943. case 1:
  1944. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1945. break;
  1946. case 2:
  1947. $model = $model->where($aler . 'combination_id', ">", 0);
  1948. break;
  1949. case 3:
  1950. $model = $model->where($aler . 'seckill_id', ">", 0);
  1951. break;
  1952. case 4:
  1953. $model = $model->where($aler . 'bargain_id', ">", 0);
  1954. break;
  1955. }
  1956. }
  1957. if (isset($where['real_name']) && $where['real_name'] != '')
  1958. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1959. if (isset($where['data']) && $where['data'] !== '')
  1960. $model = self::getModelTime($where, $model, $aler . 'add_time');
  1961. return $model;
  1962. }
  1963. /**
  1964. * 设置where条件
  1965. * @param $status
  1966. * @param null $model
  1967. * @param string $alert
  1968. * @return StoreOrder|null
  1969. */
  1970. public static function statusWhere($status, $model = null, $alert = '')
  1971. {
  1972. if ($model == null) $model = new self;
  1973. if ('' === $status)
  1974. return $model;
  1975. else if ($status == 0)//未支付
  1976. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1977. else if ($status == 1)//已支付 未发货
  1978. return $model->where($alert . 'paid', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1979. else if ($status == 2)//已支付 待收货
  1980. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  1981. else if ($status == 3)// 已支付 已收货 待评价
  1982. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  1983. else if ($status == 4)// 交易完成
  1984. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  1985. else if ($status == -1)//退款中
  1986. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  1987. else if ($status == -2)//已退款
  1988. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  1989. else if ($status == -3)//退款
  1990. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  1991. else
  1992. return $model;
  1993. }
  1994. /**
  1995. * 订单详情 管理员
  1996. * @param $orderId
  1997. * @param string $field
  1998. * @return array|null|\think\Model
  1999. * @throws DataNotFoundException
  2000. * @throws ModelNotFoundException
  2001. * @throws \think\exception\DbException
  2002. */
  2003. public static function getAdminOrderDetail($orderId, $field = '*')
  2004. {
  2005. return self::where('order_id', $orderId)->field($field)->find();
  2006. }
  2007. /**
  2008. * 获取指定时间区间的支付金额 管理员
  2009. * @param $start
  2010. * @param $stop
  2011. * @return float
  2012. */
  2013. public static function getOrderTimeBusinessVolumePrice($start, $stop)
  2014. {
  2015. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  2016. }
  2017. /**
  2018. * 获取指定时间区间的支付订单数量 管理员
  2019. * @param $start
  2020. * @param $stop
  2021. * @return float
  2022. */
  2023. public static function getOrderTimeBusinessVolumeNumber($start, $stop)
  2024. {
  2025. return self::where('is_del', 0)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  2026. }
  2027. /**
  2028. * 获取当前时间到指定时间的支付金额 管理员
  2029. * @param $start 开始时间
  2030. * @param $stop 结束时间
  2031. * @return mixed
  2032. */
  2033. public static function chartTimePrice($start, $stop)
  2034. {
  2035. $model = new self;
  2036. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2037. $model = $model->where('is_del', 0);
  2038. $model = $model->where('paid', 1);
  2039. $model = $model->where('refund_status', 0);
  2040. $model = $model->where('add_time', '>=', $start);
  2041. $model = $model->where('add_time', '<', $stop);
  2042. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2043. $model = $model->order('add_time ASC');
  2044. return $model->select();
  2045. }
  2046. /**
  2047. * 获取当前时间到指定时间的支付订单数 管理员
  2048. * @param $start 开始时间
  2049. * @param $stop 结束时间
  2050. * @return mixed
  2051. */
  2052. public static function chartTimeNumber($start, $stop)
  2053. {
  2054. $model = new self;
  2055. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2056. $model = $model->where('is_del', 0);
  2057. $model = $model->where('paid', 1);
  2058. $model = $model->where('refund_status', 0);
  2059. $model = $model->where('add_time', '>=', $start);
  2060. $model = $model->where('add_time', '<', $stop);
  2061. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2062. $model = $model->order('add_time ASC');
  2063. return $model->select();
  2064. }
  2065. /**
  2066. * 修改支付方式为线下支付
  2067. * @param $orderId
  2068. * @return bool
  2069. */
  2070. public static function setOrderTypePayOffline($orderId)
  2071. {
  2072. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2073. }
  2074. /**
  2075. * 线下付款
  2076. * @param $id
  2077. * @return $this
  2078. */
  2079. public static function updateOffline($id)
  2080. {
  2081. $count = self::where('id', $id)->count();
  2082. if (!$count) return self::setErrorInfo('订单不存在');
  2083. $count = self::where('id', $id)->where('paid', 0)->count();
  2084. if (!$count) return self::setErrorInfo('订单已支付');
  2085. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2086. return $res;
  2087. }
  2088. /**
  2089. * 向创建订单10分钟未付款的用户发送短信
  2090. */
  2091. public static function sendTen()
  2092. {
  2093. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  2094. foreach ($list as $phone) {
  2095. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  2096. }
  2097. }
  2098. public function productInfo()
  2099. {
  2100. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2101. }
  2102. public static function setOrderProductReplyWhere($where)
  2103. {
  2104. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2105. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2106. })->with('productInfo', function ($query) use ($where) {
  2107. $alias = '';
  2108. if (isset($where['title']) && $where['title'] != '')
  2109. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2110. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2111. if ($where['is_reply'] >= 0) {
  2112. $query->where("{$alias}is_reply", $where['is_reply']);
  2113. } else {
  2114. $query->where("{$alias}is_reply", '>', 0);
  2115. }
  2116. }
  2117. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2118. $query->where($alias . 'product_id', $where['producr_id']);
  2119. $query->where("{$alias}is_del", 0);
  2120. });
  2121. return $model;
  2122. }
  2123. public static function getOrderProductReplyList($where)
  2124. {
  2125. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2126. $list = count($list) ? $list->toArray() : [];
  2127. foreach ($list as $key => $item) {
  2128. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2129. foreach ($item['productInfo'] as $k => $v) {
  2130. if (!$v['nickname'] && $v['uid']) {
  2131. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2132. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2133. }
  2134. $v['image'] = '';
  2135. $v['store_name'] = '';
  2136. if ($v['product_id']) {
  2137. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2138. if ($product) {
  2139. $v['image'] = $product['image'];
  2140. $v['store_name'] = $product['store_name'];
  2141. }
  2142. }
  2143. $list[$key]['productInfo'][$k] = $v;
  2144. }
  2145. }
  2146. }
  2147. $count = self::setOrderProductReplyWhere($where)->count();
  2148. return compact('list', 'count');
  2149. }
  2150. }