StoreOrder.php 147 KB

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