StoreOrder.php 120 KB

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