StoreOrderServices.php 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\dao\order\StoreOrderDao;
  13. use app\jobs\BatchHandleJob;
  14. use app\jobs\order\AutoOrderUnpaidCancelJob;
  15. use app\jobs\order\SpliteStoreOrderJob;
  16. use app\model\system\config\SystemConfig;
  17. use app\model\user\User;
  18. use app\model\user\UserBill;
  19. use app\model\user\UserBrokerage;
  20. use app\services\activity\combination\StorePinkServices;
  21. use app\services\activity\coupon\StoreCouponIssueServices;
  22. use app\services\BaseServices;
  23. use app\services\product\branch\StoreBranchProductServices;
  24. use app\services\other\queue\QueueAuxiliaryServices;
  25. use app\services\other\queue\QueueServices;
  26. use app\services\pay\PayServices;
  27. use app\services\product\product\StoreProductLogServices;
  28. use app\services\product\product\StoreProductServices;
  29. use app\services\product\sku\StoreProductAttrValueServices;
  30. use app\services\store\finance\StoreFinanceFlowServices;
  31. use app\services\store\SystemStoreServices;
  32. use app\services\system\config\ConfigServices;
  33. use app\services\system\form\SystemFormServices;
  34. use app\services\user\AwardIntegralServices;
  35. use app\services\user\UserAwardIntegralServices;
  36. use app\services\user\UserBrokerageServices;
  37. use app\services\user\UserInvoiceServices;
  38. use app\services\user\UserServices;
  39. use app\services\product\product\StoreProductReplyServices;
  40. use app\services\user\UserAddressServices;
  41. use app\services\user\level\UserLevelServices;
  42. use crmeb\exceptions\AdminException;
  43. use crmeb\services\CacheService;
  44. use crmeb\services\FileService;
  45. use crmeb\services\FormBuilder as Form;
  46. use crmeb\services\printer\Printer;
  47. use crmeb\services\SystemConfigService;
  48. use crmeb\traits\ServicesTrait;
  49. use crmeb\utils\Arr;
  50. use think\exception\ValidateException;
  51. use think\facade\Log;
  52. /**
  53. * Class StoreOrderServices
  54. * @package app\services\order
  55. * @mixin StoreOrderDao
  56. */
  57. class StoreOrderServices extends BaseServices
  58. {
  59. use ServicesTrait;
  60. /**
  61. * 订单类型
  62. * @var string[]
  63. */
  64. protected $type = [
  65. 0 => '普通',
  66. 1 => '秒杀',
  67. 2 => '砍价',
  68. 3 => '拼团',
  69. 4 => '积分',
  70. 5 => '套餐',
  71. 6 => '预售',
  72. 7 => '新人礼',
  73. 8 => '抽奖',
  74. 9 => '拼单',
  75. 10 => '桌码'
  76. ];
  77. /**
  78. * 发货类型
  79. * @var string[]
  80. */
  81. public $deliveryType = ['send' => '商家配送', 'express' => '快递配送', 'fictitious' => '虚拟发货', 'delivery_part_split' => '拆分部分发货', 'delivery_split' => '拆分发货完成'];
  82. /**
  83. * StoreOrderProductServices constructor.
  84. * @param StoreOrderDao $dao
  85. */
  86. public function __construct(StoreOrderDao $dao)
  87. {
  88. $this->dao = $dao;
  89. }
  90. /**
  91. * 从缓存中获取购买商品个数
  92. * @param int $uid
  93. * @param int $type
  94. * @param int $id
  95. * @return int
  96. * @author 等风来
  97. * @email 136327134@qq.com
  98. * @date 2022/11/3
  99. */
  100. public function getBuyCountCache(int $uid, int $type, int $id)
  101. {
  102. $key = md5($uid . $type . $id);
  103. $res = $this->dao->cacheInfoById($key);
  104. if (null !== $res) {
  105. $num = $this->dao->getBuyCount($uid, $type, $id);
  106. $this->dao->cacheUpdate(['type' => $type, 'uid' => $uid, 'product_id' => $id, 'totalNum' => $num ?: 0], $key);
  107. } else {
  108. $num = $res['totalNum'] ?? 0;
  109. }
  110. return (int)$num;
  111. }
  112. /**
  113. * 获取门店订单统计
  114. * @param int $storeId
  115. * @return array
  116. */
  117. public function getStoreOrderHeader(int $storeId)
  118. {
  119. return [
  120. 'cashier' => $this->dao->count(['pid' => 0, 'type' => 6, 'is_system_del' => 0, 'store_id' => $storeId]),
  121. 'delivery' => $this->dao->count(['pid' => 0, 'type' => 7, 'is_system_del' => 0, 'store_id' => $storeId]),
  122. 'writeoff' => $this->dao->count(['pid' => 0, 'type' => 5, 'is_system_del' => 0, 'store_id' => $storeId]),
  123. ];
  124. }
  125. /**
  126. * 获取列表
  127. * @param array $where
  128. * @param array $field
  129. * @param array $with
  130. * @param bool $abridge
  131. * @param string $order
  132. * @return array
  133. * @throws \think\db\exception\DataNotFoundException
  134. * @throws \think\db\exception\DbException
  135. * @throws \think\db\exception\ModelNotFoundException
  136. */
  137. public function getOrderList(array $where, array $field = ['*'], array $with = [], bool $abridge = false, string $order = 'add_time DESC,id DESC')
  138. {
  139. [$page, $limit] = $this->getPageValue();
  140. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, $order);
  141. $count = $this->dao->count($where);
  142. $stat = [];
  143. $batch_url = "file/upload/1";
  144. if ($data) {
  145. $data = $this->tidyOrderList($data, true, $abridge);
  146. foreach ($data as &$item) {
  147. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  148. $cart_num = 0;
  149. foreach ($item['_info'] as &$items) {
  150. if (isset($items['cart_info']['is_gift']) && $items['cart_info']['is_gift']) continue;
  151. $cart_num += $items['cart_info']['cart_num'];
  152. $cart_ids = [];
  153. $cart_ids[] = ['cart_id' => $items['cart_info']['id'], 'cart_num' => $items['cart_info']['cart_num']];
  154. /** @var StoreOrderSplitServices $storeOrderSpliteServices */
  155. $storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
  156. $cartInfos = $storeOrderSpliteServices->getSplitOrderCartInfo($item['id'], $cart_ids, $item);
  157. $total_price = $pay_postage = 0;
  158. foreach ($cartInfos as $cart) {
  159. $_info = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  160. $total_price = bcadd((string)$total_price, bcmul((string)($_info['truePrice'] ?? 0), (string)$cart['cart_num'], 4), 2);
  161. if (!in_array($item['shipping_type'], [2, 4])) {
  162. $pay_postage = bcadd((string)$pay_postage, (string)($_info['postage_price'] ?? 0), 2);
  163. }
  164. }
  165. //实际退款金额
  166. $refund_pay_price = bcadd((string)$total_price, (string)$pay_postage, 2);
  167. if (isset($item['change_price']) && (float)$item['change_price']) {//有改价 且是拆分
  168. //订单原实际支付金额
  169. $order_pay_price = bcadd((string)$item['change_price'], (string)$item['pay_price'], 2);
  170. $refund_price = bcmul((string)bcdiv((string)$item['pay_price'], (string)$order_pay_price, 4), (string)$refund_pay_price, 2);
  171. } else {
  172. $refund_price = $refund_pay_price;
  173. }
  174. $items['cart_info']['refund_price'] = $refund_price;
  175. }
  176. $item['is_all_refund'] = $refund_num == $cart_num;
  177. }
  178. }
  179. return compact('data', 'count', 'stat', 'batch_url');
  180. }
  181. /**获取单个订单信息
  182. * @param string $key
  183. * @param int $uid
  184. * @param array $with
  185. * @return array|\think\Model|null
  186. * @throws \think\db\exception\DataNotFoundException
  187. * @throws \think\db\exception\DbException
  188. * @throws \think\db\exception\ModelNotFoundException
  189. */
  190. public function getOneOrderList(string $key, int $uid, array $with = [])
  191. {
  192. return $this->dao->getUserOrderDetail($key, $uid, array_merge(['user', 'spread', 'refund'], $with));
  193. }
  194. /**
  195. * 获取列表
  196. * @param array $where
  197. * @return array
  198. * @throws \think\db\exception\DataNotFoundException
  199. * @throws \think\db\exception\DbException
  200. * @throws \think\db\exception\ModelNotFoundException
  201. */
  202. public function getSplitOrderList(array $where, array $field = ['*'], array $with = [])
  203. {
  204. $data = $this->dao->getOrderList($where, $field, 0, 0, $with);
  205. if ($data) {
  206. $data = $this->tidyOrderList($data);
  207. /** @var StoreOrderStatusServices $statusServices */
  208. $statusServices = app()->make(StoreOrderStatusServices::class);
  209. foreach ($data as &$item) {
  210. $log = $statusServices->getColumn(['oid' => $item['id']], 'change_time', 'change_type');
  211. if (isset($log['delivery'])) {
  212. $delivery = date('Y-m-d H:i:s', $log['delivery']);
  213. } elseif (isset($log['delivery_goods'])) {
  214. $delivery = date('Y-m-d H:i:s', $log['delivery_goods']);
  215. } elseif (isset($log['delivery_fictitious'])) {
  216. $delivery = date('Y-m-d H:i:s', $log['delivery_fictitious']);
  217. } else {
  218. $delivery = '';
  219. }
  220. $item['delivery_time'] = $delivery;
  221. }
  222. }
  223. return $data;
  224. }
  225. /**
  226. * 前端订单列表
  227. * @param array $where
  228. * @param array|string[] $field
  229. * @param array $with
  230. * @return array
  231. * @throws \think\db\exception\DataNotFoundException
  232. * @throws \think\db\exception\DbException
  233. * @throws \think\db\exception\ModelNotFoundException
  234. */
  235. public function getOrderApiList(array $where, array $field = ['*'], array $with = [])
  236. {
  237. [$page, $limit] = $this->getPageValue();
  238. if (isset($where['status']) && $where['status'] === '') {
  239. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, 'id DESC');
  240. } else {
  241. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with);
  242. }
  243. foreach ($data as &$item) {
  244. $item = $this->tidyOrder($item, true);
  245. $cart_num = 0;
  246. foreach ($item['cartInfo'] ?: [] as $key => $product) {
  247. if (isset($item['_status']['_type']) && $item['_status']['_type'] == 3) {
  248. $item['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', (int)$product['add_time']) : '时间错误';
  249. }
  250. $item['cartInfo'][$key]['productInfo']['price'] = $product['truePrice'] ?? 0;
  251. if (isset($product['is_gift']) && $product['is_gift']) continue;
  252. $cart_num += $product['cart_num'];
  253. }
  254. if (count($item['refund'])) {
  255. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  256. $item['is_all_refund'] = $refund_num == $cart_num;
  257. } else {
  258. $item['is_all_refund'] = false;
  259. }
  260. }
  261. return $data;
  262. }
  263. /**
  264. * 获取订单数量
  265. * @param int $uid
  266. * @param int $store_id
  267. * @param int $plat_type
  268. * @return array
  269. */
  270. public function getOrderData(int $uid = 0, int $store_id = -1, int $plat_type = -1)
  271. {
  272. $where = ['pid' => 0, 'uid' => $uid, 'is_del' => 0, 'is_system_del' => 0, 'plat_type' => $plat_type];
  273. $countWhere = [];
  274. if ($store_id != -1) {
  275. $where['store_id'] = $store_id;
  276. $countWhere['store_id'] = $store_id;
  277. }
  278. $data['order_count'] = (string)$this->dao->count($where);
  279. $where = $where + ['paid' => 1];
  280. $data['sum_price'] = (string)$this->dao->sum($where, 'pay_price', true);
  281. // $countWhere = $store_id != -1 ? ['pid' => 0, 'store_id' => $store_id] : ['pid' => 0];
  282. if ($uid) {
  283. $countWhere['uid'] = $uid;
  284. }
  285. if ($plat_type != -1) {
  286. $countWhere['plat_type'] = $plat_type;
  287. }
  288. $pid_where = ['pid' => 0];
  289. $not_pid_where = ['not_pid' => 1];
  290. $data['unpaid_count'] = (string)$this->dao->count(['status' => 0] + $countWhere + $pid_where);
  291. $data['unshipped_count'] = (string)$this->dao->count(['status' => 1] + $countWhere + $pid_where);
  292. $data['received_count'] = (string)$this->dao->count(['status' => 2] + $countWhere + $pid_where);
  293. $data['evaluated_count'] = (string)$this->dao->count(['status' => 3] + $countWhere + $pid_where);
  294. $data['unwritoff_count'] = (string)$this->dao->count(['status' => 5] + $countWhere);
  295. $data['complete_count'] = (string)$this->dao->count(['status' => 4] + $countWhere + $pid_where);
  296. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  297. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  298. $refund_where = ['is_cancel' => 0];
  299. if ($uid) $refund_where['uid'] = $uid;
  300. if ($store_id != -1) $refund_where['store_id'] = $store_id;
  301. $data['refunding_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [1, 2, 4, 5]]);
  302. $data['refunded_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [3, 6]]);
  303. $data['refund_count'] = (string)bcadd($data['refunding_count'], $data['refunded_count'], 0);
  304. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  305. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  306. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  307. return $data;
  308. }
  309. /**
  310. * 订单详情数据格式化
  311. * @param $order
  312. * @param bool $detail 是否需要订单商品详情
  313. * @param bool $isPic 是否需要订单状态图片
  314. * @return mixed
  315. */
  316. public function tidyOrder($order, bool $detail = false, bool $isPic = false)
  317. {
  318. if ($detail == true && isset($order['id'])) {
  319. /** @var StoreOrderCartInfoServices $cartServices */
  320. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  321. $cartInfos = $cartServices->getCartColunm(['oid' => $order['id']], 'cart_num,is_writeoff,surplus_num,cart_info,refund_num,product_type,is_support_refund,is_gift,promotions_id,type,relation_id,write_times,write_surplus_times,write_start,write_end', 'unique');
  322. $info = [];
  323. /** @var StoreProductReplyServices $replyServices */
  324. $replyServices = app()->make(StoreProductReplyServices::class);
  325. foreach ($cartInfos as $k => $cartInfo) {
  326. $cart = json_decode($cartInfo['cart_info'], true);
  327. $cart['cart_num'] = $cartInfo['cart_num'];
  328. $cart['is_writeoff'] = $cartInfo['is_writeoff'];
  329. $cart['surplus_num'] = $cartInfo['write_surplus_times'];
  330. $cart['refund_num'] = $cartInfo['refund_num'];
  331. $cart['write_times'] = $cartInfo['write_times'];
  332. $cart['write_surplus_times'] = $cartInfo['write_surplus_times'];
  333. $cart['write_start'] = $cartInfo['write_start'];
  334. $cart['write_end'] = $cartInfo['write_end'];
  335. $cart['write_off'] = max(bcsub((string)$cart['write_times'], (string)$cart['write_surplus_times'], 0), 0);
  336. $cart['product_type'] = $cartInfo['product_type'];
  337. $cart['supplier_id'] = $cart['store_id'] = 0;
  338. if ($cartInfo['type'] == 1) {
  339. $cart['store_id'] = $cartInfo['relation_id'] ?? 0;
  340. } elseif ($cartInfo['type'] == 2) {
  341. $cart['supplier_id'] = $cartInfo['relation_id'] ?? 0;
  342. }
  343. $cart['is_support_refund'] = $cartInfo['is_support_refund'];
  344. $cart['is_gift'] = $cartInfo['is_gift'];
  345. $cart['promotions_id'] = $cartInfo['promotions_id'];
  346. $cart['unique'] = $k;
  347. //新增是否评价字段
  348. $cart['is_reply'] = $replyServices->count(['unique' => $k]);
  349. if (isset($cart['productInfo']['attrInfo'])) {
  350. $cart['productInfo']['attrInfo'] = get_thumb_water($cart['productInfo']['attrInfo']);
  351. }
  352. $cart['productInfo'] = get_thumb_water($cart['productInfo']);
  353. //一种商品买多件 计算总优惠
  354. $cart['vip_sum_truePrice'] = bcmul($cart['vip_truePrice'], $cart['cart_num'] ? $cart['cart_num'] : 1, 2);
  355. $cart['is_valid'] = 1;
  356. array_push($info, $cart);
  357. unset($cart);
  358. }
  359. $order['cartInfo'] = $info;
  360. }
  361. /** @var StoreOrderStatusServices $statusServices */
  362. $statusServices = app()->make(StoreOrderStatusServices::class);
  363. $status = [];
  364. $storeInfo = [];
  365. if ($order['store_id']) {
  366. $storeServices = app()->make(SystemStoreServices::class);
  367. $storeInfo = $storeServices->get((int)$order['store_id']);
  368. }
  369. //系统预设取消订单时间段
  370. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  371. //获取配置
  372. $systemValue = SystemConfigService::more($keyValue);
  373. //格式化数据
  374. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  375. switch ($order['type'] ?? 0) {
  376. case 1://秒杀
  377. $secs = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  378. break;
  379. case 2://砍价
  380. $secs = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  381. break;
  382. case 3://拼团
  383. $secs = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  384. break;
  385. default:
  386. $secs = $systemValue['order_cancel_time'];
  387. break;
  388. }
  389. $order['stop_time'] = $secs * 3600 + $order['add_time'];
  390. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  391. $status['_type'] = 9;
  392. $status['_title'] = '线下付款,未支付';
  393. $status['_msg'] = '等待商家处理,请耐心等待';
  394. $status['_class'] = 'nobuy';
  395. } else if (!$order['paid']) {
  396. $status['_type'] = 0;
  397. $status['_title'] = '未支付';
  398. $status['_msg'] = '请在' . date('m-d H:i:s', $order['stop_time']) . '前完成支付!';
  399. $status['_class'] = 'nobuy';
  400. } else if ($order['refund_status'] == 2) {
  401. $status['_type'] = -2;
  402. $status['_title'] = '已退款';
  403. $status['_msg'] = '已为您退款,感谢您的支持';
  404. $status['_class'] = 'state-sqtk';
  405. } else if ($order['status'] == 4) {
  406. if ($order['delivery_type'] == 'send') {// 送货
  407. $status['_type'] = 2;
  408. $status['_title'] = '待收货';
  409. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已送货';
  410. $status['_class'] = 'state-ysh';
  411. } elseif ($order['delivery_type'] == 'express') {// 发货
  412. $status['_type'] = 2;
  413. $status['_title'] = '待收货';
  414. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  415. $status['_class'] = 'state-ysh';
  416. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  417. $status['_type'] = 2;
  418. $status['_title'] = '待收货';
  419. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_part_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  420. $status['_class'] = 'state-ysh';
  421. } else {
  422. $status['_type'] = 2;
  423. $status['_title'] = '待收货';
  424. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  425. $status['_class'] = 'state-ysh';
  426. }
  427. } elseif ($order['status'] == 5) {
  428. if ($order['shipping_type'] == 2) {
  429. $status['_type'] = 5;
  430. $status['_title'] = '部分核销';
  431. $status['_msg'] = '部分核销,请继续进行核销';
  432. $status['_class'] = 'state-nfh';
  433. } else {
  434. $status['_type'] = 2;
  435. $status['_title'] = '待收货';
  436. $status['_msg'] = '部分核销收货,请继续进行核销';
  437. $status['_class'] = 'state-ysh';
  438. }
  439. } else if ($order['refund_status'] == 1) {
  440. if (in_array($order['refund_type'], [0, 1, 2])) {
  441. $status['_type'] = -1;
  442. $status['_title'] = '申请退款中';
  443. $status['_msg'] = '商家审核中,请耐心等待';
  444. $status['_class'] = 'state-sqtk';
  445. } elseif ($order['refund_type'] == 4) {
  446. $status['_type'] = -1;
  447. $status['_title'] = '申请退款中';
  448. $status['_msg'] = '商家同意退款,请填写退货订单号';
  449. $status['_class'] = 'state-sqtk';
  450. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  451. $status['refund_name'] = sys_config('refund_name', '');
  452. $status['refund_phone'] = sys_config('refund_phone', '');
  453. $status['refund_address'] = sys_config('refund_address', '');
  454. } else {
  455. $status['refund_name'] = $storeInfo['name'];
  456. $status['refund_phone'] = $storeInfo['phone'];
  457. $status['refund_address'] = $storeInfo['detailed_address'];
  458. }
  459. } elseif ($order['refund_type'] == 5) {
  460. $status['_type'] = -1;
  461. $status['_title'] = '申请退款中';
  462. $status['_msg'] = '等待商家收货';
  463. $status['_class'] = 'state-sqtk';
  464. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  465. $status['refund_name'] = sys_config('refund_name', '');
  466. $status['refund_phone'] = sys_config('refund_phone', '');
  467. $status['refund_address'] = sys_config('refund_address', '');
  468. } else {
  469. $status['refund_name'] = $storeInfo['name'];
  470. $status['refund_phone'] = $storeInfo['phone'];
  471. $status['refund_address'] = $storeInfo['detailed_address'];
  472. }
  473. }
  474. } else if ($order['refund_status'] == 3) {
  475. $status['_type'] = -1;
  476. $status['_title'] = '部分退款(子订单)';
  477. $status['_msg'] = '拆分发货,部分退款';
  478. $status['_class'] = 'state-sqtk';
  479. } else if ($order['refund_status'] == 4) {
  480. $status['_type'] = -1;
  481. $status['_title'] = '子订单已全部申请退款中';
  482. $status['_msg'] = '拆分发货,全部退款';
  483. $status['_class'] = 'state-sqtk';
  484. } else if (!$order['status']) {
  485. if ($order['pink_id']) {
  486. /** @var StorePinkServices $pinkServices */
  487. $pinkServices = app()->make(StorePinkServices::class);
  488. if ($pinkServices->getCount(['id' => $order['pink_id'], 'status' => 1])) {
  489. $status['_type'] = 1;
  490. $status['_title'] = '拼团中';
  491. $status['_msg'] = '等待其他人参加拼团';
  492. $status['_class'] = 'state-nfh';
  493. } else if (in_array($order['shipping_type'], [1, 3])) {
  494. $status['_type'] = 1;
  495. $status['_title'] = '未发货';
  496. $status['_msg'] = '商家未发货,请耐心等待';
  497. $status['_class'] = 'state-nfh';
  498. } else {
  499. $status['_type'] = 5;
  500. $status['_title'] = '待核销';
  501. $status['_msg'] = '待核销,请到核销点进行核销';
  502. $status['_class'] = 'state-nfh';
  503. }
  504. } else {
  505. if (in_array($order['shipping_type'], [1, 3])) {
  506. $status['_type'] = 1;
  507. $status['_title'] = '未发货';
  508. $status['_msg'] = '商家未发货,请耐心等待';
  509. $status['_class'] = 'state-nfh';
  510. } else {
  511. $status['_type'] = 5;
  512. $status['_title'] = '待核销';
  513. $status['_msg'] = '待核销,请到核销点进行核销';
  514. $status['_class'] = 'state-nfh';
  515. }
  516. }
  517. } else if ($order['status'] == 1) {
  518. if ($order['delivery_type'] == 'send') {// 配送
  519. $status['_type'] = 2;
  520. $status['_title'] = '待收货';
  521. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已发货';
  522. $status['_class'] = 'state-ysh';
  523. } elseif ($order['delivery_type'] == 'express') {// 发货
  524. $status['_type'] = 2;
  525. $status['_title'] = '待收货';
  526. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  527. $status['_class'] = 'state-ysh';
  528. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  529. $status['_type'] = 2;
  530. $status['_title'] = '待收货';
  531. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  532. $status['_class'] = 'state-ysh';
  533. } else {
  534. $status['_type'] = 2;
  535. $status['_title'] = '待收货';
  536. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  537. $status['_class'] = 'state-ysh';
  538. }
  539. } else if ($order['status'] == 2) {
  540. $status['_type'] = 3;
  541. $status['_title'] = '待评价';
  542. $status['_msg'] = '已收货,快去评价一下吧';
  543. $status['_class'] = 'state-ypj';
  544. } else if ($order['status'] == 3) {
  545. $status['_type'] = 4;
  546. $status['_title'] = '交易完成';
  547. $status['_msg'] = '交易完成,感谢您的支持';
  548. $status['_class'] = 'state-ytk';
  549. }
  550. if (isset($order['pay_type']))
  551. $status['_payType'] = ($status['_type'] ?? 0) == 0 ? '' : PayServices::PAY_TYPE[$order['pay_type']] ?? '其他方式';
  552. if (isset($order['delivery_type']))
  553. $status['_deliveryType'] = isset($this->deliveryType[$order['delivery_type']]) ? $this->deliveryType[$order['delivery_type']] : '其他方式';
  554. $order['_status'] = $status;
  555. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : '';
  556. $order['_add_time'] = isset($order['add_time']) ? (strstr((string)$order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  557. $order['status_pic'] = '';
  558. //获取商品状态图片
  559. if ($isPic) {
  560. try {
  561. $order_details_images = sys_data('order_details_images') ?: [];
  562. $order_details_images = array_combine(array_column($order_details_images, 'order_status'), $order_details_images);
  563. $_type = $order['_status']['_type'] == 5 ? 2 : $order['_status']['_type'];
  564. $order['status_pic'] = $order_details_images[$_type]['pic'] ?? '';
  565. } catch (\Throwable $e) {
  566. }
  567. }
  568. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? 2;
  569. //自购返佣
  570. if ($order['uid'] == $order['spread_uid']) {
  571. $order['spread_nickname'] = isset($order['spread_nickname']) ? $order['spread_nickname'] . '(自购)' : '';
  572. }
  573. $order['longitude'] = $order['latitude'] = '';
  574. //处理地址定位
  575. if (isset($order['user_location']) && $order['user_location']) {
  576. [$longitude, $latitude] = explode(' ', $order['user_location']);
  577. $order['longitude'] = $longitude;
  578. $order['latitude'] = $latitude;
  579. }
  580. return $order;
  581. }
  582. /**
  583. * 整理订单类型
  584. * @param $order
  585. * @param bool $abridge
  586. * @return string[]
  587. */
  588. public function tidyOrderType($order, bool $abridge = false)
  589. {
  590. $pink_name = $color = '';
  591. if ($order && isset($order['type'])) {
  592. switch ($order['type']) {
  593. case 0://普通订单
  594. if ($order['shipping_type'] == 1) {
  595. $pink_name = $abridge ? '普通' : '[普通订单]';
  596. $color = '#895612';
  597. } else if ($order['shipping_type'] == 2) {
  598. $pink_name = $abridge ? '核销' : '[核销订单]';
  599. $color = '#8956E8';
  600. } else if ($order['shipping_type'] == 3) {
  601. $pink_name = $abridge ? '分配' : '[分配订单]';
  602. $color = '#FFA21B';
  603. } else if ($order['shipping_type'] == 4) {
  604. $pink_name = $abridge ? '收银' : '[收银订单]';
  605. $color = '#2EC479';
  606. }
  607. break;
  608. case 1://秒杀
  609. $pink_name = $abridge ? '秒杀' : '[秒杀订单]';
  610. $color = '#32c5e9';
  611. break;
  612. case 2://砍价
  613. $pink_name = $abridge ? '砍价' : '[砍价订单]';
  614. $color = '#12c5e9';
  615. break;
  616. case 3://拼团
  617. if (isset($order['pinkStatus'])) {
  618. switch ($order['pinkStatus']) {
  619. case 1:
  620. $pink_name = $abridge ? '拼团' : '[拼团订单]正在进行中';
  621. $color = '#f00';
  622. break;
  623. case 2:
  624. $pink_name = $abridge ? '拼团' : '[拼团订单]已完成';
  625. $color = '#00f';
  626. break;
  627. case 3:
  628. $pink_name = $abridge ? '拼团' : '[拼团订单]未完成';
  629. $color = '#f0f';
  630. break;
  631. default:
  632. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  633. $color = '#457856';
  634. break;
  635. }
  636. } else {
  637. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  638. $color = '#457856';
  639. }
  640. break;
  641. case 4://积分
  642. $pink_name = $abridge ? '积分' : '[积分订单]';
  643. $color = '#12c5e9';
  644. break;
  645. case 5://套餐
  646. $pink_name = $abridge ? '优惠' : '[优惠套餐]';
  647. $color = '#12c5e9';
  648. break;
  649. case 6://预售
  650. $pink_name = $abridge ? '预售' : '[预售订单]';
  651. $color = '#12c5e9';
  652. break;
  653. case 7://新人礼
  654. $pink_name = $abridge ? '新人礼' : '[新人专享]';
  655. $color = '#12c5e9';
  656. break;
  657. case 8://抽奖
  658. $pink_name = $abridge ? '抽奖' : '[抽奖订单]';
  659. $color = '#12c5e9';
  660. break;
  661. case 9://拼单
  662. $pink_name = $abridge ? '拼单' : '[拼单订单]';
  663. $color = '#12c5e9';
  664. break;
  665. case 10://桌码
  666. $pink_name = $abridge ? '桌码' : '[桌码订单]';
  667. $color = '#F5222D';
  668. break;
  669. }
  670. }
  671. return [$pink_name, $color];
  672. }
  673. /**
  674. * 数据转换
  675. * @param array $data
  676. * @param bool $is_cart_info
  677. * @return array|null
  678. */
  679. public function tidyOrderList(array $data, bool $is_cart_info = true, bool $abridge = false)
  680. {
  681. if (!$data) {
  682. return $data;
  683. }
  684. /** @var StoreOrderCartInfoServices $services */
  685. $services = app()->make(StoreOrderCartInfoServices::class);
  686. foreach ($data as &$item) {
  687. if ($is_cart_info) $item['_info'] = $services->getOrderCartInfo((int)$item['id']);
  688. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  689. $item['_refund_time'] = isset($item['refund_reason_time']) && $item['refund_reason_time'] ? date('Y-m-d H:i:s', $item['refund_reason_time']) : '';
  690. $item['_pay_time'] = isset($item['pay_time']) && $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
  691. [$pink_name, $color] = $this->tidyOrderType($item, $abridge);
  692. $item['pink_name'] = $pink_name;
  693. $item['color'] = $color;
  694. if ($item['paid'] == 1) {
  695. switch ($item['pay_type']) {
  696. case PayServices::WEIXIN_PAY:
  697. $item['pay_type_name'] = '微信支付';
  698. break;
  699. case PayServices::YUE_PAY:
  700. $item['pay_type_name'] = '余额支付';
  701. break;
  702. case PayServices::OFFLINE_PAY:
  703. $item['pay_type_name'] = '线下支付';
  704. break;
  705. case PayServices::ALIAPY_PAY:
  706. $item['pay_type_name'] = '支付宝支付';
  707. break;
  708. case PayServices::CASH_PAY:
  709. $item['pay_type_name'] = '现金支付';
  710. break;
  711. default:
  712. $item['pay_type_name'] = '其他支付';
  713. break;
  714. }
  715. } else {
  716. switch ($item['pay_type']) {
  717. default:
  718. $item['pay_type_name'] = '未支付';
  719. break;
  720. case 'offline':
  721. $item['pay_type_name'] = '线下支付';
  722. $item['pay_type_info'] = 1;
  723. break;
  724. }
  725. }
  726. $status_name = ['status_name' => '', 'pics' => []];
  727. if ($item['is_del'] || $item['is_system_del']) {
  728. $status_name['status_name'] = '已删除';
  729. $item['_status'] = -1;
  730. } else if ($item['paid'] == 0 && $item['status'] == 0) {
  731. $status_name['status_name'] = '未支付';
  732. $item['_status'] = 1;//未支付
  733. } else if ($item['paid'] == 1 && $item['status'] == 4 && in_array($item['shipping_type'], [1, 3]) && $item['refund_status'] == 0) {
  734. $status_name['status_name'] = '部分发货';
  735. $item['_status'] = 8;//已支付 部分发货
  736. } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
  737. $status_name['status_name'] = '已退款';
  738. $item['_status'] = 7;//已支付 已退款
  739. } else if ($item['paid'] == 1 && $item['status'] == 5 && $item['refund_status'] == 0) {
  740. $status_name['status_name'] = $item['shipping_type'] == 2 ? '部分核销' : '部分收货';
  741. $item['_status'] = 12;//已支付 部分核销
  742. } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
  743. $item['_status'] = 3;//已支付 申请退款中
  744. $refundReasonTime = $item['refund_reason_time'] ? date('Y-m-d H:i', $item['refund_reason_time']) : '';
  745. $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
  746. $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
  747. $img = [];
  748. if (count($refundReasonWapImg)) {
  749. foreach ($refundReasonWapImg as $itemImg) {
  750. if (strlen(trim($itemImg)))
  751. $img[] = $itemImg;
  752. }
  753. }
  754. $status_name['status_name'] = <<<HTML
  755. <b style="color:#f124c7">申请退款</b><br/>
  756. <span>退款原因:{$item['refund_reason_wap']}</span><br/>
  757. <span>备注说明:{$item['refund_reason_wap_explain']}</span><br/>
  758. <span>退款时间:{$refundReasonTime}</span><br/>
  759. <span>退款凭证:</span>
  760. HTML;
  761. $status_name['pics'] = $img;
  762. } else if ($item['paid'] == 1 && $item['refund_status'] == 4) {
  763. $item['_status'] = 10;//拆单发货 已全部申请退款
  764. $status_name['status_name'] = '退款中';
  765. } else if ($item['paid'] == 1 && $item['status'] == 0 && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  766. $status_name['status_name'] = '未发货';
  767. $item['_status'] = 2;//已支付 未发货
  768. } else if ($item['paid'] == 1 && in_array($item['status'], [0, 1]) && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
  769. $status_name['status_name'] = '未核销';
  770. $item['_status'] = 11;//已支付 待核销
  771. } else if ($item['paid'] == 1 && in_array($item['status'], [1, 5]) && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  772. $status_name['status_name'] = '待收货';
  773. $item['_status'] = 4;//已支付 待收货
  774. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  775. $status_name['status_name'] = '待评价';
  776. $item['_status'] = 5;//已支付 待评价
  777. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  778. $status_name['status_name'] = '已完成';
  779. $item['_status'] = 6;//已支付 已完成
  780. } else if ($item['paid'] == 1 && $item['refund_status'] == 3) {
  781. $item['_status'] = 9;//拆单发货 部分申请退款
  782. $status_name['status_name'] = '部分退款';
  783. }
  784. $item['status_name'] = $status_name;
  785. if ($item['store_id'] == 0 && $item['clerk_id'] == 0 && !isset($item['clerk_name'])) {
  786. $item['clerk_name'] = '总平台';
  787. }
  788. //根据核销员更改store_name
  789. if ($item['clerk_id'] && isset($item['staff_store_id']) && $item['staff_store_id']) {
  790. /** @var SystemStoreServices $store */
  791. $store = app()->make(SystemStoreServices::class);
  792. $storeOne = $store->value(['id' => $item['staff_store_id']], 'name');
  793. if ($storeOne) $item['store_name'] = $storeOne;
  794. }
  795. //自购返佣
  796. if ($item['uid'] == $item['spread_uid']) {
  797. $item['spread_nickname'] = isset($item['spread_nickname']) ? $item['spread_nickname'] . '(自购)' : '';
  798. }
  799. }
  800. return $data;
  801. }
  802. /**
  803. * 处理订单金额
  804. * @param $where
  805. * @return array
  806. */
  807. public function getOrderPrice($where)
  808. {
  809. // $where['pid'] = 0;//子订单不统计
  810. $whereData = [];
  811. $price['today_count_sum'] = 0; //今日订单总数
  812. $price['count_sum'] = 0; //订单总数
  813. $price['pay_price'] = 0;//支付金额
  814. $price['today_pay_price'] = 0;//今日支付金额
  815. if ($where['status'] == '') {
  816. $whereData['paid'] = 1;
  817. $whereData['refund_status'] = [0, 3];
  818. }
  819. $not_pid = $where;
  820. unset($not_pid['pid']);
  821. $not_pid['not_pid'] = 1;
  822. $sumNumber = $this->dao->search($where + $whereData)->field([
  823. 'count(id) as count_sum',
  824. ])->find();
  825. $price['count_sum'] = $sumNumber && $sumNumber['count_sum'] ? $sumNumber['count_sum'] : 0;
  826. $sumNumber = $this->dao->search($whereData + $where)->field([
  827. 'sum(pay_price) as sum_pay_price',
  828. ])->find();
  829. $price['pay_price'] = $sumNumber && $sumNumber['sum_pay_price'] ? $sumNumber['sum_pay_price'] : 0;
  830. $where['time'] = 'today';
  831. $not_pid['time'] = 'today';
  832. $sumNumber = $this->dao->search($where + $whereData)->field([
  833. 'count(id) as today_count_sum',
  834. ])->find();
  835. $price['today_count_sum'] = $sumNumber && $sumNumber['today_count_sum'] ? $sumNumber['today_count_sum'] : 0;
  836. $sumNumber = $this->dao->search($whereData + $where + ['paid' => 1])->field([
  837. 'sum(pay_price) as today_pay_price',
  838. ])->find();
  839. $price['today_pay_price'] = $sumNumber && $sumNumber['today_pay_price'] ? $sumNumber['today_pay_price'] : 0;
  840. return $price;
  841. }
  842. /**
  843. * 获取订单列表页面统计数据
  844. * @param $where
  845. * @return array
  846. */
  847. public function getBadge($where)
  848. {
  849. $price = $this->getOrderPrice($where);
  850. return [
  851. [
  852. 'name' => '订单数量',
  853. 'field' => '件',
  854. 'count' => $price['count_sum'],
  855. 'className' => 'md-basket',
  856. 'col' => 6
  857. ],
  858. [
  859. 'name' => '订单金额',
  860. 'field' => '元',
  861. 'count' => $price['pay_price'],
  862. 'className' => 'md-pricetags',
  863. 'col' => 6
  864. ],
  865. [
  866. 'name' => '今日订单数量',
  867. 'field' => '件',
  868. 'count' => $price['today_count_sum'],
  869. 'className' => 'ios-chatbubbles',
  870. 'col' => 6
  871. ],
  872. [
  873. 'name' => '今日支付金额',
  874. 'field' => '元',
  875. 'count' => $price['today_pay_price'],
  876. 'className' => 'ios-cash',
  877. 'col' => 6
  878. ],
  879. ];
  880. }
  881. /**
  882. *
  883. * @param array $where
  884. * @return mixed
  885. */
  886. public function orderStoreCount(array $where)
  887. {
  888. $defaultWhere = ['time' => $where['time'], 'store_id' => $where['store_id'] ?? 0, 'is_system_del' => 0];
  889. if (isset($where['store_id'])) {
  890. $defaultWhere['store_id'] = $where['store_id'];
  891. }
  892. //全部订单
  893. $data['all'] = (string)$this->dao->count(['pid' => 0] + $defaultWhere);
  894. //普通订单
  895. $data['general'] = (string)$this->dao->count(['pid' => 0, 'type' => 0] + $defaultWhere);
  896. //拼团订单
  897. $data['pink'] = (string)$this->dao->count(['pid' => 0, 'type' => 3] + $defaultWhere);
  898. //秒杀订单
  899. $data['seckill'] = (string)$this->dao->count(['pid' => 0, 'type' => 1] + $defaultWhere);
  900. //砍价订单
  901. $data['bargain'] = (string)$this->dao->count(['pid' => 0, 'type' => 2] + $defaultWhere);
  902. //收银订单
  903. $data['cashier'] = (string)$this->dao->count(['pid' => 0, 'type' => 6] + $defaultWhere);
  904. $data['write_off'] = (string)$this->dao->count(['pid' => 0, 'type' => 5] + $defaultWhere);
  905. $data['delivery'] = (string)$this->dao->count(['pid' => 0, 'type' => 7] + $defaultWhere);
  906. //预售订单
  907. $data['presale'] = (string)$this->dao->count(['pid' => 0, 'type' => 8] + $defaultWhere);
  908. switch ($where['type']) {
  909. case 0:
  910. $data['statusAll'] = $data['general'];
  911. break;
  912. case 1:
  913. $data['statusAll'] = $data['seckill'];
  914. break;
  915. case 2:
  916. $data['statusAll'] = $data['bargain'];
  917. break;
  918. case 3:
  919. $data['statusAll'] = $data['pink'];
  920. break;
  921. case 4:
  922. break;
  923. case 5:
  924. $data['statusAll'] = $data['write_off'];
  925. break;
  926. case 6:
  927. $data['statusAll'] = $data['cashier'];
  928. break;
  929. case 7:
  930. $data['statusAll'] = $data['delivery'];
  931. break;
  932. case 8:
  933. $data['statusAll'] = $data['presale'];
  934. break;
  935. default:
  936. $data['statusAll'] = $data['all'];
  937. }
  938. $count_where = ['pid' => 0, 'type' => $where['type']] + $defaultWhere;
  939. //未支付
  940. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  941. //未发货
  942. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1]);
  943. //部分发货
  944. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7]);
  945. //待收货
  946. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2]);
  947. //待核销
  948. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  949. //已核销
  950. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  951. //待评价
  952. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  953. //交易完成
  954. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  955. //退款中
  956. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  957. //已退款
  958. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  959. //删除订单
  960. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  961. return $data;
  962. }
  963. /**
  964. *
  965. * @param array $where
  966. * @return mixed
  967. */
  968. public function orderCount(array $where)
  969. {
  970. $default_where = [
  971. 'pid' => [0, -1],
  972. 'time' => $where['time'],
  973. 'status' => $where['status'],
  974. 'pay_type' => $where['pay_type'],
  975. 'field_key' => $where['field_key'],
  976. 'real_name' => $where['real_name'],
  977. 'is_system_del' => 0
  978. ];
  979. $count_where = ['type' => $where['type'] ?? 0, 'store_id' => $where['store_id'] ?? 0, 'supplier_id' => $where['supplier_id'] ?? 0];
  980. // if ($count_where['store_id'] || $count_where['supplier_id'] || (isset($where['plat_type']) && in_array($where['plat_type'], [1, 2]))) {
  981. // $default_where['pid'] = 0;
  982. // }
  983. //全部订单
  984. $data['all'] = (string)$this->dao->count($default_where + $count_where);
  985. //普通订单
  986. $data['general'] = (string)$this->dao->count(['type' => 0] + $default_where + $count_where);
  987. //平台订单
  988. $data['plat'] = (string)$this->dao->count(['plat_type' => 0, 'pid' => 0] + $default_where + $count_where);
  989. //门店订单
  990. $data['store'] = (string)$this->dao->count(['plat_type' => 1, 'pid' => 0] + $default_where + $count_where);
  991. //供应商订单
  992. $data['supplier'] = (string)$this->dao->count(['plat_type' => 2, 'pid' => 0] + $default_where + $count_where);
  993. //拼团订单
  994. $data['pink'] = (string)$this->dao->count(['type' => 3] + $default_where);
  995. //秒杀订单
  996. $data['seckill'] = (string)$this->dao->count(['type' => 1] + $default_where);
  997. //砍价订单
  998. $data['bargain'] = (string)$this->dao->count(['type' => 2] + $default_where);
  999. //预售订单
  1000. $data['presale'] = (string)$this->dao->count(['type' => 8] + $default_where);
  1001. $data['statusAll'] = $data['all'];
  1002. if (trim($where['type'], ' ') !== '') {
  1003. switch ($where['type']) {
  1004. case 0:
  1005. $data['statusAll'] = $data['general'];
  1006. break;
  1007. case 1:
  1008. $data['statusAll'] = $data['seckill'];
  1009. break;
  1010. case 2:
  1011. $data['statusAll'] = $data['bargain'];
  1012. break;
  1013. case 3:
  1014. $data['statusAll'] = $data['pink'];
  1015. break;
  1016. case 4:
  1017. break;
  1018. case 8:
  1019. $data['statusAll'] = $data['presale'];
  1020. break;
  1021. default:
  1022. $data['statusAll'] = $data['all'];
  1023. }
  1024. }
  1025. $count_where = ['type' => $where['type']] + $default_where;
  1026. //未支付
  1027. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  1028. //未发货
  1029. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1, 'shipping_type' => 1]);
  1030. //部分发货
  1031. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7, 'shipping_type' => 1]);
  1032. //待收货
  1033. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2, 'shipping_type' => 1]);
  1034. //待核销
  1035. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  1036. //已核销
  1037. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  1038. //待评价
  1039. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  1040. //交易完成
  1041. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  1042. //退款中
  1043. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1044. //已退款
  1045. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1046. //删除订单
  1047. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  1048. return $data;
  1049. }
  1050. /**
  1051. * 创建修改订单表单
  1052. * @param int $id
  1053. * @return array
  1054. * @throws \FormBuilder\Exception\FormBuilderException
  1055. */
  1056. public function updateForm(int $id)
  1057. {
  1058. $product = $this->dao->get($id);
  1059. if (!$product) {
  1060. throw new ValidateException('Data does not exist!');
  1061. }
  1062. $f = [];
  1063. $f[] = Form::input('order_id', '订单编号', $product->getData('order_id'))->disabled(true);
  1064. $f[] = Form::number('total_price', '商品总价', (float)$product->getData('total_price'))->min(0)->disabled(true);
  1065. $f[] = Form::number('total_postage', '原始邮费', (float)$product->getData('total_postage'))->min(0)->disabled(true);
  1066. $f[] = Form::number('pay_postage', '实际支付邮费', (float)$product->getData('pay_postage') ?: 0)->disabled(true);
  1067. $f[] = Form::number('pay_price', '实际支付金额', (float)$product->getData('pay_price'))->min(0);
  1068. $f[] = Form::number('gain_integral', '赠送积分', (float)$product->getData('gain_integral') ?: 0)->precision(0);
  1069. return create_form('修改订单', $f, $this->url('/order/update/' . $id), 'PUT');
  1070. }
  1071. /**
  1072. * 修改订单
  1073. * @param int $id
  1074. * @param array $data
  1075. * @return mixed
  1076. * @throws \Exception
  1077. */
  1078. public function updateOrder(int $id, array $data)
  1079. {
  1080. $order = $this->dao->getOne(['id' => $id, 'is_del' => 0]);
  1081. if (!$order) {
  1082. throw new ValidateException('订单不存在或已删除');
  1083. }
  1084. if ($order['paid']) {
  1085. throw new ValidateException('订单已支付');
  1086. }
  1087. //限制改价金额两位小数
  1088. $data['pay_price'] = sprintf("%.2f", $data['pay_price']);
  1089. $pay_price = $order['pay_price'];
  1090. if ($order['change_price']) {//已经改过一次价
  1091. $pay_price = bcadd((string)$pay_price, (string)$order['change_price'], 2);
  1092. }
  1093. //记录改价优惠金额
  1094. $data['change_price'] = (float)bcsub((string)$pay_price, (string)($data['pay_price'] ?? 0), 2);
  1095. /** @var StoreOrderStatusServices $services */
  1096. $services = app()->make(StoreOrderStatusServices::class);
  1097. $this->transaction(function () use ($id, $order, $data, $services) {
  1098. $res = $this->dao->update($id, $data);
  1099. $res = $res && $services->save([
  1100. 'oid' => $id,
  1101. 'change_type' => 'order_edit',
  1102. 'change_time' => time(),
  1103. 'change_message' => '商品总价为:' . $order['pay_price'] . ' 修改实际支付金额为:' . $data['pay_price']
  1104. ]);
  1105. if ($res) {
  1106. return true;
  1107. } else {
  1108. throw new ValidateException('Modification failed');
  1109. }
  1110. });
  1111. //新订单号
  1112. // $order['order_id'] = $data['order_id'];
  1113. //改价提醒
  1114. event('order.price', [$order, $data['pay_price']]);
  1115. return true;
  1116. }
  1117. /**
  1118. * 订单图表
  1119. * @param $cycle
  1120. * @return array
  1121. */
  1122. public function orderCharts($cycle)
  1123. {
  1124. $datalist = [];
  1125. $where = [];
  1126. $series1 = ['normal' => ['color' => [
  1127. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1128. 'colorStops' => [
  1129. [
  1130. 'offset' => 0,
  1131. 'color' => '#69cdff'
  1132. ],
  1133. [
  1134. 'offset' => 0.5,
  1135. 'color' => '#3eb3f7'
  1136. ],
  1137. [
  1138. 'offset' => 1,
  1139. 'color' => '#1495eb'
  1140. ]
  1141. ]
  1142. ]]
  1143. ];
  1144. $series2 = ['normal' => ['color' => [
  1145. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1146. 'colorStops' => [
  1147. [
  1148. 'offset' => 0,
  1149. 'color' => '#6fdeab'
  1150. ],
  1151. [
  1152. 'offset' => 0.5,
  1153. 'color' => '#44d693'
  1154. ],
  1155. [
  1156. 'offset' => 1,
  1157. 'color' => '#2cc981'
  1158. ]
  1159. ]
  1160. ]]
  1161. ];
  1162. $chartdata = [];
  1163. $data = [];//临时
  1164. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1165. $chartdata['yAxis']['maxprice'] = 0;//最大值金额
  1166. switch ($cycle) {
  1167. case 'thirtyday':
  1168. //上期
  1169. $datebefor = date('Y-m-d 00:00:00', strtotime('-59 day'));
  1170. $dateafter = date('Y-m-d 23:59:59', strtotime('-29 day'));
  1171. //当前
  1172. $now_datebefor = date('Y-m-d 00:00:00', strtotime('-29 day'));
  1173. $now_dateafter = date('Y-m-d 23:59:59');
  1174. for ($i = -29; $i <= 0; $i++) {
  1175. $datalist[date('Y-m-d', strtotime($i . ' day'))] = date('Y-m-d', strtotime($i . ' day'));
  1176. }
  1177. $order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'day');
  1178. if (empty($order_list)) return ['yAxis' => [], 'legend' => [], 'xAxis' => [], 'serise' => [], 'pre_cycle' => [], 'cycle' => []];
  1179. $order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1180. $cycle_list = [];
  1181. foreach ($datalist as $dk => $dd) {
  1182. if (isset($order_list[$dk]) && !empty($order_list[$dd])) {
  1183. $cycle_list[$dd] = $order_list[$dd];
  1184. } else {
  1185. $cycle_list[$dd] = ['count' => 0, 'day' => $dd, 'price' => ''];
  1186. }
  1187. }
  1188. foreach ($cycle_list as $k => $v) {
  1189. $data['day'][] = $v['day'];
  1190. $data['count'][] = $v['count'];
  1191. $data['price'][] = round($v['price'], 2);
  1192. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1193. $chartdata['yAxis']['maxnum'] = $v['count'];//日最大订单数
  1194. if ($chartdata['yAxis']['maxprice'] < $v['price'])
  1195. $chartdata['yAxis']['maxprice'] = $v['price'];//日最大金额
  1196. }
  1197. $chartdata['legend'] = ['订单金额', '订单数'];//分类
  1198. $chartdata['xAxis'] = $data['day'];//X轴值
  1199. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['price']];//分类1值
  1200. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['count'], 'yAxisIndex' => 1];//分类2值
  1201. break;
  1202. case 'week':
  1203. $weekarray = [['周日'], ['周一'], ['周二'], ['周三'], ['周四'], ['周五'], ['周六']];
  1204. $datebefor = date('Y-m-d 00:00:00', strtotime('-1 week Monday'));
  1205. $dateafter = date('Y-m-d 23:59:59', strtotime('-1 week Sunday'));
  1206. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'week');
  1207. //数据查询重新处理
  1208. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1209. $now_datebefor = date('Y-m-d 00:00:00', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
  1210. $now_dateafter = date('Y-m-d 23:59:59', strtotime("+1 day"));
  1211. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'week');
  1212. //数据查询重新处理 key 变为当前值
  1213. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1214. foreach ($weekarray as $dk => $dd) {
  1215. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1216. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1217. } else {
  1218. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1219. }
  1220. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1221. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1222. } else {
  1223. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1224. }
  1225. }
  1226. foreach ($weekarray as $k => $v) {
  1227. $data['day'][] = $v[0];
  1228. $data['pre']['count'][] = $v['pre']['count'];
  1229. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1230. $data['now']['count'][] = $v['now']['count'];
  1231. $data['now']['price'][] = round($v['now']['price'], 2);
  1232. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1233. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1234. }
  1235. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1236. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1237. }
  1238. }
  1239. $chartdata['legend'] = ['上周金额', '本周金额', '上周订单数', '本周订单数'];//分类
  1240. $chartdata['xAxis'] = $data['day'];//X轴值
  1241. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1242. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1243. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1244. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1245. break;
  1246. case 'month':
  1247. $weekarray = ['01' => ['1'], '02' => ['2'], '03' => ['3'], '04' => ['4'], '05' => ['5'], '06' => ['6'], '07' => ['7'], '08' => ['8'], '09' => ['9'], '10' => ['10'], '11' => ['11'], '12' => ['12'], '13' => ['13'], '14' => ['14'], '15' => ['15'], '16' => ['16'], '17' => ['17'], '18' => ['18'], '19' => ['19'], '20' => ['20'], '21' => ['21'], '22' => ['22'], '23' => ['23'], '24' => ['24'], '25' => ['25'], '26' => ['26'], '27' => ['27'], '28' => ['28'], '29' => ['29'], '30' => ['30'], '31' => ['31']];
  1248. $datebefor = date('Y-m-01 00:00:00', strtotime('-1 month'));
  1249. $dateafter = date('Y-m-d 23:59:59', strtotime(date('Y-m-01')));
  1250. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], "month");
  1251. //数据查询重新处理
  1252. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1253. $now_datebefor = date('Y-m-01 00:00:00');
  1254. $now_dateafter = date('Y-m-d', strtotime("+1 day"));
  1255. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], "month");
  1256. //数据查询重新处理 key 变为当前值
  1257. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1258. foreach ($weekarray as $dk => $dd) {
  1259. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1260. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1261. } else {
  1262. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1263. }
  1264. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1265. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1266. } else {
  1267. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1268. }
  1269. }
  1270. foreach ($weekarray as $k => $v) {
  1271. $data['day'][] = $v[0];
  1272. $data['pre']['count'][] = $v['pre']['count'];
  1273. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1274. $data['now']['count'][] = $v['now']['count'];
  1275. $data['now']['price'][] = round($v['now']['price'], 2);
  1276. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1277. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1278. }
  1279. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1280. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1281. }
  1282. }
  1283. $chartdata['legend'] = ['上月金额', '本月金额', '上月订单数', '本月订单数'];//分类
  1284. $chartdata['xAxis'] = $data['day'];//X轴值
  1285. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1286. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1287. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1288. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1289. break;
  1290. case 'year':
  1291. $weekarray = ['01' => ['一月'], '02' => ['二月'], '03' => ['三月'], '04' => ['四月'], '05' => ['五月'], '06' => ['六月'], '07' => ['七月'], '08' => ['八月'], '09' => ['九月'], '10' => ['十月'], '11' => ['十一月'], '12' => ['十二月']];
  1292. $datebefor = date('Y-01-01 00:00:00', strtotime('-1 year'));
  1293. $dateafter = date('Y-12-31 23:59:59', strtotime('-1 year'));
  1294. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'year');
  1295. //数据查询重新处理
  1296. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1297. $now_datebefor = date('Y-01-01 00:00:00');
  1298. $now_dateafter = date('Y-12-31 23:59:59');
  1299. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'year');
  1300. //数据查询重新处理 key 变为当前值
  1301. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1302. $y = date('Y');
  1303. foreach ($weekarray as $dk => $dd) {
  1304. $order_dk = $y . '-' . $dk;
  1305. if (isset($new_order_list[$order_dk]) && !empty($new_order_list[$order_dk])) {
  1306. $weekarray[$dk]['pre'] = $new_order_list[$order_dk];
  1307. } else {
  1308. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1309. }
  1310. if (isset($new_now_order_list[$order_dk]) && !empty($new_now_order_list[$order_dk])) {
  1311. $weekarray[$dk]['now'] = $new_now_order_list[$order_dk];
  1312. } else {
  1313. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1314. }
  1315. }
  1316. foreach ($weekarray as $k => $v) {
  1317. $data['day'][] = $v[0];
  1318. $data['pre']['count'][] = $v['pre']['count'];
  1319. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1320. $data['now']['count'][] = $v['now']['count'];
  1321. $data['now']['price'][] = round($v['now']['price'], 2);
  1322. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1323. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1324. }
  1325. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1326. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1327. }
  1328. }
  1329. $chartdata['legend'] = ['去年金额', '今年金额', '去年订单数', '今年订单数'];//分类
  1330. $chartdata['xAxis'] = $data['day'];//X轴值
  1331. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1332. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1333. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1334. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1335. break;
  1336. default:
  1337. break;
  1338. }
  1339. //统计总数上期
  1340. $pre_total = $this->dao->preTotalFind($where, [$datebefor, $dateafter]);
  1341. if ($pre_total) {
  1342. $chartdata['pre_cycle']['count'] = [
  1343. 'data' => $pre_total['count'] ?: 0
  1344. ];
  1345. $chartdata['pre_cycle']['price'] = [
  1346. 'data' => $pre_total['price'] ?: 0
  1347. ];
  1348. }
  1349. //统计总数
  1350. $total = $this->dao->preTotalFind($where, [$now_datebefor, $now_dateafter]);
  1351. if ($total) {
  1352. $cha_count = intval($pre_total['count']) - intval($total['count']);
  1353. $pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
  1354. $chartdata['cycle']['count'] = [
  1355. 'data' => $total['count'] ?: 0,
  1356. 'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
  1357. 'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
  1358. ];
  1359. $cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
  1360. $pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
  1361. $chartdata['cycle']['price'] = [
  1362. 'data' => $total['price'] ?: 0,
  1363. 'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
  1364. 'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
  1365. ];
  1366. }
  1367. return $chartdata;
  1368. }
  1369. /**
  1370. * 获取订单数量
  1371. * @param int $store_id
  1372. * @param int $type
  1373. * @param string $field
  1374. * @return int
  1375. */
  1376. public function storeOrderCount(int $store_id = 0, int $type = -1, string $field = 'store_id')
  1377. {
  1378. return $this->dao->storeOrderCount($store_id, $type, $field);
  1379. }
  1380. /**
  1381. * 首页头部统计
  1382. * @return array
  1383. */
  1384. public function homeStatics()
  1385. {
  1386. /** @var UserServices $uSercice */
  1387. $uSercice = app()->make(UserServices::class);
  1388. /** @var StoreProductLogServices $productLogServices */
  1389. $productLogServices = app()->make(StoreProductLogServices::class);
  1390. // 销售额
  1391. //今日销售额
  1392. $today_sales = $this->dao->totalSales('today');
  1393. //昨日销售额
  1394. $yesterday_sales = $this->dao->totalSales('yesterday');
  1395. //日同比
  1396. $sales_today_ratio = $this->countRate($today_sales, $yesterday_sales);
  1397. //周销售额
  1398. // //本周
  1399. // $this_week_sales = $this->dao->totalSales('week');
  1400. // //上周
  1401. // $last_week_sales = $this->dao->totalSales('last week');
  1402. // //周同比
  1403. // $sales_week_ratio = $this->countRate($this_week_sales, $last_week_sales);
  1404. //总销售额
  1405. $total_sales = $this->dao->totalSales('month');
  1406. $sales = [
  1407. 'today' => $today_sales,
  1408. 'yesterday' => $yesterday_sales,
  1409. 'today_ratio' => $sales_today_ratio,
  1410. // 'week' => $this_week_sales,
  1411. // 'last_week' => $last_week_sales,
  1412. // 'week_ratio' => $sales_week_ratio,
  1413. 'total' => $total_sales . '元',
  1414. 'date' => '今日'
  1415. ];
  1416. //用户访问量
  1417. //今日访问量
  1418. $today_visits = $productLogServices->count(['time' => 'today', 'type' => 'visit']);
  1419. //昨日访问量
  1420. $yesterday_visits = $productLogServices->count(['time' => 'yesterday', 'type' => 'visit']);
  1421. //日同比
  1422. $visits_today_ratio = $this->countRate($today_visits, $yesterday_visits);
  1423. // //本周访问量
  1424. // $this_week_visits = $productLogServices->count(['time' => 'week', 'type' => 'visit']);
  1425. // //上周访问量
  1426. // $last_week_visits = $productLogServices->count(['time' => 'last week', 'type' => 'visit']);
  1427. // //周同比
  1428. // $visits_week_ratio = $this->countRate($this_week_visits, $last_week_visits);
  1429. //总访问量
  1430. $total_visits = $productLogServices->count(['time' => 'month', 'type' => 'visit']);
  1431. $visits = [
  1432. 'today' => $today_visits,
  1433. 'yesterday' => $yesterday_visits,
  1434. 'today_ratio' => $visits_today_ratio,
  1435. // 'week' => $this_week_visits,
  1436. // 'last_week' => $last_week_visits,
  1437. // 'week_ratio' => $visits_week_ratio,
  1438. 'total' => $total_visits . 'Pv',
  1439. 'date' => '今日'
  1440. ];
  1441. // 订单量
  1442. //今日订单量
  1443. $today_order = $this->dao->totalOrderCount('today');
  1444. //昨日订单量
  1445. $yesterday_order = $this->dao->totalOrderCount('yesterday');
  1446. //订单日同比
  1447. $order_today_ratio = $this->countRate($today_order, $yesterday_order);
  1448. // //本周订单量
  1449. // $this_week_order = $this->dao->totalOrderCount('week');
  1450. // //上周订单量
  1451. // $last_week_order = $this->dao->totalOrderCount('last week');
  1452. // //订单周同比
  1453. // $order_week_ratio = $this->countRate($this_week_order, $last_week_order);
  1454. //总订单量
  1455. $total_order = $this->dao->totalOrderCount('month');
  1456. $order = [
  1457. 'today' => $today_order,
  1458. 'yesterday' => $yesterday_order,
  1459. 'today_ratio' => $order_today_ratio,
  1460. // 'week' => $this_week_order,
  1461. // 'last_week' => $last_week_order,
  1462. // 'week_ratio' => $order_week_ratio,
  1463. 'total' => $total_order . '单',
  1464. 'date' => '今日'
  1465. ];
  1466. // 用户
  1467. //今日新增用户
  1468. $today_user = $uSercice->totalUserCount('today');
  1469. //昨日新增用户
  1470. $yesterday_user = $uSercice->totalUserCount('yesterday');
  1471. //新增用户日同比
  1472. $user_today_ratio = $this->countRate($today_user, $yesterday_user);
  1473. // //本周新增用户
  1474. // $this_week_user = $uSercice->totalUserCount('week');
  1475. // //上周新增用户
  1476. // $last_week_user = $uSercice->totalUserCount('last week');
  1477. // //新增用户周同比
  1478. // $user_week_ratio = $this->countRate($this_week_user, $last_week_user);
  1479. //本月新增用户
  1480. $total_user = $uSercice->totalUserCount('month');
  1481. $user = [
  1482. 'today' => $today_user,
  1483. 'yesterday' => $yesterday_user,
  1484. 'today_ratio' => $user_today_ratio,
  1485. // 'week' => $this_week_user,
  1486. // 'last_week' => $last_week_user,
  1487. // 'week_ratio' => $user_week_ratio,
  1488. 'total' => $total_user . '人',
  1489. 'date' => '今日'
  1490. ];
  1491. $integralService = app()->make(AwardIntegralServices::class);
  1492. $today = $integralService->getIntegralSum(['add_time_date' => 'today']);
  1493. $yesterday = $integralService->getIntegralSum(['add_time_date' => 'yesterday']);
  1494. $today_ratio = $this->countRate($today, $yesterday);
  1495. $lack = [
  1496. 'today' => $today,
  1497. 'yesterday' => $yesterday,
  1498. 'today_ratio' => $today_ratio,
  1499. 'total' => $integralService->getIntegralSum(['add_time_date' => 'month']),
  1500. 'date' => '今日'
  1501. ];
  1502. $today = UserBrokerage::where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1503. $yesterday = UserBrokerage::where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1504. $today_ratio = $this->countRate($today, $yesterday);
  1505. $s_integral = [
  1506. 'today' => $today,
  1507. 'yesterday' => $yesterday,
  1508. 'today_ratio' => $today_ratio,
  1509. 'total' => User::sum('brokerage_price'),
  1510. 'date' => '今日'
  1511. ];
  1512. $today = UserBill::where('category', 'integral')->where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1513. $yesterday = UserBill::where('category', 'integral')->where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1514. $today_ratio = $this->countRate($today, $yesterday);
  1515. $a_integral = [
  1516. 'today' => $today,
  1517. 'yesterday' => $yesterday,
  1518. 'today_ratio' => $today_ratio,
  1519. 'total' => User::sum('integral'),
  1520. 'date' => '今日'
  1521. ];
  1522. $today = UserBill::where('category', 'energy')->where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1523. $yesterday = UserBill::where('category', 'energy')->where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1524. $today_ratio = $this->countRate($today, $yesterday);
  1525. $l_price = [
  1526. 'today' => $today,
  1527. 'yesterday' => $yesterday,
  1528. 'today_ratio' => $today_ratio,
  1529. 'total' => User::sum('energy'),
  1530. 'date' => '今日'
  1531. ];
  1532. $info = array_values(compact('sales', 'visits', 'order', 'user', 'lack', 'a_integral', 's_integral', 'l_price'));
  1533. $info[0]['title'] = '销售额';
  1534. $info[1]['title'] = '用户访问量';
  1535. $info[2]['title'] = '订单量';
  1536. $info[3]['title'] = '新增用户';
  1537. $info[4]['title'] = '参考分';
  1538. $info[5]['title'] = '消费分';
  1539. $info[6]['title'] = '佣金';
  1540. $info[7]['title'] = '能量';
  1541. $info[0]['total_name'] = '本月销售额';
  1542. $info[1]['total_name'] = '本月访问量';
  1543. $info[2]['total_name'] = '本月订单量';
  1544. $info[3]['total_name'] = '本月新增用户';
  1545. $info[4]['total_name'] = '本月参考分';
  1546. $info[5]['total_name'] = '剩余消费分';
  1547. $info[6]['total_name'] = '剩余佣金';
  1548. $info[7]['total_name'] = '剩余能量值';
  1549. return $info;
  1550. }
  1551. /**
  1552. * 打印订单
  1553. * @param int $id
  1554. * @param bool $isTable
  1555. * @return bool
  1556. */
  1557. public function orderPrint(int $id, int $type = -1, int $relation_id = -1, bool $isTable = false)
  1558. {
  1559. $order = $this->dao->get($id);
  1560. if (!$order) {
  1561. throw new ValidateException('订单信息不存在!');
  1562. }
  1563. $order = $order->toArray();
  1564. /** @var StoreOrderCartInfoServices $cartServices */
  1565. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  1566. $product = $cartServices->getCartInfoPrintProduct((int)$order['id']);
  1567. if (!$product) {
  1568. throw new ValidateException('订单商品获取失败,无法打印!');
  1569. }
  1570. if ($type == -1 && $relation_id == -1) {//取订单属于那一端
  1571. $type = $relation_id = 0;
  1572. if (isset($order['store_id']) && $order['store_id']) {
  1573. $store_id = (int)$order['store_id'];
  1574. if ($isTable) {
  1575. if (isset($order['type']) && $order['type'] == 10) {
  1576. $print = store_config($store_id, 'store_printing_timing');
  1577. if (!$print || !is_array($print) || !in_array(2, $print)) {
  1578. return true;
  1579. }
  1580. }
  1581. }
  1582. $type = 1;
  1583. $relation_id = $store_id;
  1584. } elseif (isset($order['supplier_id']) && $order['supplier_id']) {
  1585. $supplier_id = (int)$order['supplier_id'];
  1586. $type = 2;
  1587. $relation_id = $supplier_id;
  1588. }
  1589. }
  1590. /** @var ConfigServices $configServices */
  1591. $configServices = app()->make(ConfigServices::class);
  1592. [$switch, $name, $configData] = $configServices->getPrintingConfig($type, $relation_id);
  1593. if (!$switch) {
  1594. throw new ValidateException('请先开启小票打印');
  1595. }
  1596. foreach ($configData as $value) {
  1597. if (!$value) {
  1598. throw new ValidateException('请先配置小票打印开发者');
  1599. }
  1600. }
  1601. $printer = new Printer($name, $configData);
  1602. $printer->setPrinterContent([
  1603. 'name' => sys_config('site_name'),
  1604. 'orderInfo' => is_object($order) ? $order->toArray() : $order,
  1605. 'product' => $product
  1606. ])->startPrinter();
  1607. return true;
  1608. }
  1609. /**
  1610. * 获取订单确认数据
  1611. * @param array $user
  1612. * @param $cartId
  1613. * @param bool $new
  1614. * @param int $addressId
  1615. * @param int $shipping_type
  1616. * @param int $store_id
  1617. * @param int $coupon_id
  1618. * @return array
  1619. * @throws \Psr\SimpleCache\InvalidArgumentException
  1620. * @throws \think\db\exception\DataNotFoundException
  1621. * @throws \think\db\exception\DbException
  1622. * @throws \think\db\exception\ModelNotFoundException
  1623. */
  1624. public function getOrderConfirmData(array $user, $cartId, bool $new, int $addressId, int $shipping_type = 1, int $store_id = 0, int $coupon_id = 0)
  1625. {
  1626. $addr = $data = [];
  1627. $uid = (int)$user['uid'];
  1628. /** @var UserAddressServices $addressServices */
  1629. $addressServices = app()->make(UserAddressServices::class);
  1630. if ($addressId) {
  1631. $addr = $addressServices->getAdderssCache($addressId);
  1632. }
  1633. //没传地址id或地址已删除未找到 ||获取默认地址
  1634. if (!$addr) {
  1635. $addr = $addressServices->getUserDefaultAddressCache($uid);
  1636. }
  1637. $data['upgrade_addr'] = 0;
  1638. if ($addr) {
  1639. $addr = is_object($addr) ? $addr->toArray() : $addr;
  1640. if (isset($addr['upgrade']) && $addr['upgrade'] == 0) {
  1641. $data['upgrade_addr'] = 1;
  1642. }
  1643. } else {
  1644. $addr = [];
  1645. }
  1646. if ($store_id) {
  1647. /** @var SystemStoreServices $storeServices */
  1648. $storeServices = app()->make(SystemStoreServices::class);
  1649. $storeServices->getStoreInfo($store_id);
  1650. }
  1651. /** @var StoreCartServices $cartServices */
  1652. $cartServices = app()->make(StoreCartServices::class);
  1653. //获取购物车信息
  1654. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, $new, $addr, $shipping_type, $store_id, $coupon_id);
  1655. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  1656. $data['storeFreePostage'] = $storeFreePostage;
  1657. $validCartInfo = $cartGroup['valid'];
  1658. $giveCartList = $cartGroup['giveCartList'] ?? [];
  1659. /** @var StoreOrderComputedServices $computedServices */
  1660. $computedServices = app()->make(StoreOrderComputedServices::class);
  1661. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  1662. $priceGroup['couponPrice'] = $cartGroup['couponPrice'] ?? 0;
  1663. $priceGroup['firstOrderPrice'] = $cartGroup['firstOrderPrice'] ?? 0;
  1664. $validCartInfo = array_merge($priceGroup['cartInfo'] ?? $validCartInfo, $giveCartList);
  1665. $other = [
  1666. 'offlinePostage' => sys_config('offline_postage'),
  1667. 'integralRatio' => sys_config('integral_ratio'),
  1668. 'give_integral' => $cartGroup['giveIntegral'] ?? 0,
  1669. 'give_coupon' => $cartGroup['giveCoupon'] ?? [],
  1670. 'give_product' => $cartGroup['giveProduct'],
  1671. 'promotions' => $cartGroup['promotions']
  1672. ];
  1673. $deduction = $cartGroup['deduction'];
  1674. $data['product_type'] = $deduction['product_type'] ?? 0;
  1675. $data['valid_count'] = count($validCartInfo);
  1676. $data['addressInfo'] = $addr;
  1677. $data['type'] = $deduction['type'] ?? 0;
  1678. $data['activity_id'] = $deduction['activity_id'] ?? 0;
  1679. $data['seckill_id'] = $deduction['type'] == 1 ? $deduction['activity_id'] : 0;
  1680. $data['bargain_id'] = $deduction['type'] == 2 ? $deduction['activity_id'] : 0;
  1681. $data['combination_id'] = $deduction['type'] == 3 ? $deduction['activity_id'] : 0;
  1682. $data['luck_record_id'] = $deduction['type'] == 8 ? $deduction['activity_id'] : 0;
  1683. $data['collate_code_id'] = $deduction['type'] == 9 || $deduction['type'] == 10 ? $deduction['collate_code_id'] : 0;
  1684. $data['discount_id'] = $deduction['type'] == 5 ? $deduction['activity_id'] : 0;
  1685. $data['newcomer_id'] = $deduction['type'] == 7 ? $deduction['activity_id'] : 0;
  1686. $data['deduction'] = in_array($deduction['product_type'], [1, 2]) || $deduction['activity_id'] > 0;
  1687. $data['cartInfo'] = array_merge($cartGroup['cartInfo'], $giveCartList);
  1688. // $data['giveCartInfo'] = $giveCartList;
  1689. $data['custom_form'] = [];
  1690. if (isset($cartGroup['cartInfo'][0]['productInfo']['system_form_id']) && $cartGroup['cartInfo'][0]['productInfo']['system_form_id']) {
  1691. /** @var SystemFormServices $systemFormServices */
  1692. $systemFormServices = app()->make(SystemFormServices::class);
  1693. $formInfo = $systemFormServices->value(['id' => $cartGroup['cartInfo'][0]['productInfo']['system_form_id']], 'value');
  1694. if ($formInfo) {
  1695. $data['custom_form'] = is_string($formInfo) ? json_decode($formInfo, true) : $formInfo;
  1696. }
  1697. }
  1698. $data['give_integral'] = $other['give_integral'];
  1699. $data['give_coupon'] = [];
  1700. if ($other['give_coupon']) {
  1701. /** @var StoreCouponIssueServices $couponIssueService */
  1702. $couponIssueService = app()->make(StoreCouponIssueServices::class);
  1703. $data['give_coupon'] = $couponIssueService->getColumn([['id', 'IN', $other['give_coupon']]], 'id,coupon_title');
  1704. }
  1705. $data['priceGroup'] = $priceGroup;
  1706. $data['orderKey'] = $this->cacheOrderInfo($uid, $validCartInfo, $priceGroup, $other, $addr, $cartGroup['invalid'] ?? [], $deduction);
  1707. $data['offlinePostage'] = $other['offlinePostage'];
  1708. if (isset($user['pwd'])) unset($user['pwd']);
  1709. $user['vip'] = isset($priceGroup['vipPrice']) && $priceGroup['vipPrice'] > 0;
  1710. $user['vip_id'] = 0;
  1711. $user['discount'] = 0;
  1712. //用户等级是否开启
  1713. if (sys_config('member_func_status', 1)) {
  1714. /** @var UserLevelServices $levelServices */
  1715. $levelServices = app()->make(UserLevelServices::class);
  1716. $userLevel = $levelServices->getUerLevelInfoByUid($uid);
  1717. if ($user['vip'] || $userLevel) {
  1718. $user['vip'] = true;
  1719. $user['vip_id'] = $userLevel['id'] ?? 0;
  1720. $user['discount'] = $userLevel['discount'] ?? 0;
  1721. }
  1722. }
  1723. $user['record_pone'] = !isset($user['record_pone']) || !$user['record_pone'] ? '' : $user['record_pone'];
  1724. $data['userInfo'] = $user;
  1725. $data['integralRatio'] = $other['integralRatio'];
  1726. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1727. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1728. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1729. $data['store_func_status'] = (int)(sys_config('store_func_status', 1));//门店是否开启
  1730. $data['store_self_mention'] = false;//门店自提
  1731. $data['store_delivery_status'] = false;//门店配送
  1732. if ($data['store_func_status']) {
  1733. //门店自提是否开启
  1734. /** @var SystemStoreServices $systemStoreServices */
  1735. $systemStoreServices = app()->make(SystemStoreServices::class);
  1736. $data['store_self_mention'] = sys_config('store_self_mention') && $systemStoreServices->count(['type' => 0, 'is_store' => 1]);
  1737. $data['store_delivery_status'] = !!$systemStoreServices->count(['type' => 0]);
  1738. }
  1739. $data['store_func_status'] = $data['store_func_status'] && ($data['store_self_mention'] || $data['store_delivery_status']);
  1740. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  1741. $data['system_store'] = [];//门店信息
  1742. /** @var UserInvoiceServices $userInvoice */
  1743. $userInvoice = app()->make(UserInvoiceServices::class);
  1744. $invoice_func = $userInvoice->invoiceFuncStatus();
  1745. $data['invoice_func'] = $invoice_func['invoice_func'];
  1746. $data['special_invoice'] = $invoice_func['special_invoice'];
  1747. $data['integral_ratio_status'] = (int)sys_config('integral_ratio_status', 1);
  1748. return $data;
  1749. }
  1750. /**
  1751. * 缓存订单信息
  1752. * @param int $uid
  1753. * @param array $cartInfo
  1754. * @param array $priceGroup
  1755. * @param array $other
  1756. * @param array $addr
  1757. * @param array $invalidCartInfo
  1758. * @param array $deduction
  1759. * @param int $cacheTime
  1760. * @return string
  1761. * @throws \Psr\SimpleCache\InvalidArgumentException
  1762. */
  1763. public function cacheOrderInfo(int $uid, array $cartInfo, array $priceGroup, array $other = [], array $addr = [], array $invalidCartInfo = [], array $deduction = [], int $cacheTime = 600)
  1764. {
  1765. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1766. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1767. $key = md5($storeOrderCreateService->getNewOrderId((string)$uid) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8));
  1768. CacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
  1769. return $key;
  1770. }
  1771. /**
  1772. * 获取订单缓存信息
  1773. * @param int $uid
  1774. * @param string $key
  1775. * @return |null
  1776. */
  1777. public function getCacheOrderInfo(int $uid, string $key)
  1778. {
  1779. $cacheName = 'user_order_' . $uid . $key;
  1780. if (!CacheService::redisHandler()->has($cacheName)) return null;
  1781. return CacheService::redisHandler()->get($cacheName);
  1782. }
  1783. /**
  1784. * 获取用户购买活动产品的次数
  1785. * @param $uid
  1786. * @param $seckill_id
  1787. * @return int
  1788. */
  1789. public function activityProductCount(array $where)
  1790. {
  1791. return $this->dao->count($where);
  1792. }
  1793. /**
  1794. * 获取拼团的订单id
  1795. * @param int $pid
  1796. * @param int $uid
  1797. * @return mixed
  1798. */
  1799. public function getStoreIdPink(int $pid, int $uid)
  1800. {
  1801. return $this->dao->value(['uid' => $uid, 'pink_id' => $pid, 'is_del' => 0], 'order_id');
  1802. }
  1803. /**
  1804. * 判断当前订单中是否有拼团
  1805. * @param int $pid
  1806. * @param int $uid
  1807. * @return int
  1808. */
  1809. public function getIsOrderPink($pid = 0, $uid = 0)
  1810. {
  1811. return $this->dao->count(['uid' => $uid, 'pink_id' => $pid, 'refund_status' => 0, 'is_del' => 0]);
  1812. }
  1813. /**
  1814. * 判断支付方式是否开启
  1815. * @param $payType
  1816. * @return bool
  1817. */
  1818. public function checkPaytype(string $payType)
  1819. {
  1820. $res = false;
  1821. switch ($payType) {
  1822. case PayServices::WEIXIN_PAY:
  1823. $res = (bool)sys_config('pay_weixin_open');
  1824. break;
  1825. case PayServices::YUE_PAY:
  1826. $res = sys_config('balance_func_status') && sys_config('yue_pay_status') == 1;
  1827. break;
  1828. case 'offline':
  1829. $res = sys_config('offline_pay_status') == 1;
  1830. break;
  1831. case PayServices::ALIAPY_PAY:
  1832. $res = sys_config('ali_pay_status') == 1;
  1833. break;
  1834. }
  1835. return $res;
  1836. }
  1837. /**
  1838. * 修改支付方式为线下支付
  1839. * @param string $orderId
  1840. * @return bool
  1841. */
  1842. public function setOrderTypePayOffline(string $orderId)
  1843. {
  1844. return $this->dao->update($orderId, ['pay_type' => 'offline'], 'order_id');
  1845. }
  1846. /**
  1847. * 删除订单
  1848. * @param $uni
  1849. * @param $uid
  1850. * @return bool
  1851. */
  1852. public function removeOrder(string $uni, int $uid)
  1853. {
  1854. $order = $this->getUserOrderDetail($uni, $uid);
  1855. if (!$order) {
  1856. throw new ValidateException('订单不存在!');
  1857. }
  1858. $order = $this->tidyOrder($order);
  1859. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  1860. throw new ValidateException('该订单无法删除!');
  1861. $order->is_del = 1;
  1862. /** @var StoreOrderStatusServices $statusService */
  1863. $statusService = app()->make(StoreOrderStatusServices::class);
  1864. $res = $statusService->save([
  1865. 'oid' => $order['id'],
  1866. 'change_type' => 'remove_order',
  1867. 'change_message' => '删除订单',
  1868. 'change_time' => time()
  1869. ]);
  1870. if ($order->save() && $res) {
  1871. //未支付和已退款的状态下才可以退积分退库存退优惠券
  1872. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  1873. /** @var StoreOrderRefundServices $refundServices */
  1874. $refundServices = app()->make(StoreOrderRefundServices::class);
  1875. $this->transaction(function () use ($order, $refundServices) {
  1876. //回退积分和优惠卷
  1877. $res = $refundServices->integralAndCouponBack($order);
  1878. //回退库存
  1879. $res = $res && $refundServices->regressionStock($order);
  1880. if (!$res) {
  1881. throw new ValidateException('取消订单失败!');
  1882. }
  1883. });
  1884. }
  1885. return true;
  1886. } else
  1887. throw new ValidateException('订单删除失败!');
  1888. }
  1889. /**
  1890. * 取消订单
  1891. * @param $order_id
  1892. * @param int $uid
  1893. * @return bool
  1894. * @throws \think\db\exception\DataNotFoundException
  1895. * @throws \think\db\exception\DbException
  1896. * @throws \think\db\exception\ModelNotFoundException
  1897. */
  1898. public function cancelOrder($order_id, int $uid)
  1899. {
  1900. $order = $this->dao->getOne(['order_id' => $order_id, 'uid' => $uid, 'is_del' => 0]);
  1901. if (!$order) {
  1902. throw new ValidateException('没有查到此订单');
  1903. }
  1904. if ($order->paid) {
  1905. throw new ValidateException('订单已经支付无法取消');
  1906. }
  1907. /** @var StoreOrderRefundServices $refundServices */
  1908. $refundServices = app()->make(StoreOrderRefundServices::class);
  1909. $this->transaction(function () use ($refundServices, $order) {
  1910. //回退积分和优惠卷
  1911. $res = $refundServices->integralAndCouponBack($order);
  1912. //回退库存和销量
  1913. $res = $res && $refundServices->regressionStock($order);
  1914. $order->is_del = 1;
  1915. if (!($res && $order->save())) {
  1916. throw new ValidateException('取消订单失败');
  1917. }
  1918. });
  1919. //订单取消事件
  1920. event('order.cancel', [$order]);
  1921. return true;
  1922. }
  1923. /**
  1924. * 判断订单完成
  1925. * @param StoreProductReplyServices $replyServices
  1926. * @param array $uniqueList
  1927. * @param $oid
  1928. * @return mixed
  1929. */
  1930. public function checkOrderOver($replyServices, array $uniqueList, $oid)
  1931. {
  1932. //订单商品全部评价完成
  1933. $replyServices->count(['unique' => $uniqueList, 'oid' => $oid]);
  1934. if ($replyServices->count(['unique' => $uniqueList, 'oid' => $oid]) == count($uniqueList)) {
  1935. $res = $this->dao->update($oid, ['status' => '3']);
  1936. if (!$res) throw new ValidateException('评价后置操作失败!');
  1937. /** @var StoreOrderStatusServices $statusService */
  1938. $statusService = app()->make(StoreOrderStatusServices::class);
  1939. $statusService->save([
  1940. 'oid' => $oid,
  1941. 'change_type' => 'check_order_over',
  1942. 'change_message' => '用户评价',
  1943. 'change_time' => time()
  1944. ]);
  1945. }
  1946. }
  1947. /**
  1948. * 某个用户订单
  1949. * @param int $uid
  1950. * @param UserServices $userServices
  1951. * @return array
  1952. * @throws \think\db\exception\DataNotFoundException
  1953. * @throws \think\db\exception\DbException
  1954. * @throws \think\db\exception\ModelNotFoundException
  1955. */
  1956. public function getUserOrderList(int $uid)
  1957. {
  1958. /** @var UserServices $userServices */
  1959. $userServices = app()->make(UserServices::class);
  1960. $user = $userServices->getUserWithTrashedInfo($uid);
  1961. if (!$user) {
  1962. throw new ValidateException('数据不存在');
  1963. }
  1964. [$page, $limit] = $this->getPageValue();
  1965. $where = ['uid' => $uid, 'pid' => [0, -1], 'paid' => 1, 'is_del' => 0, 'is_system_del' => 0];
  1966. $list = $this->dao->getStairOrderList($where, 'order_id,real_name,total_num,total_price,pay_price,FROM_UNIXTIME(pay_time,"%Y-%m-%d") as pay_time,paid,pay_type,type,activity_id,activity_append', $page, $limit);
  1967. $count = $this->dao->count($where);
  1968. return compact('list', 'count');
  1969. }
  1970. /**
  1971. * 获取推广订单列表
  1972. * @param int $uid
  1973. * @param $where
  1974. * @return array
  1975. * @throws \think\db\exception\DataNotFoundException
  1976. * @throws \think\db\exception\DbException
  1977. * @throws \think\db\exception\ModelNotFoundException
  1978. */
  1979. public function getUserStairOrderList(int $uid, $where)
  1980. {
  1981. $where_data = [];
  1982. if (isset($where['type'])) {
  1983. switch ((int)$where['type']) {
  1984. case 1:
  1985. $where_data['spread_uid'] = $uid;
  1986. break;
  1987. case 2:
  1988. $where_data['spread_two_uid'] = $uid;
  1989. break;
  1990. default:
  1991. $where_data['spread_or_uid'] = $uid;
  1992. break;
  1993. }
  1994. }
  1995. if (isset($where['data']) && $where['data']) {
  1996. $where_data['time'] = $where['data'];
  1997. }
  1998. if (isset($where['order_id']) && $where['order_id']) {
  1999. $where_data['order_id'] = $where['order_id'];
  2000. }
  2001. if (isset($where['nickname']) && $where['nickname']) {
  2002. $where_data['real_name'] = $where['nickname'];
  2003. }
  2004. //推广订单只显示支付过并且未退款的订单
  2005. $where_data['pid'] = 0;
  2006. $where_data['paid'] = 1;
  2007. $where_data['refund_status'] = 0;
  2008. [$page, $limit] = $this->getPageValue();
  2009. $list = $this->dao->getStairOrderList($where_data, '*', $page, $limit);
  2010. $count = $this->dao->count($where_data);
  2011. return compact('list', 'count');
  2012. }
  2013. /**
  2014. * 订单导出
  2015. * @param array $where
  2016. * @return array
  2017. * @throws \think\db\exception\DataNotFoundException
  2018. * @throws \think\db\exception\DbException
  2019. * @throws \think\db\exception\ModelNotFoundException
  2020. */
  2021. public function getExportList(array $where, array $with = [], int $limit = 0)
  2022. {
  2023. if ($limit) {
  2024. [$page] = $this->getPageValue();
  2025. } else {
  2026. [$page, $limit] = $this->getPageValue();
  2027. }
  2028. $list = $this->dao->search($where)->with($with)->page($page, $limit)->order('id asc')->select()->toArray();
  2029. if ($list) {
  2030. /** @var $userServices */
  2031. $userServices = app()->make(UserServices::class);
  2032. $userSex = $userServices->getColumn([['uid', 'IN', array_unique(array_column($list, 'uid'))]], 'uid,sex', 'uid');
  2033. foreach ($list as &$item) {
  2034. /** @var StoreOrderCartInfoServices $orderCart */
  2035. $orderCart = app()->make(StoreOrderCartInfoServices::class);
  2036. $_info = $orderCart->getCartColunm(['oid' => $item['id']], 'cart_info', 'unique');
  2037. foreach ($_info as $k => $v) {
  2038. $cart_info = is_string($v) ? json_decode($v, true) : $v;
  2039. if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
  2040. $_info[$k] = $cart_info;
  2041. unset($cart_info);
  2042. }
  2043. $item['_info'] = $_info;
  2044. $item['sex'] = $userSex[$item['uid']]['sex'] ?? '';
  2045. [$pink_name, $color] = $this->tidyOrderType($item);
  2046. $item['pink_name'] = $pink_name;
  2047. $item['color'] = $color;
  2048. }
  2049. }
  2050. return $list;
  2051. }
  2052. /**
  2053. * 自动取消订单
  2054. * @return bool
  2055. * @throws \think\db\exception\DataNotFoundException
  2056. * @throws \think\db\exception\DbException
  2057. * @throws \think\db\exception\ModelNotFoundException
  2058. */
  2059. public function runOrderUnpaidCancel(int $page = 0, int $limit = 0)
  2060. {
  2061. $list = $this->dao->getOrderUnPaid(0, $page, $limit)->field(['*'])->select();
  2062. if (!$list) {
  2063. return true;
  2064. }
  2065. //系统预设取消订单时间段
  2066. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  2067. //获取配置
  2068. $systemValue = SystemConfigService::more($keyValue);
  2069. //格式化数据
  2070. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  2071. $secsArr = [];
  2072. //秒杀
  2073. $secsArr[1] = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  2074. //砍价
  2075. $secsArr[2] = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  2076. //拼团
  2077. $secsArr[3] = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  2078. //默认
  2079. $secsArr[0] = $systemValue['order_cancel_time'];
  2080. /** @var StoreOrderRefundServices $refundServices */
  2081. $refundServices = app()->make(StoreOrderRefundServices::class);
  2082. foreach ($list as $order) {
  2083. $type = $order['type'];
  2084. $secs = $secsArr[$type] ?? $secsArr[0];
  2085. if ($secs == 0) continue;
  2086. if (($order['add_time'] + bcmul($secs, '3600', 0)) < time()) {
  2087. try {
  2088. $this->transaction(function () use ($order, $refundServices) {
  2089. //回退积分和优惠卷
  2090. $res = $refundServices->integralAndCouponBack($order);
  2091. //回退库存和销量
  2092. $res = $res && $refundServices->regressionStock($order);
  2093. //修改订单状态
  2094. $res = $res && $this->dao->update($order['id'], ['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  2095. if (!$res) {
  2096. throw new ValidateException('订单号' . $order['order_id'] . '自动取消订单失败');
  2097. }
  2098. return true;
  2099. });
  2100. //订单取消事件
  2101. event('order.cancel', [$order]);
  2102. } catch (\Throwable $e) {
  2103. Log::error('自动取消订单失败,失败原因:' . $e->getMessage(), $e->getTrace());
  2104. }
  2105. }
  2106. }
  2107. return true;
  2108. }
  2109. /**
  2110. * 批量加入对接
  2111. * @param int $count
  2112. * @param int $limit
  2113. */
  2114. public function batchJoinJob(int $count, int $limit)
  2115. {
  2116. $pages = ceil($limit / $count);
  2117. for ($i = 1; $i <= $pages; $i++) {
  2118. AutoOrderUnpaidCancelJob::dispatch([$i, $limit]);
  2119. }
  2120. return true;
  2121. }
  2122. /**
  2123. * 自动取消订单
  2124. * @return bool
  2125. * @throws \think\db\exception\DataNotFoundException
  2126. * @throws \think\db\exception\DbException
  2127. * @throws \think\db\exception\ModelNotFoundException
  2128. */
  2129. public function orderUnpaidCancel()
  2130. {
  2131. $count = $this->dao->getOrderUnPaid()->count();
  2132. $maxLimit = 100;
  2133. if ($count > $maxLimit) {
  2134. return $this->batchJoinJob($count, $maxLimit);
  2135. }
  2136. return $this->runOrderUnpaidCancel();
  2137. }
  2138. /**
  2139. * 根据时间获取当天或昨天订单营业额
  2140. * @param array $where
  2141. * @return float|int
  2142. */
  2143. public function getOrderMoneyByWhere(array $where, string $sum_field, string $selectType, string $group = "")
  2144. {
  2145. switch ($selectType) {
  2146. case "sum" :
  2147. return $this->dao->getDayTotalMoney($where, $sum_field);
  2148. case "group" :
  2149. return $this->dao->getDayGroupMoney($where, $sum_field, $group);
  2150. }
  2151. }
  2152. /**
  2153. * 统计时间段订单数
  2154. * @param array $where
  2155. * @param string $sum_field
  2156. */
  2157. public function getOrderCountByWhere(array $where)
  2158. {
  2159. return $this->dao->getDayOrderCount($where);
  2160. }
  2161. /**
  2162. * 分组统计时间段订单数
  2163. * @param $where
  2164. * @return mixed
  2165. */
  2166. public function getOrderGroupCountByWhere($where)
  2167. {
  2168. return $this->dao->getOrderGroupCount($where);
  2169. }
  2170. /**
  2171. * 时间段支付订单人数
  2172. * @param $where
  2173. * @return mixed
  2174. */
  2175. public function getPayOrderPeopleByWhere($where)
  2176. {
  2177. return $this->dao->getPayOrderPeople($where);
  2178. }
  2179. /**
  2180. * 时间段分组统计支付订单人数
  2181. * @param $where
  2182. * @return mixed
  2183. */
  2184. public function getPayOrderGroupPeopleByWhere($where)
  2185. {
  2186. return $this->dao->getPayOrderGroupPeople($where);
  2187. }
  2188. /**
  2189. * 批量更新数据
  2190. * @param array $ids
  2191. * @param array $data
  2192. * @param string|null $key
  2193. * @return BaseModel
  2194. */
  2195. public function orderDel(array $ids, $redisKey, $queueId)
  2196. {
  2197. /** @var QueueServices $queueService */
  2198. $queueService = app()->make(QueueServices::class);
  2199. $res = $this->dao->batchUpdateOrder($ids, ['is_system_del' => 1]);
  2200. if ($res) {
  2201. $queueService->doSuccessSremRedis($ids, $redisKey, $queueId['type']);
  2202. } else {
  2203. $queueService->addQueueFail($queueId['id'], $redisKey);
  2204. throw new AdminException('删除失败');
  2205. }
  2206. }
  2207. /**获取发货excel文件数据
  2208. * @param string $file
  2209. * @param $row
  2210. * @return array
  2211. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  2212. */
  2213. public function readExpreExcel(string $file, $row = 2)
  2214. {
  2215. if (!$file) throw new AdminException('请上传发货数据表');
  2216. /** @var FileService $readExcelService */
  2217. $readExcelService = app()->make(FileService::class);
  2218. $exprData = $readExcelService->readExcel($file, $row);
  2219. if (!$exprData) throw new AdminException('发货数据为空');
  2220. return $exprData;
  2221. }
  2222. /**
  2223. * 队列发货
  2224. * @return bool
  2225. * @throws \think\db\exception\DataNotFoundException
  2226. * @throws \think\db\exception\DbException
  2227. * @throws \think\db\exception\ModelNotFoundException
  2228. */
  2229. public function adminQueueOrderDo(array $data, bool $is_again = false)
  2230. {
  2231. if (!$data) return false;
  2232. /** @var QueueServices $queueService */
  2233. $queueService = app()->make(QueueServices::class);
  2234. /** @var QueueAuxiliaryServices $auxiliaryService */
  2235. $auxiliaryService = app()->make(QueueAuxiliaryServices::class);
  2236. $queueWhere['type'] = $data['queueType'];
  2237. $queueWhere['status'] = 0;
  2238. if (isset($data['queueId']) && $data['queueId']) $queueWhere['id'] = $data['queueId'];
  2239. $queueInfo = $queueService->getQueueOne($queueWhere);
  2240. $ids = $auxiliaryService->getCacheOidList($queueInfo['id'], $data['cacheType']);
  2241. $data['ids'] = array_column($ids, 'relation_id');
  2242. $data['queueId'] = $queueInfo['id'];
  2243. //if ($queueInfo['status'] == 2) throw new ValidateException('任务已完成');
  2244. //把队列需要执行的入参数据存起来,以便队列执行失败后接着执行,同时队列状态改为正在执行状态。
  2245. $queueService->setQueueDoing($data, $queueInfo['id'], $is_again);
  2246. $oids = $auxiliaryService->getOrderExpreList(['binding_id' => $queueInfo['id'], 'type' => $data['cacheType'], 'status' => [0, 2]]);
  2247. $oids = $oids ? array_column($oids, 'relation_id') : [];
  2248. // $chunkPids = array_chunk($oids, 1000, true);
  2249. $data['queueId'] = $queueInfo['id'];
  2250. foreach ($oids as $v) {
  2251. //加入队列
  2252. BatchHandleJob::dispatch([$v, $data['queueType'], $data]);
  2253. }
  2254. return true;
  2255. }
  2256. /**
  2257. * 对外接口获取订单状态
  2258. * @param int $oid
  2259. */
  2260. public function outGetStatus(string $oid)
  2261. {
  2262. $order = $this->dao->getOne(['order_id' => $oid]);
  2263. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  2264. $status_name = '线下支付';
  2265. } else if (!$order['paid']) {
  2266. $status_name = '未支付';
  2267. } else if ($order['status'] == 0 && $order['refund_status'] == 0) {
  2268. $status_name = '待发货';
  2269. } else if ($order['refund_status'] == 1) {
  2270. $status_name = '申请退款中';
  2271. } else if ($order['refund_status'] == 2) {
  2272. $status_name = '已退款';
  2273. } else if ($order['refund_status'] == 3) {
  2274. $status_name = '部分退款(子订单)';
  2275. } else if ($order['refund_status'] == 4) {
  2276. $status_name = '子订单已全部申请退款中';
  2277. } else if (!$order['status']) {
  2278. $status_name = '未发货';
  2279. } else if ($order['status'] == 1) {
  2280. $status_name = '待收货';
  2281. } else if ($order['status'] == 2) {
  2282. $status_name = '待评价';
  2283. } else if ($order['status'] == 3) {
  2284. $status_name = '交易完成';
  2285. }
  2286. $data = [];
  2287. $data['status_name'] = $status_name;
  2288. $data['status'] = $order['status'];
  2289. $data['paid'] = $order['paid'];
  2290. $data['pay_type'] = $order['pay_type'];
  2291. $data['refund_status'] = $order['refund_status'];
  2292. return $data;
  2293. }
  2294. /**
  2295. * 对外接口根据订单id查询收货方式
  2296. * @param string $oid
  2297. * @return array
  2298. */
  2299. public function outGetShippingType(string $oid)
  2300. {
  2301. $shipping_type = $this->dao->value(['order_id' => $oid], 'shipping_type');
  2302. $shipping_type = $shipping_type == 1 ? '商家配送' : '到店自提';
  2303. return compact('shipping_type');
  2304. }
  2305. /**
  2306. * 对外接口根据订单id查询配送信息
  2307. * @param string $oid
  2308. * @return array|\think\Model|null
  2309. * @throws \think\db\exception\DataNotFoundException
  2310. * @throws \think\db\exception\DbException
  2311. * @throws \think\db\exception\ModelNotFoundException
  2312. */
  2313. public function OutDeliveryType(string $oid)
  2314. {
  2315. $info = $this->dao->getOne(['order_id' => $oid], 'order_id,delivery_type,delivery_name,delivery_id');
  2316. return $info ? $info->toArray() : [];
  2317. }
  2318. /**
  2319. * 对外接口获取运费
  2320. * @param int $cartId
  2321. * @param int $uid
  2322. * @param int $addressId
  2323. * @return array
  2324. * @throws \Psr\SimpleCache\InvalidArgumentException
  2325. */
  2326. public function outGetPostage($cartId, int $uid, int $addressId, int $couponId = 0)
  2327. {
  2328. $addr = [];
  2329. /** @var UserAddressServices $addressServices */
  2330. $addressServices = app()->make(UserAddressServices::class);
  2331. /** @var UserServices $userServices */
  2332. $userServices = app()->make(UserServices::class);
  2333. $user = $userServices->get($uid);
  2334. if ($addressId) {
  2335. $addr = $addressServices->getAdderssCache($addressId);
  2336. }
  2337. //没传地址id或地址已删除未找到 ||获取默认地址
  2338. if (!$addr) {
  2339. $addr = $addressServices->getUserDefaultAddressCache($uid);
  2340. }
  2341. /** @var StoreCartServices $cartServices */
  2342. $cartServices = app()->make(StoreCartServices::class);
  2343. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, true, $addr);
  2344. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  2345. $validCartInfo = $cartGroup['valid'];
  2346. /** @var StoreOrderComputedServices $computedServices */
  2347. $computedServices = app()->make(StoreOrderComputedServices::class);
  2348. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  2349. $postage = $priceGroup['storePostage'] ?? 0;
  2350. return compact('postage');
  2351. }
  2352. /**
  2353. * 获取配送员订单统计列表
  2354. * @param array $where
  2355. * @return array
  2356. * @throws \think\db\exception\DataNotFoundException
  2357. * @throws \think\db\exception\DbException
  2358. * @throws \think\db\exception\ModelNotFoundException
  2359. */
  2360. public function getDeliveryStatistics(array $where)
  2361. {
  2362. [$page, $limit] = $this->getPageValue();
  2363. $where['is_del'] = 0;
  2364. $where['paid'] = 1;
  2365. $where['is_system_del'] = 0;
  2366. $where['delivery_type'] = 'send';
  2367. $where['refund_status'] = [0, 3];
  2368. $list = $this->dao->getList((array)$where, ['*'], (int)$page, (int)$limit, ['user']);
  2369. if ($list) {
  2370. $list = $this->tidyOrderList($list, false);
  2371. }
  2372. $count = $this->dao->count($where);
  2373. return compact('list', 'count');
  2374. }
  2375. /**
  2376. * 配送员订单统计
  2377. * @param $store_id
  2378. * @param $delivery_uid
  2379. * @param $time
  2380. * @return array
  2381. * @throws \think\db\exception\DataNotFoundException
  2382. * @throws \think\db\exception\DbException
  2383. * @throws \think\db\exception\ModelNotFoundException
  2384. */
  2385. public function getStatisticsHeader($store_id, $delivery_uid, $time)
  2386. {
  2387. $where['is_del'] = 0;
  2388. $where['paid'] = 1;
  2389. $where['is_system_del'] = 0;
  2390. $where['delivery_type'] = 'send';
  2391. $where['store_id'] = $store_id;
  2392. $where['refund_status'] = [0, 3];
  2393. if ($delivery_uid) {
  2394. $where['delivery_uid'] = $delivery_uid;
  2395. }
  2396. [$start, $end, $timeType, $xAxis] = $time;
  2397. $order = $this->dao->orderAddTimeList($where, [$start, $end], $timeType, false);
  2398. $price = array_column($order, 'price', 'day');
  2399. $count = array_column($order, 'count', 'day');
  2400. $data = $series = [];
  2401. foreach ($xAxis as $key) {
  2402. $data['配送订单金额'][] = isset($price[$key]) ? floatval($price[$key]) : 0;
  2403. $data['配送单数'][] = isset($count[$key]) ? floatval($count[$key]) : 0;
  2404. }
  2405. foreach ($data as $key => $item) {
  2406. $series[] = [
  2407. 'name' => $key,
  2408. 'data' => $item,
  2409. 'type' => 'line',
  2410. 'smooth' => 'true',
  2411. 'yAxisIndex' => 1,
  2412. ];
  2413. }
  2414. return compact('xAxis', 'series');
  2415. }
  2416. /**
  2417. * 门店线上支付订单详情
  2418. * @param int $store
  2419. * @param int $uid
  2420. * @return mixed
  2421. * @throws \think\db\exception\DataNotFoundException
  2422. * @throws \think\db\exception\DbException
  2423. * @throws \think\db\exception\ModelNotFoundException
  2424. */
  2425. public function payCashierOrder(int $store, int $uid)
  2426. {
  2427. $order = $this->dao->payCashierOrder($store, $uid);
  2428. if (!$order) throw new ValidateException('订单不存在');
  2429. $order = $order->toArray();
  2430. $order = $this->tidyOrder($order, true);
  2431. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  2432. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  2433. $order['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  2434. return $order;
  2435. }
  2436. /**
  2437. * 订单分配|重新分配给你门店
  2438. * @param int $id
  2439. * @param int $store_id
  2440. * @return mixed
  2441. * @throws \think\db\exception\DataNotFoundException
  2442. * @throws \think\db\exception\DbException
  2443. * @throws \think\db\exception\ModelNotFoundException
  2444. */
  2445. public function shareOrder(int $id, int $store_id)
  2446. {
  2447. $orderInfo = $this->dao->get((int)$id);
  2448. if (!$orderInfo) {
  2449. throw new ValidateException('订单不存在');
  2450. }
  2451. //卡密商品
  2452. if ($orderInfo['product_type'] == 1) {
  2453. throw new ValidateException('订单中卡密商品门店暂不支持');
  2454. }
  2455. /** @var SystemStoreServices $storeServices */
  2456. $storeServices = app()->make(SystemStoreServices::class);
  2457. $storeInfo = $storeServices->getStoreInfo($store_id);
  2458. if ($orderInfo['status'] != 0) {
  2459. throw new ValidateException('订单已发货');
  2460. }
  2461. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  2462. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  2463. $cart_info = $storeOrderCartInfoServices->getSplitCartList($id, 'cart_info');
  2464. if (!$cart_info) {
  2465. throw new ValidateException('订单已发货');
  2466. }
  2467. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  2468. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  2469. if ($storeOrderRefundServices->count(['store_order_id' => $id, 'refund_type' => [1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
  2470. throw new ValidateException('订单有售后申请请先处理');
  2471. }
  2472. $platProductIds = [];
  2473. $platStoreProductIds = [];
  2474. $storeProductIds = [];
  2475. foreach ($cart_info as $cart) {
  2476. $productInfo = $cart['productInfo'] ?? [];
  2477. if (isset($productInfo['store_delivery']) && !$productInfo['store_delivery']) {//有商品不支持门店配送
  2478. return [[], $cart_info];
  2479. }
  2480. switch ($productInfo['type'] ?? 0) {
  2481. case 0://平台
  2482. case 2://供应商
  2483. $platProductIds[] = $cart['product_id'];
  2484. break;
  2485. case 1://门店
  2486. if ($productInfo['pid']) {//门店自有商品
  2487. $storeProductIds[] = $cart['product_id'];
  2488. } else {
  2489. $platStoreProductIds[] = $cart['product_id'];
  2490. }
  2491. break;
  2492. }
  2493. }
  2494. if ($storeProductIds && $store_id != $orderInfo['store_id']) {
  2495. throw new ValidateException('该门店商品未上架或未设置库存');
  2496. }
  2497. /** @var StoreBranchProductServices $branchProductServics */
  2498. $branchProductServics = app()->make(StoreBranchProductServices::class);
  2499. //转换成平台商品
  2500. if ($platStoreProductIds) {
  2501. $ids = $branchProductServics->getStoreProductIds($platStoreProductIds);
  2502. $platProductIds = array_merge($platProductIds, $ids);
  2503. }
  2504. $productCount = count($platProductIds);
  2505. //商品没下架 && 库存足够
  2506. if ($productCount != $branchProductServics->count(['pid' => $platProductIds, 'is_show' => 1, 'is_del' => 0, 'type' => 1, 'relation_id' => $store_id])) {
  2507. throw new ValidateException('该门店商品未上架或未设置库存');
  2508. }
  2509. /** @var StoreProductAttrValueServices $skuValueServices */
  2510. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  2511. foreach ($cart_info as $cart) {
  2512. if (isset($cart['productInfo']['store_delivery']) && !$cart['productInfo']['store_delivery']) {//有商品不支持门店配送
  2513. throw new ValidateException('有商品不支持门店配送');
  2514. }
  2515. switch ($cart['type']) {
  2516. case 0:
  2517. case 6:
  2518. case 8:
  2519. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['product_id'], 'type' => 0], 'suk');
  2520. break;
  2521. case 1:
  2522. case 2:
  2523. case 3:
  2524. case 5:
  2525. case 7:
  2526. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['activity_id'], 'type' => $cart['type']], 'suk');
  2527. break;
  2528. }
  2529. $branchProductInfo = $branchProductServics->isValidStoreProduct((int)$cart['product_id'], $store_id);
  2530. if (!$branchProductInfo) {
  2531. throw new ValidateException('该门店商品库存不足');
  2532. }
  2533. $attrValue = $skuValueServices->get(['suk' => $suk, 'product_id' => $branchProductInfo['id'], 'type' => 0]);
  2534. if (!$attrValue) {
  2535. throw new ValidateException('该门店商品库存不足');
  2536. }
  2537. }
  2538. $res = $this->transaction(function () use ($id, $store_id, $orderInfo, $storeInfo, $cart_info, $branchProductServics) {
  2539. if ($orderInfo['store_id'] > 0) {//重新分配门店
  2540. //返还原来门店库存
  2541. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 0);
  2542. } else {
  2543. //返还平台库存
  2544. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, 0, -1);
  2545. }
  2546. //扣门店库存
  2547. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 1, $store_id);
  2548. $res = $res && $this->dao->update($id, ['store_id' => $storeInfo['id'], 'shipping_type' => $orderInfo['shipping_type'] == 1 ? 3 : $orderInfo['shipping_type']]);
  2549. return $res;
  2550. });
  2551. $orderInfo['store_id'] = $storeInfo['id'];
  2552. //删除之前的账单记录
  2553. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  2554. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  2555. $storeFinanceFlowServices->update(['link_id' => $orderInfo['order_id']], ['is_del' => 1]);
  2556. //分配后置方法
  2557. SpliteStoreOrderJob::dispatchDo('splitAfter', [$orderInfo, true]);
  2558. return $res;
  2559. }
  2560. /**
  2561. * 获取退货商品列表
  2562. * @param array $cart_ids
  2563. * @param int $id
  2564. * @return array
  2565. * @throws \think\db\exception\DataNotFoundException
  2566. * @throws \think\db\exception\DbException
  2567. * @throws \think\db\exception\ModelNotFoundException
  2568. */
  2569. public function refundCartInfoList(array $cart_ids = [], int $id = 0)
  2570. {
  2571. $orderInfo = $this->dao->get($id);
  2572. if (!$orderInfo) {
  2573. throw new ValidateException('订单不存在');
  2574. }
  2575. $orderInfo = $this->tidyOrder($orderInfo, true);
  2576. $cartInfo = $orderInfo['cartInfo'] ?? [];
  2577. $data = [];
  2578. if ($cart_ids) {
  2579. foreach ($cart_ids as $cart) {
  2580. if (!isset($cart['cart_id']) || !$cart['cart_id']) {
  2581. throw new ValidateException('请重新选择退款商品,或件数');
  2582. }
  2583. }
  2584. $cart_ids = array_combine(array_column($cart_ids, 'cart_id'), $cart_ids);
  2585. $i = 0;
  2586. foreach ($cartInfo as $item) {
  2587. if (isset($cart_ids[$item['id']])) {
  2588. $data['cartInfo'][$i] = $item;
  2589. if (isset($cart_ids[$item['id']]['cart_num'])) $data['cartInfo'][$i]['cart_num'] = $cart_ids[$item['id']]['cart_num'];
  2590. $i++;
  2591. }
  2592. }
  2593. }
  2594. $data['_status'] = $orderInfo['_status'] ?? [];
  2595. $data['cartInfo'] = $data['cartInfo'] ?? $cartInfo;
  2596. return $data;
  2597. }
  2598. /**
  2599. * 拆单的发货订单数量
  2600. * @param int $id
  2601. * @param $order
  2602. * @return int
  2603. * @throws \think\db\exception\DataNotFoundException
  2604. * @throws \think\db\exception\DbException
  2605. * @throws \think\db\exception\ModelNotFoundException
  2606. */
  2607. public function getDeliverNum(int $id, $order): int
  2608. {
  2609. if (!$order) {
  2610. $order = $this->get($id);
  2611. }
  2612. $ids = $id;
  2613. $pid = (int)$order['pid'];
  2614. if ($pid > 0) {
  2615. $ids = $this->Value([['pid', '=', $pid], ['status', '=', 1]], 'GROUP_CONCAT(id)');
  2616. if (!empty($ids)) {
  2617. $ids = array_map('intval', array_filter(explode(',', $ids)));
  2618. }
  2619. }
  2620. return $this->getCount(['id' => $ids, 'status' => 1]);
  2621. }
  2622. /**
  2623. * 获取确认订单页面是否展示快递配送和到店自提
  2624. * @param $uid
  2625. * @param $cartIds
  2626. * @param $new
  2627. * @return array
  2628. * @throws \Psr\SimpleCache\InvalidArgumentException
  2629. */
  2630. public function checkShipping($uid, $cartIds, $new)
  2631. {
  2632. if ($new) {
  2633. $cartIds = explode(',', $cartIds);
  2634. $cartInfo = [];
  2635. $redis = CacheService::redisHandler();
  2636. foreach ($cartIds as $key) {
  2637. $info = $redis->get($key);
  2638. if ($info) {
  2639. $cartInfo[] = $info;
  2640. }
  2641. }
  2642. } else {
  2643. /** @var StoreCartServices $cartServices */
  2644. $cartServices = app()->make(StoreCartServices::class);
  2645. $cartInfo = $cartServices->getCartList(['uid' => $uid, 'status' => 1, 'id' => $cartIds], 0, 0, ['productInfo', 'attrInfo']);
  2646. }
  2647. if (!$cartInfo) {
  2648. throw new ValidateException('获取购物车信息失败');
  2649. }
  2650. $arr = [];
  2651. $store_id = [];
  2652. //delivery_type :1、快递,2、到店自提,3、门店配送
  2653. foreach ($cartInfo as $item) {
  2654. $delivery_type = is_string($item['productInfo']['delivery_type']) ? explode(',', $item['productInfo']['delivery_type']) : $item['productInfo']['delivery_type'];
  2655. if (in_array(1, $delivery_type)) {//支持平台配送 验证平台该商品
  2656. $productInfo = $item['productInfo'] ?? [];
  2657. if ($productInfo && isset($productInfo['type']) && $productInfo['type'] == 1 && isset($productInfo['pid']) && $productInfo['pid']) {
  2658. /** @var StoreProductServices $productServices */
  2659. $productServices = app()->make(StoreProductServices::class);
  2660. $platInfo = $productServices->getCacheProductInfo((int)$productInfo['pid']);
  2661. if (!$platInfo || $platInfo['stock'] <= 0) {
  2662. unset($delivery_type[array_search('1', $delivery_type)]);
  2663. }
  2664. }
  2665. }
  2666. $arr = array_merge($arr, $delivery_type);
  2667. if (isset($item['productInfo']['type']) && isset($item['productInfo']['relation_id']) && $item['productInfo']['type'] == 1 && $item['productInfo']['relation_id']) {
  2668. $store_id[] = $item['productInfo']['relation_id'];
  2669. }
  2670. }
  2671. $count = count($arr);
  2672. if (!$count) {
  2673. $arr = [1, 2, 3];
  2674. }
  2675. // 门店总开关
  2676. if (!sys_config('store_func_status', 1)) {
  2677. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2678. if (in_array(3, $arr)) unset($arr[array_search(3, $arr)]);
  2679. } elseif (sys_config('store_self_mention', 1)) {
  2680. //判断有没有满足自提的店铺
  2681. $where['id'] = $store_id;
  2682. $where['is_store'] = 1;
  2683. $where['is_show'] = 1;
  2684. $where['is_del'] = 0;
  2685. /** @var SystemStoreServices $SystemStoreServe */
  2686. $SystemStoreServe = app()->make(SystemStoreServices::class);
  2687. $store_list = $SystemStoreServe->count($where);
  2688. if (!$store_list) {
  2689. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2690. }
  2691. } else {
  2692. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2693. }
  2694. $arr = array_merge(array_unique($arr));
  2695. return ['type' => $arr];
  2696. }
  2697. /**
  2698. * @param int $pid
  2699. * @param int $order_id
  2700. * @return bool
  2701. * @throws \think\db\exception\DbException
  2702. */
  2703. public function checkSubOrderNotSend(int $pid, int $order_id)
  2704. {
  2705. $order_count = $this->dao->getSubOrderNotSend($pid, $order_id);
  2706. if ($order_count > 0) {
  2707. return false;
  2708. } else {
  2709. return true;
  2710. }
  2711. }
  2712. /**
  2713. * @param int $pid
  2714. * @param int $order_id
  2715. * @return bool
  2716. * @throws \think\db\exception\DbException
  2717. */
  2718. public function checkSubOrderNotTake(int $pid, int $order_id)
  2719. {
  2720. $order_count = $this->dao->getSubOrderNotTake($pid, $order_id);
  2721. if ($order_count > 0) {
  2722. return false;
  2723. } else {
  2724. return true;
  2725. }
  2726. }
  2727. /**
  2728. * 地区返佣
  2729. * @param $orderInfo
  2730. * @param $userInfo
  2731. * @return bool
  2732. */
  2733. public function backAreaBrokerage()
  2734. {
  2735. //商城分销功能是否开启 0关闭1开启
  2736. if (!sys_config('brokerage_func_status')) return true;
  2737. if (sys_config('area_award_time') <= 0) return true;
  2738. $last_time = sys_config('area_award_last_time');
  2739. if ($last_time + (3600 * (sys_config('area_award_time'))) > time()) {
  2740. return true;
  2741. }
  2742. //冻结时间
  2743. $broken_time = intval(sys_config('extract_time'));
  2744. $frozen_time = time() + $broken_time * 86400;
  2745. $userServices = app()->make(UserServices::class);
  2746. $storeOrderServices = app()->make(StoreOrderServices::class);
  2747. $res = true;
  2748. // 获取上级推广员信息
  2749. /** @var UserServices $userServices */
  2750. //找有代理的省
  2751. $provinces = $userServices->search()->where('area_admin', 3)->column('area_admin_province');
  2752. $provinces = array_unique($provinces);
  2753. foreach ($provinces as $value) {
  2754. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value)
  2755. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2756. ->where('send_area_award', 0)
  2757. ->where('paid', 1)
  2758. ->where('is_del', 0)
  2759. ->where('is_system_del', 0)
  2760. ->where('refund_status', 0)
  2761. ->whereIn('status', [2, 3])
  2762. ->field('sum(total_price-cost) as total_price_sum')
  2763. ->find();
  2764. $order_price = $order_price['total_price_sum'] ?? 0;
  2765. if ($order_price <= 0) {
  2766. continue;
  2767. }
  2768. //找省代
  2769. $admins = $userServices->search()->where('area_admin', 3)->where('area_admin_province', $value)->select();
  2770. if (count($admins) > 0) {
  2771. $award = bcdiv(bcmul((string)sys_config('province_award'), (string)$order_price, 2), 100, 2);
  2772. if ($award > 0) {
  2773. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2774. if ($brokeragePrice > 0) {
  2775. foreach ($admins as $v) {
  2776. $spreadPrice = (string)$v['brokerage_price'];
  2777. // 上级推广员返佣之后的金额
  2778. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2779. // 添加佣金记录
  2780. /** @var UserBrokerageServices $userBrokerageServices */
  2781. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2782. $type = 'get_area_award';
  2783. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2784. 'pay_price' => floatval($order_price),
  2785. 'area' => $value . '省级',
  2786. 'number' => floatval($brokeragePrice),
  2787. 'frozen_time' => $frozen_time
  2788. ], $balance, 0);
  2789. // 添加用户佣金
  2790. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2791. $res = $res1 && $res2 && $res;
  2792. }
  2793. }
  2794. }
  2795. }
  2796. }
  2797. $citys = $userServices->search()->where('area_admin', 2)->select();
  2798. $pc = [];
  2799. foreach ($citys as $v) {
  2800. $p = $v['area_admin_province'];
  2801. $c = $v['area_admin_city'];
  2802. if (!in_array(compact('p', 'c'), $pc)) {
  2803. $pc[] = compact('p', 'c');
  2804. }
  2805. }
  2806. foreach ($pc as $value) {
  2807. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value['p'])->where('order_city', $value['c'])
  2808. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2809. ->where('send_area_award', 0)
  2810. ->where('paid', 1)
  2811. ->where('is_del', 0)
  2812. ->where('is_system_del', 0)
  2813. ->where('refund_status', 0)
  2814. ->whereIn('status', [2, 3])
  2815. ->field('sum(total_price-cost) as total_price_sum')
  2816. ->find();
  2817. $order_price = $order_price['total_price_sum'] ?? 0;
  2818. if ($order_price <= 0) {
  2819. continue;
  2820. }
  2821. //找市代
  2822. $admins = $userServices->search()->where('area_admin', 2)->where('area_admin_province', $value['p'])
  2823. ->where('area_admin_city', $value['c'])->select();
  2824. if (count($admins) > 0) {
  2825. $award = bcdiv(bcmul((string)sys_config('city_award'), (string)$order_price, 2), 100, 2);
  2826. if ($award > 0) {
  2827. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2828. if ($brokeragePrice > 0) {
  2829. foreach ($admins as $v) {
  2830. $spreadPrice = (string)$v['brokerage_price'];
  2831. // 上级推广员返佣之后的金额
  2832. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2833. // 添加佣金记录
  2834. /** @var UserBrokerageServices $userBrokerageServices */
  2835. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2836. $type = 'get_area_brokerage';
  2837. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2838. 'pay_price' => floatval($order_price),
  2839. 'area' => $value['p'] . $value['c'] . '级',
  2840. 'number' => floatval($brokeragePrice),
  2841. 'frozen_time' => $frozen_time
  2842. ], $balance, 0);
  2843. // 添加用户佣金
  2844. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2845. $res = $res1 && $res2 && $res;
  2846. }
  2847. }
  2848. }
  2849. }
  2850. }
  2851. $citys = $userServices->search()->where('area_admin', 1)->select();
  2852. $pcd = [];
  2853. foreach ($citys as $v) {
  2854. $p = $v['area_admin_province'];
  2855. $c = $v['area_admin_city'];
  2856. $d = $v['area_admin_district'];
  2857. if (!in_array(compact('p', 'c', 'd'), $pcd)) {
  2858. $pcd[] = compact('p', 'c', 'd');
  2859. }
  2860. }
  2861. foreach ($pcd as $value) {
  2862. $order_price = $storeOrderServices->search(['pid' => 0])
  2863. ->where('order_province', $value['p'])
  2864. ->where('order_city', $value['c'])
  2865. ->where('order_district', $value['d'])
  2866. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2867. ->where('send_area_award', 0)
  2868. ->where('paid', 1)
  2869. ->where('is_del', 0)
  2870. ->where('is_system_del', 0)
  2871. ->where('refund_status', 0)
  2872. ->whereIn('status', [2, 3])
  2873. ->field('sum(total_price-cost) as total_price_sum')
  2874. ->find();
  2875. $order_price = $order_price['total_price_sum'] ?? 0;
  2876. if ($order_price <= 0) {
  2877. continue;
  2878. }
  2879. //找区代
  2880. $admins = $userServices->search()->where('area_admin', 1)
  2881. ->where('area_admin_province', $value['p'])
  2882. ->where('area_admin_city', $value['c'])
  2883. ->where('area_admin_district', $value['d'])
  2884. ->select();
  2885. if (count($admins) > 0) {
  2886. $award = bcdiv(bcmul((string)sys_config('district_award'), (string)$order_price, 2), 100, 2);
  2887. if ($award > 0) {
  2888. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2889. if ($brokeragePrice > 0) {
  2890. foreach ($admins as $v) {
  2891. $spreadPrice = (string)$v['brokerage_price'];
  2892. // 上级推广员返佣之后的金额
  2893. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2894. // 添加佣金记录
  2895. /** @var UserBrokerageServices $userBrokerageServices */
  2896. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2897. $type = 'get_area_brokerage';
  2898. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2899. 'pay_price' => floatval($order_price),
  2900. 'area' => $value['p'] . $value['c'] . $value['d'] . '级',
  2901. 'number' => floatval($brokeragePrice),
  2902. 'frozen_time' => $frozen_time
  2903. ], $balance, 0);
  2904. // 添加用户佣金
  2905. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2906. $res = $res1 && $res2 && $res;
  2907. }
  2908. }
  2909. }
  2910. }
  2911. }
  2912. return $res
  2913. && $storeOrderServices->search()->where('send_area_award', 0)->update(['send_area_award' => 1])
  2914. && SystemConfig::where('menu_name', 'area_award_last_time')->update(['value' => time()]);
  2915. }
  2916. }