StoreOrder.php 118 KB

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