minutes.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. <?php
  2. /**
  3. * 任务计划 - 分钟执行的任务
  4. *
  5. *
  6. *
  7. *
  8. */
  9. defined('InShopNC') or exit('Access Invalid!');
  10. require_once (BASE_ROOT_PATH . '/helper/message/publisher.php');
  11. require_once(BASE_HELPER_PATH . '/refill/util.php');
  12. require_once(BASE_HELPER_PATH . '/refill/divert_account.php');
  13. require_once(BASE_HELPER_PATH . '/refill/RefillFactory.php');
  14. require_once(BASE_CORE_PATH . '/framework/function/http.php');
  15. require_once(BASE_HELPER_PATH . '/PHPExcel/PHPExcel.php');
  16. require_once(BASE_HELPER_PATH . '/task/task_helper.php');
  17. class minutesControl extends BaseCronControl
  18. {
  19. public function indexexOp()
  20. {
  21. $this->_cron_common([1,2,3,4,5,6,7]);
  22. }
  23. public function indexOp()
  24. {
  25. Log::record(__FUNCTION__ . " start",Log::DEBUG);
  26. //未付款订单超期自动关闭
  27. // $this->_order_timeout_cancel();
  28. $this->_cron_common([1,2,3,4,5,6,7]);
  29. $this->_fetch_order_unavaliable();
  30. $this->_check_merchant_alarm_amount();
  31. Log::record(__FUNCTION__ . " end",Log::DEBUG);
  32. // $this->_web_index_update();
  33. // $this->_check_merchant_alarm_amount();
  34. // $this->check_refill_order_limit();
  35. // $this->_cron_mail_send();
  36. // $this->_SendOrderQuery();
  37. }
  38. //任务队列处理
  39. public function admin_taskOp()
  40. {
  41. Log::short_name('task');
  42. Log::record('start task',Log::DEBUG);
  43. $this->exec_task(false);
  44. }
  45. public function update_channel_balanceOp()
  46. {
  47. $balance_getter = function ($provider_id)
  48. {
  49. $provider_model = Model('refill_provider');
  50. $provider_info = $provider_model->getProviderInfo(['provider_id' => $provider_id, 'opened' => 1]);
  51. if (empty($provider_info)) {
  52. return false;
  53. }
  54. $channel_name = $provider_info['name'];
  55. if ($provider_info['type'] == 1) {
  56. $type = 'RefillOil';
  57. } elseif ($provider_info['type'] == 2 || $provider_info['type'] == 3) {
  58. $type = 'RefillPhone';
  59. } else {
  60. $type = 'RefillPhone';
  61. }
  62. Log::record("query balance channel_name:{$channel_name}",Log::DEBUG);
  63. $provider = refill\util::getProvider($channel_name,$type);
  64. if($provider == false) return false;
  65. [$state, $balance] = $provider->balance();
  66. Log::record("query balance channel_name:{$channel_name}, err_msg:{$balance}",Log::DEBUG);
  67. if(!$state) {
  68. return false;
  69. } else {
  70. return round(floatval($balance),4);
  71. }
  72. };
  73. $providers = function ()
  74. {
  75. $pids = [];
  76. $i = 0;
  77. while (true)
  78. {
  79. $start = $i * 1000;
  80. $items = Model()->table('refill_provider')->where(['opened' => 1])->field('*')->order('provider_id desc')->limit("{$start},1000")->select();
  81. if(empty($items)) {
  82. return $pids;
  83. }
  84. $i++;
  85. foreach ($items as $item) {
  86. $pid = intval($item['provider_id']);
  87. $pids[] = $pid;
  88. }
  89. }
  90. };
  91. $mod_provider = Model('refill_provider');
  92. $pids = $providers();
  93. foreach ($pids as $pid)
  94. {
  95. try {
  96. $balance = $balance_getter($pid);
  97. if($balance !== false) {
  98. $mod_provider->editProvider(['balance' => $balance],['provider_id' => $pid]);
  99. }
  100. }
  101. catch (Exception $ex)
  102. {
  103. Log::record($ex->getMessage(),Log::ERR);
  104. }
  105. }
  106. }
  107. private function _fetch_order_unavaliable()
  108. {
  109. try {
  110. $mod_fetch_order = Model('fetch_order');
  111. $trans = new trans_wapper($mod_fetch_order,__METHOD__);
  112. $items = $mod_fetch_order->timeout_orders(900);
  113. foreach ($items as $item) {
  114. $fetch_id = $item['fetch_id'];
  115. $mod_fetch_order->unavaliable($fetch_id);
  116. }
  117. $trans->commit();
  118. foreach ($items as $item) {
  119. $order_sn = $item['order_sn'];
  120. $chname = $item['channel_name'];
  121. refill\util::push_notify($chname,['order_sn' => $order_sn,'state' => 'CANCEL']);
  122. }
  123. }
  124. catch (Exception $ex) {
  125. $trans->rollback();
  126. Log::record(__METHOD__ . " " . $ex->getMessage(),Log::ERR);
  127. }
  128. }
  129. private function _check_merchant_alarm_amount()
  130. {
  131. $mch_cache = rcache("merchant-notify", 'refill-');
  132. $caches = empty($mch_cache['data']) ? [] : unserialize($mch_cache['data']);
  133. $new_caches = [];
  134. $merchants = Model('merchant')->getMerchantList(['merchant.merchant_state' => 1], '', '', true, 'merchant.*,member.available_predeposit', "0,1000");
  135. foreach ($merchants as $merchant) {
  136. $mchid = $merchant['mchid'];
  137. $phones = empty($merchant['warning_phone']) ? [] : unserialize($merchant['warning_phone']);
  138. $available_pd = intval($merchant['available_predeposit']);
  139. $alarm_pd = intval($merchant['alarm_amount']);
  140. if (array_key_exists($mchid, $caches)) {
  141. $mch_cache = $caches[$mchid];
  142. } else {
  143. $mch_cache = ['last_time' => 0, 'send_count' => 0];
  144. }
  145. if ($available_pd < $alarm_pd || $available_pd < 10000) {
  146. $counts = $mch_cache['send_count'];
  147. if (($mch_cache['last_time'] + 300 < time()) && $counts < 2) {
  148. $mch_cache = ['last_time' => time(), 'send_count' => $counts + 1];
  149. foreach ($phones as $phone) {
  150. if (!empty($phone)) {
  151. QueueClient::push('sendSMS', ['mobile' => $phone,
  152. 'type' => 'balance_warning', 'datas' => [date("m月d日H时"), $merchant['available_predeposit']]]);
  153. }
  154. }
  155. }
  156. } else {
  157. $mch_cache = ['last_time' => 0, 'send_count' => 0];
  158. }
  159. $new_caches[$mchid] = $mch_cache;
  160. }
  161. wcache("merchant-notify", ['data' => serialize($new_caches)], 'refill-');
  162. }
  163. public function check_refill_order_limit()
  164. {
  165. $mch_cache = rcache("storge_limit" , 'merchant-');
  166. $caches = empty($mch_cache['data']) ? [] : unserialize($mch_cache['data']);
  167. $reader = function ($mchid,$time)
  168. {
  169. $cond['mchid'] = $mchid;
  170. $cond['inner_status'] = 0;
  171. $cond['order_state'] = ORDER_STATE_SUCCESS;
  172. $cond['refill_order.order_time'] = ['egt', $time];
  173. $items = Model('')->table('refill_order,vr_order')->join('inner')
  174. ->on('refill_order.order_id=vr_order.order_id')
  175. ->field('refill_order.mchid,refill_order.card_type,refill_order.refill_amount,count(*) as num')
  176. ->group('refill_order.card_type,refill_order.refill_amount')
  177. ->where($cond)->select();
  178. return $items;
  179. };
  180. $merger = function ($limits,$reals,$mchid,$card_type)
  181. {
  182. $result = [];
  183. foreach ($limits as $amount => $limit)
  184. {
  185. $limit = intval($limit);
  186. if($limit === -1) {
  187. $allow = true;
  188. }
  189. elseif($limit === 0) {
  190. $allow = false;
  191. }
  192. else
  193. {
  194. $finded = false;
  195. foreach ($reals as $item)
  196. {
  197. $tmp = intval($item['refill_amount'] + 0.005);
  198. if($item['card_type'] == $card_type && $tmp == $amount) {
  199. $num = $item['num'];
  200. $allow = $limit > $num;
  201. $finded = true;
  202. break;
  203. }
  204. }
  205. if(!$finded) {
  206. $allow = true;
  207. }
  208. }
  209. $result["{$mchid}-{$card_type}-{$amount}"] = $allow;
  210. }
  211. return $result;
  212. };
  213. $type_map = ['petrochina' => 1,'sinopec' => 2];
  214. $abilitys = [];
  215. foreach ($caches as $cache)
  216. {
  217. $mchid = intval($cache['mchid']);
  218. $start = $cache['time'];
  219. $petros = $cache['petrochina'];
  220. $sinos = $cache['sinopec'];
  221. $items = $reader($mchid,$start);
  222. $prets = $merger($petros,$items,$mchid,$type_map['petrochina']);
  223. $srets = $merger($sinos,$items,$mchid,$type_map['sinopec']);
  224. foreach ($prets as $key => $val) {
  225. $abilitys[$key] = $val;
  226. }
  227. foreach ($srets as $key => $val) {
  228. $abilitys[$key] = $val;
  229. }
  230. }
  231. $old = rcache("refill_able",'merchant-');
  232. $old = empty($old) ? "" : $old['data'];
  233. ksort($abilitys);
  234. $new = serialize($abilitys);
  235. if($new != $old) {
  236. wcache("refill_able" , ['data' => $new] , 'merchant-');
  237. // $publisher = new message\publisher();
  238. // $publisher->modify_refill_merchant();
  239. }
  240. }
  241. /**
  242. * 未付款订单超期自动关闭
  243. */
  244. private function _order_timeout_cancel()
  245. {
  246. Log::record(__FUNCTION__,Log::DEBUG);
  247. //实物订单超期未支付系统自动关闭
  248. $_break = false;
  249. $model_order = Model('order');
  250. $logic_order = Logic('order');
  251. $condition = [];
  252. $condition['order_state'] = ORDER_STATE_NEW;
  253. $condition['add_time'] = ['lt',time() - ORDER_AUTO_CANCEL_DAY * 86400];
  254. //分批,每批处理100个订单,最多处理5W个订单
  255. for ($i = 0; $i < 500; $i++)
  256. {
  257. if ($_break) {
  258. break;
  259. }
  260. $order_list = $model_order->getOrderList($condition, '', '*', '', 100);
  261. if (empty($order_list)) break;
  262. foreach ($order_list as $order_info)
  263. {
  264. Log::record("1",Log::DEBUG);
  265. $result = $logic_order->changeOrderStateCancel($order_info,'system','系统','超期未支付系统自动关闭订单',true,false);
  266. Log::record("2",Log::DEBUG);
  267. if (!$result['state']) {
  268. $this->log('实物订单超期未支付关闭失败SN:'.$order_info['order_sn']); $_break = true; break;
  269. } else {
  270. Log::record("3",Log::DEBUG);
  271. account_helper::onPredeposit('order_cancel',$order_info['buyer_id'],$order_info['order_sn']);
  272. Log::record("4",Log::DEBUG);
  273. }
  274. }
  275. }
  276. //虚拟订单超期未支付系统自动关闭
  277. $_break = false;
  278. $model_vr_order = Model('vr_order');
  279. $logic_vr_order = Logic('vr_order');
  280. $condition = [];
  281. $condition['order_state'] = ORDER_STATE_NEW;
  282. $condition['add_time'] = ['lt',time() - VRORDER_AUTO_CANCEL_MINUTE * 60];
  283. //分批,每批处理100个订单,最多处理5W个订单
  284. for ($i = 0; $i < 500; $i++)
  285. {
  286. if ($_break) {
  287. break;
  288. }
  289. $order_list = $model_vr_order->getOrderList($condition, '', '*', '',100);
  290. if (empty($order_list)) break;
  291. foreach ($order_list as $order_info) {
  292. $result = $logic_vr_order->changeOrderStateCancel($order_info,'system','超期未支付系统自动关闭订单',false);
  293. }
  294. if (!$result['state']) {
  295. $this->log('虚拟订单超期未支付关闭失败SN:'.$order_info['order_sn']);
  296. $_break = true;
  297. }
  298. }
  299. }
  300. /**
  301. * 更新首页的商品价格信息
  302. */
  303. private function _web_index_update()
  304. {
  305. Model('web_config')->updateWebGoods();
  306. }
  307. /**
  308. * 发送邮件消息
  309. */
  310. private function _cron_mail_send()
  311. {
  312. //每次发送数量
  313. $_num = 50;
  314. $model_storemsgcron = Model('mail_cron');
  315. $cron_array = $model_storemsgcron->getMailCronList([], $_num);
  316. if (!empty($cron_array))
  317. {
  318. $email = new Email();
  319. $mail_array = [];
  320. foreach ($cron_array as $val)
  321. {
  322. $return = $email->send_sys_email($val['mail'],$val['subject'],$val['contnet']);
  323. if ($return) {
  324. // 记录需要删除的id
  325. $mail_array[] = $val['mail_id'];
  326. }
  327. }
  328. // 删除已发送的记录
  329. $model_storemsgcron->delMailCron(['mail_id' => ['in', $mail_array]]);
  330. }
  331. }
  332. public function second_queueOp()
  333. {
  334. while (true)
  335. {
  336. do{
  337. try {
  338. $ret = $this->_cron_common([8]);
  339. perfor_clear();
  340. } catch (Exception $ex) {
  341. Log::record($ex->getMessage(),Log::ERR);
  342. }
  343. }
  344. while($ret === true);
  345. sleep(1);
  346. }
  347. }
  348. public function account_editOp()
  349. {
  350. $stamp = 0;
  351. while (true)
  352. {
  353. try {
  354. $divertor = new refill\divert_account();
  355. $next = time();
  356. $divertor->update_account($stamp);
  357. $stamp = $next;
  358. } catch (Exception $ex) {
  359. Log::record($ex->getMessage(),Log::ERR);
  360. }
  361. sleep(1);
  362. }
  363. }
  364. private function exec_task($merchant)
  365. {
  366. $task_manager = new task\manager();
  367. $task_id = 0;
  368. while (true)
  369. {
  370. try
  371. {
  372. $task = $task_manager->pop_task($task_id,$merchant);
  373. if (!empty($task)) {
  374. $task_manager->handle($task);
  375. $task_id = $task['task_id'];
  376. }
  377. }
  378. catch (Exception $ex) {
  379. Log::record($ex->getMessage(),Log::ERR);
  380. }
  381. sleep(1);
  382. }
  383. }
  384. //任务队列处理
  385. public function merchant_taskOp()
  386. {
  387. Log::short_name('merchant_task');
  388. Log::record('start task',Log::DEBUG);
  389. $this->exec_task(true);
  390. }
  391. //更新统计业务数据
  392. public function stat_utilOp()
  393. {
  394. Log::short_name('stat_util');
  395. while (true)
  396. {
  397. try {
  398. $this->_update_earlist_send();
  399. $this->_calc_arrears();
  400. } catch (Exception $ex) {
  401. Log::record($ex->getMessage(), Log::ERR);
  402. }
  403. sleep(1);
  404. }
  405. }
  406. //更新统计业务数据
  407. public function statOp()
  408. {
  409. Log::short_name('stat');
  410. while (true)
  411. {
  412. try {
  413. $this->_update_earlist_send();
  414. $this->_calc_arrears();
  415. } catch (Exception $ex) {
  416. Log::record($ex->getMessage(), Log::ERR);
  417. }
  418. sleep(1);
  419. }
  420. }
  421. private function _update_earlist_send()
  422. {
  423. //查找最早的充值中的订单时间
  424. // $update_earliest_ordertime = function () {
  425. // $mod = Model('refill_detail');
  426. // $time = $mod->getEarliestSendTime();
  427. // wcache('stat-info', ['earliest_order_time' => $time], 'refill-');
  428. // };
  429. // $update_earliest_ordertime();
  430. //按各个机构,更新最早的充值中的订单时间
  431. $update_earliest_ordertime_bymerchant = function () {
  432. $mod = Model('refill_detail');
  433. $mtimes = $mod->getEarliestSendTimeByMerchant();
  434. $val = json_encode($mtimes);
  435. wkcachex('stat-earliest-ordertime', $val, 'refill-');
  436. };
  437. $update_earliest_ordertime_bymerchant();
  438. }
  439. private function _calc_arrears()
  440. {
  441. $send_amount_reader = function () {
  442. $val = rkcachex('stat-merchant-sendamount', 'refill-');
  443. $val = json_decode($val, true);
  444. return $val;
  445. };
  446. $del_stop = function ($amounts)
  447. {
  448. $ins = Cache::getInstance('cacheredis');
  449. $items = $ins->hkeys('merchant-debts-detail','refill-');
  450. if(empty($items)) {
  451. return;
  452. }
  453. $keys = [];
  454. foreach ($items as $key) {
  455. $keys[] = intval($key);
  456. }
  457. foreach ($keys as $mchid)
  458. {
  459. if(array_key_exists($mchid,$amounts)) {
  460. continue;
  461. } else {
  462. $ins->hdel('merchant-debts-detail','refill-',$mchid);
  463. }
  464. }
  465. };
  466. $debts_detail_fun = function ($amounts)
  467. {
  468. $debts_detail = [];
  469. $mod = Model();
  470. $i = 0;
  471. while (true)
  472. {
  473. $start = $i * 1000;
  474. $items = $mod->table('merchant,member')->join('inner')->on('member.member_id=merchant.admin_id')
  475. ->field('mchid,credit_bonus,co_id,available_predeposit')->where(['merchant_state' => 1, 'co_id' => ['gt', 0]])->order('mchid asc')->limit("{$start},1000")->select();
  476. if(empty($items)) {
  477. break;
  478. }
  479. $i++;
  480. foreach ($items as $item)
  481. {
  482. $mchid = intval($item['mchid']);
  483. $co_id = intval($item['co_id']);
  484. $credit_bonus = round(floatval($item['credit_bonus']), 2);
  485. $available_predeposit = round(floatval($item['available_predeposit']), 2);
  486. if (array_key_exists($mchid, $amounts)) {
  487. $send_amounts = $amounts[$mchid]['send_amounts'];
  488. $lack_amounts = $amounts[$mchid]['lack_amounts'];
  489. } else {
  490. $send_amounts = 0;
  491. $lack_amounts = 0;
  492. }
  493. Log::record("co_id={$co_id} mchid={$mchid} send_amounts={$send_amounts} lack_amounts={$lack_amounts}",Log::DEBUG);
  494. $available = $available_predeposit - $credit_bonus + $send_amounts;// - $lack_amounts;
  495. $debt = -$available;
  496. $debts_detail[$co_id][$mchid] = $debt;
  497. $val = ['debt' => $debt, 'send_amounts' => $send_amounts, 'lack_amounts' => $lack_amounts];
  498. wcache('merchant-debts-detail', [$mchid => serialize($val)], 'refill-');
  499. }
  500. }
  501. return $debts_detail;
  502. };
  503. $company_debt_fun = function ()
  504. {
  505. $co_debts = [];
  506. $mod = Model('refill_company');
  507. $i = 0;
  508. while (true)
  509. {
  510. $start = $i * 1000;
  511. $items = $mod->field('co_id,max_debt')->where(['opened' => 1, 'co_type' => 'merchant'])->order('co_id asc')->limit("{$start},1000")->select();
  512. if(empty($items)) {
  513. break;
  514. }
  515. $i++;
  516. foreach ($items as $item)
  517. {
  518. $co_id = intval($item['co_id']);
  519. $max_debt = round(floatval($item['max_debt']), 2);
  520. $co_debts[$co_id] = $max_debt;
  521. }
  522. }
  523. return $co_debts;
  524. };
  525. $calc_debts = function ($co_id,$detail)
  526. {
  527. if(!array_key_exists($co_id,$detail)) {
  528. return [[], 0];
  529. }
  530. $mchids=[];
  531. $sum_debts = 0;
  532. $co_details = $detail[$co_id];
  533. foreach ($co_details as $mchid => $debts) {
  534. $mchids[] = $mchid;
  535. $sum_debts += $debts;
  536. }
  537. return [$mchids,$sum_debts];
  538. };
  539. $judge_stop = function ($co_debts, $debts_detail) use ($calc_debts)
  540. {
  541. foreach ($co_debts as $co_id => $max_debts)
  542. {
  543. [$mchids, $sum_debts] = $calc_debts($co_id,$debts_detail);
  544. wcache('company-debts', [$co_id => $sum_debts], 'refill-');
  545. if(empty($mchids)) continue;
  546. if($max_debts < $sum_debts) {
  547. $fStop = 1;
  548. } else {
  549. $fStop = 0;
  550. }
  551. foreach ($mchids as $mchid) {
  552. wcache('merchant-debt-judge', [$mchid => $fStop], 'refill-');
  553. }
  554. }
  555. };
  556. $need_calc = function ($clac_time)
  557. {
  558. static $latest_time = 0;
  559. if($clac_time > $latest_time) {
  560. $latest_time = $clac_time;
  561. return true;
  562. } else {
  563. return false;
  564. }
  565. };
  566. $result = $send_amount_reader();
  567. $del_stop($result);
  568. if (!empty($result) && $need_calc(intval($result['time']))) {
  569. $mch_amounts = $result['send_amounts'];
  570. $debts_detail = $debts_detail_fun($mch_amounts);
  571. $co_debts = $company_debt_fun();
  572. $judge_stop($co_debts, $debts_detail);
  573. }
  574. }
  575. /**
  576. * 执行通用任务
  577. */
  578. private function _cron_common($types)
  579. {
  580. Log::record(__FUNCTION__,Log::DEBUG);
  581. //查找待执行任务
  582. $model_cron = Model('cron');
  583. $cron = $model_cron->getCronList(['exetime'=> ['elt',time()],'type' => ['in',$types]]);
  584. if (!is_array($cron)) return false;
  585. $count = count($cron);
  586. if ($count <= 0) return false;
  587. Log::record("match cron count={$count}",Log::DEBUG);
  588. $cron_array = [];
  589. $cronid = [];
  590. $exeid = 1;
  591. foreach ($cron as $v)
  592. {
  593. $type = intval($v['type']);
  594. if($type == 8) {
  595. $cron_array[$v['type']][$exeid] = $v;
  596. $exeid++;
  597. }
  598. else {
  599. $cron_array[$v['type']][$v['exeid']] = $v;
  600. }
  601. }
  602. foreach ($cron_array as $k=>$v)
  603. {
  604. // 如果方法不存是,直接删除id
  605. if (!method_exists($this,'_cron_'.$k)) {
  606. $tmp = current($v);
  607. $cronid[] = $tmp['id'];
  608. continue;
  609. }
  610. $method = '_cron_'.$k;
  611. Log::record("crontab minutest:{$method}",Log::DEBUG);
  612. $result = call_user_func_array([$this, '_cron_' . $k], [$v]);
  613. if (is_array($result)) {
  614. $cronid = array_merge($cronid, $result);
  615. } else {
  616. $method = '_cron_' . $k;
  617. Log::record("crontab minutest err:{$method}", Log::ERR);
  618. }
  619. }
  620. //删除执行完成的cron信息
  621. if (!empty($cronid) && is_array($cronid)) {
  622. $model_cron->delCron(['id' => ['in', $cronid]]);
  623. }
  624. return true;
  625. }
  626. //'任务类型 1商品上架 2根据商品id更新商品促销价格 3优惠套装过期 4推荐展位过期 5团购开始更新商品促销价格 6团购过期 7限时折扣过期',
  627. //1商品上架
  628. private function _cron_1($cron = array())
  629. {
  630. $condition = ['goods_commonid' => ['in',array_keys($cron)]];
  631. $update = Model('goods')->editProducesOnline($condition);
  632. if ($update)
  633. {
  634. //返回执行成功的cronid
  635. $cronid = [];
  636. foreach ($cron as $v) {
  637. $cronid[] = $v['id'];
  638. }
  639. }
  640. else {
  641. return false;
  642. }
  643. return $cronid;
  644. }
  645. //2根据商品id更新商品促销价格
  646. private function _cron_2($cron = array())
  647. {
  648. $condition = ['goods_id' => ['in',array_keys($cron)]];
  649. $update = Model('goods')->editGoodsPromotionPrice($condition);
  650. if ($update){
  651. //返回执行成功的cronid
  652. $cronid = [];
  653. foreach ($cron as $v) {
  654. $cronid[] = $v['id'];
  655. }
  656. }else{
  657. return false;
  658. }
  659. return $cronid;
  660. }
  661. //3优惠套装过期
  662. private function _cron_3($cron = [])
  663. {
  664. $condition = ['store_id' => ['in', array_keys($cron)]];
  665. $update = Model('p_bundling')->editBundlingQuotaClose($condition);
  666. if ($update) {
  667. //返回执行成功的cronid
  668. $cronid = [];
  669. foreach ($cron as $v) {
  670. $cronid[] = $v['id'];
  671. }
  672. } else {
  673. return false;
  674. }
  675. return $cronid;
  676. }
  677. //4推荐展位过期
  678. private function _cron_4($cron = [])
  679. {
  680. $condition = array('store_id' => array('in', array_keys($cron)));
  681. $update = Model('p_booth')->editBoothClose($condition);
  682. if ($update) {
  683. //返回执行成功的cronid
  684. $cronid = array();
  685. foreach ($cron as $v) {
  686. $cronid[] = $v['id'];
  687. }
  688. } else {
  689. return false;
  690. }
  691. return $cronid;
  692. }
  693. //5团购开始更新商品促销价格
  694. private function _cron_5($cron = array())
  695. {
  696. $condition = [];
  697. $condition['goods_commonid'] = ['in', array_keys($cron)];
  698. $condition['start_time'] = ['lt', time()];
  699. $condition['end_time'] = ['gt', time()];
  700. $groupbuy = Model('groupbuy')->getGroupbuyList($condition);
  701. foreach ($groupbuy as $val) {
  702. Model('goods')->editGoods(['goods_promotion_price' => $val['groupbuy_price'], 'goods_promotion_type' => 1],
  703. ['goods_commonid' => $val['goods_commonid']]);
  704. }
  705. //返回执行成功的cronid
  706. $cronid = array();
  707. foreach ($cron as $v) {
  708. $cronid[] = $v['id'];
  709. }
  710. return $cronid;
  711. }
  712. /**
  713. * 抢购过期
  714. *
  715. * @param array $cron
  716. */
  717. private function _cron_6($cron = array())
  718. {
  719. $condition = ['goods_commonid' => ['in', array_keys($cron)]];
  720. //抢购活动过期
  721. $update = Model('groupbuy')->editExpireGroupbuy($condition);
  722. if ($update){
  723. //返回执行成功的cronid
  724. $cronid = [];
  725. foreach ($cron as $v) {
  726. $cronid[] = $v['id'];
  727. }
  728. }else{
  729. return false;
  730. }
  731. return $cronid;
  732. }
  733. /**
  734. * 限时折扣过期
  735. *
  736. * @param array $cron
  737. */
  738. private function _cron_7($cron = array())
  739. {
  740. $condition = array('xianshi_id' => array('in', array_keys($cron)));
  741. //限时折扣过期
  742. $update = Model('p_xianshi')->editExpireXianshi($condition);
  743. if ($update){
  744. //返回执行成功的cronid
  745. $cronid = array();
  746. foreach ($cron as $v) {
  747. $cronid[] = $v['id'];
  748. }
  749. }
  750. else{
  751. return false;
  752. }
  753. return $cronid;
  754. }
  755. private function _cron_8($cron = array())
  756. {
  757. $cronid = [];
  758. foreach ($cron as $v)
  759. {
  760. $cronid[] = intval($v['id']);
  761. $params = $v['params'];
  762. if(!empty($params))
  763. {
  764. $params = unserialize($params);
  765. if(is_array($params))
  766. {
  767. foreach ($params as $key => $value) {
  768. Log::record("delay queue: {$key}",Log::DEBUG);
  769. QueueClient::push($key,$value);
  770. }
  771. }
  772. }
  773. }
  774. return $cronid;
  775. }
  776. //查询超过5分钟的充值中订单
  777. public function _SendOrderQuery()
  778. {
  779. $model_refill_order = Model('refill_order');
  780. $condition['order_state'] = ORDER_STATE_SEND;
  781. $condition['refill_order.order_time'] = ['lt', (time() - 300)];
  782. $orders = $model_refill_order->getMerchantOrderList($condition, 1000, 0,'refill_order.order_id');
  783. if(!empty($orders)) {
  784. foreach ($orders as $order) {
  785. $order_id = $order['order_id'];
  786. QueueClient::push("QueryRefillState",['order_id' => $order_id]);
  787. }
  788. }
  789. }
  790. //
  791. public function _refill_task(): bool
  792. {
  793. Log::record(__FUNCTION__,Log::DEBUG);
  794. $model_refill_task = Model('refill_task');
  795. $task = $model_refill_task->UnDispose('order_export');
  796. if (empty($task)) return false;
  797. $task_id = $task['task_id'];
  798. $task_condition = unserialize($task['task_condition']);
  799. if (empty($task_condition)) {
  800. Log::record("refill task condition unserialize err, task_id:{$task_id}");
  801. return false;
  802. }
  803. $type = $task['type'];
  804. $cid = $task['cid'];
  805. if ($type === 'merchant') {
  806. $condition['refill_order.mchid'] = $cid;
  807. } elseif ($type === 'provider') {
  808. $condition['vr_order.store_id'] = $cid;
  809. } else {
  810. Log::record("refill task type err, task_id:{$task_id}");
  811. return false;
  812. }
  813. $order_time_type = $task_condition['order_time_type'];
  814. $start_unixtime = $task_condition['start_unixtime'];
  815. $end_unixtime = $task_condition['end_unixtime'];
  816. $order_state = $task_condition['order_state'];
  817. if ($start_unixtime > 0 && $end_unixtime > $start_unixtime) {
  818. $condition["refill_order.{$order_time_type}"] = [['egt', $start_unixtime], ['lt', $end_unixtime], 'and'];
  819. $condition['vr_order.add_time'] = ['egt', $start_unixtime-1];
  820. } elseif ($start_unixtime > 0) {
  821. $condition["refill_order.{$order_time_type}"] = ['egt', $start_unixtime];
  822. $condition['vr_order.add_time'] = ['egt', $start_unixtime-1];
  823. }
  824. if (in_array($order_state, ['0', '10', '20', '30', '40'], true)) {
  825. $condition['order_state'] = $order_state;
  826. }
  827. $model_refill_task->Dispose($task_id);
  828. [$state, $task_result] = $this->order_export($condition, $type, $task_id);
  829. if ($state) {
  830. $model_refill_task->DisposeFinish($task_id, $task_result);
  831. } else {
  832. $model_refill_task->DisposeErr($task_id, $task_result);
  833. }
  834. return true;
  835. }
  836. /**
  837. * @throws PHPExcel_Exception
  838. */
  839. private function order_export($condition, $type, $task_id)
  840. {
  841. $orders = Model('refill_order')->getAllOrders($condition);
  842. if(empty($orders)) {
  843. return [false, '统计数据为空'];
  844. }
  845. $orders = $this->orderFormat($orders);
  846. $objPHPExcel = new PHPExcel();
  847. if ($type === 'merchant') {
  848. $column_keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
  849. $column_values = ['商户号', '客户订单号', '平台单号', '面额', '充值卡号', '充值卡类型', '下单日期', '完成日期', '官方流水号', '订单状态', '扣款金额'];
  850. $data_keys = ['mchid', 'mch_order', 'order_sn', 'refill_amount', 'card_no', 'card_type_text', 'order_time_text', 'notify_time_text', 'official_sn', 'order_state_text', 'mch_amount'];
  851. } elseif ($type === 'provider') {
  852. $column_keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
  853. $column_values = ['上游订单号', '平台单号', '面额', '充值卡号', '充值卡类型', '下单日期', '完成日期', '官方流水号', '订单状态', '扣款金额'];
  854. $data_keys = ['ch_trade_no', 'order_sn', 'refill_amount', 'card_no', 'card_type_text', 'order_time_text', 'notify_time_text', 'official_sn', 'order_state_text', 'channel_amount'];
  855. } else {
  856. return [false, '主体类型错误'];
  857. }
  858. $objPHPExcel->setActiveSheetIndex(0);
  859. $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);
  860. foreach ($column_keys as $key => $column_key) {
  861. $objPHPExcel->getActiveSheet()->getColumnDimension($column_key)->setWidth(25);
  862. $cell_value = $column_key . 1;
  863. $objPHPExcel->getActiveSheet()->setCellValue($cell_value, $column_values[$key]);
  864. }
  865. foreach ($orders as $k => $order) {
  866. foreach ($column_keys as $key => $column_key) {
  867. $field = $column_key.($k+2);
  868. $objPHPExcel->getActiveSheet()->setCellValueExplicit($field, $order[$data_keys[$key]],
  869. PHPExcel_Cell_DataType::TYPE_STRING);
  870. }
  871. }
  872. try {
  873. $path = BASE_ROOT_PATH . "/data/upload/task/";
  874. if(!is_dir($path)){
  875. mkdir($path, 0755);
  876. }
  877. $filename = date('YmdHis',time())."-任务导出-任务ID:{$task_id}.xlsx";
  878. $file_path = $path . $filename;
  879. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  880. $objWriter->save($file_path);
  881. return [true, $filename];
  882. } catch (Exception $e) {
  883. return [false, $e->getMessage()];
  884. }
  885. }
  886. private function orderFormat($orders): array
  887. {
  888. $card_type_texts = [mtopcard\PetroChinaCard => '中石油', mtopcard\SinopecCard => '中石化', mtopcard\ChinaMobileCard => '中国移动', mtopcard\ChinaUnicomCard => '中国联通', mtopcard\ChinaTelecomCard => '中国电信'];
  889. $orderState = function ($order_info) {
  890. $is_retrying = $order_info['is_retrying'];
  891. switch ($order_info['order_state']) {
  892. case ORDER_STATE_CANCEL:
  893. if ($is_retrying) {
  894. $order_state = '重试中';
  895. } else {
  896. $order_state = '已取消';
  897. }
  898. break;
  899. case ORDER_STATE_NEW:
  900. $order_state = '待付款';
  901. break;
  902. case ORDER_STATE_PAY:
  903. $order_state = '待发货';
  904. break;
  905. case ORDER_STATE_SEND:
  906. $order_state = '待收货';
  907. break;
  908. case ORDER_STATE_SUCCESS:
  909. $order_state = '交易完成';
  910. break;
  911. default :
  912. $order_state = '未知状态';
  913. }
  914. return $order_state;
  915. };
  916. foreach($orders as $key => $order)
  917. {
  918. $orders[$key]['card_type_text'] = $card_type_texts[$order['card_type']];
  919. $orders[$key]['order_time_text'] = $order['order_time'] ? date('Y-m-d H:i:s', $order['order_time']) : '';
  920. $orders[$key]['notify_time_text'] = $order['notify_time'] ? date('Y-m-d H:i:s', $order['notify_time']) : '';
  921. $orders[$key]['order_state_text'] = $orderState($order);
  922. }
  923. return $orders;
  924. }
  925. }