StoreOrderServices.php 134 KB

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