StoreOrder.php 121 KB

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