public function actionIndex($environment) { $directory = \Yii::$app->basePath . '/environments/' . $environment; if (file_exists($directory)) { FileHelper::copyDirectory($directory, \Yii::$app->basePath); echo Console::renderColoredString('%g' . \Yii::t('app.console', 'Окружение успешно сменено на {env}', ['env' => $environment]), true); echo Console::renderColoredString("%n\n"); } else { throw new Exception(\Yii::t('app.console', 'Указанного окружения не существует')); } }
/** * Updates expired packages */ public function actionUpdateExpired() { $packages = $this->packageRepository->getExpired(); foreach ($packages as $package) { $package->load(); Yii::$app->queue->push('package', Yii::createObject(PackageUpdateCommand::class, [$package])); $message = "Package %N" . $package->getFullName() . '%n'; $message .= " was updated " . Yii::$app->formatter->asRelativeTime($package->getUpdateTime()); $message .= ". %GAdded to queue for update%n\n"; $this->stdout(Console::renderColoredString($message)); } }
public function actionIndex() { ini_set('memory_limit', '128M'); echo '[database connection]', PHP_EOL; echo ' i2db : ' . $this->module->i2db->dsn, PHP_EOL; echo ' infodb : ' . $this->module->infodb->dsn, PHP_EOL; echo '[gearman worker]', PHP_EOL; echo ' server : ' . $this->module->gman_server, PHP_EOL; echo ' function : "pur_gman"', PHP_EOL; echo Console::renderColoredString("%yStart worker...%n"), PHP_EOL; $worker = new GearmanWorker(); $worker->addServers($this->module->gman_server); $worker->addFunction('pur_gman', [$this, 'pur_gman']); while ($worker->work()) { } }
/** * Fetches TOP-$count components from Bower ans saves to `config/bower.list`. * * @param int $count * @param bool $skipCache */ public function actionFetchTop($count = 1000, $skipCache = false) { $result = []; $components = $this->getComponents($skipCache); ArrayHelper::multisort($components, 'stars', SORT_DESC, SORT_NUMERIC); foreach (array_slice($components, 0, $count) as $component) { $result[] = 'bower-asset/' . $component['name']; echo Console::renderColoredString("%R{$component['stars']}%N - %g{$component['name']}%N"); Console::moveCursorTo(0); Console::clearLine(); } $componentsListPath = Yii::getAlias('@hiqdev/assetpackagist/config/bower.list'); file_put_contents($componentsListPath, implode("\n", $result)); echo Console::renderColoredString('Fetched %YBower%N components list. Found %G' . count($components) . "%N components.\n"); echo Console::renderColoredString('Only %bTOP-' . $count . "%N components were added to the packages list.\n"); echo Console::renderColoredString('See %G' . $componentsListPath . "%N\n"); }
public function actionUpdateList($file = STDIN) { $handler = is_resource($file) ? $file : fopen($file, 'r'); $errorPackages = []; while ($line = fgets($handler)) { list($full) = preg_split('/\\s+/', trim($line)); list($type, $name) = AssetPackage::splitFullName($full); if (!$this->actionUpdate($type, $name)) { $errorPackages[] = $full; } } if (!is_resource($file)) { fclose($handler); } if (!empty($errorPackages)) { echo Console::renderColoredString("%RThe following packages were not updated due to unrecoverable errors:%n\n"); echo implode("\n", $errorPackages); } echo "\n"; }
/** * Attaches handlers on Queue events */ private function attachEventHandlers() { $out = function ($string) { $this->stdout(Console::renderColoredString($string)); }; Event::on(Queue::class, Queue::EVENT_BEFORE_WORK, function ($event) use($out) { /** @var JobEvent $event */ $out("%Y[{$event->channel}]%n %GNew job%n '" . get_class($event->job) . "'\n"); }); Event::on(Queue::class, Queue::EVENT_AFTER_WORK, function ($event) use($out) { /** @var JobEvent $event */ $out("%Y[{$event->channel}]%n %GJob%n '" . get_class($event->job) . "' %Gis completed%n\n"); }); Event::on(Queue::class, Queue::EVENT_AFTER_ERROR, function ($event) use($out) { /** @var ErrorEvent $event */ $out("%Y[{$event->channel}]%n %RJob '" . get_class($event->job) . "' finished with error:%n '" . $event->error . "'\n"); }); Event::on(AbstractPackageCommand::class, AbstractPackageCommand::EVENT_BEFORE_RUN, function ($event) use($out) { /** @var AbstractPackageCommand $command */ $command = $event->sender; $out("%g[" . get_class($command) . "]%n Working on package %N" . $command->getPackage()->getFullName() . "%n\n"); }); }
public function run() { $this->beforeRun(); $package = $this->package; $requires = []; foreach ($package->getReleases() as $release) { if (!isset($release['require'])) { continue; } foreach ($release['require'] as $name => $version) { $requires[$name] = true; } } foreach (array_keys($requires) as $name) { $assetPackage = AssetPackage::fromFullName($name); if ($this->packageRepository->exists($assetPackage)) { Yii::trace(Console::renderColoredString('Package %N' . $assetPackage->getFullName() . "%n already exists. Skipping.\n"), __CLASS__); continue; } Yii::$app->queue->push('package', Yii::createObject(PackageUpdateCommand::class, [$assetPackage])); Yii::trace(Console::renderColoredString('Created update command for %Y' . $assetPackage->getFullName() . "%n package\n"), __CLASS__); } $this->afterRun(); }
public function i2conv_run($job) { $workload = $job->workload(); $workload = Json::decode($workload); try { $this->module->i2db->close(); $this->module->infodb->close(); $bidKey = BidKey::findOne($workload['bidid']); if ($bidKey === null) { return; } $bidvalue = $bidKey->bidValue; if ($bidvalue === null) { return; } if (!ArrayHelper::isIn($bidKey->state, ['Y', 'N', 'D'])) { return; } if ($bidKey->bidproc === 'J') { return; } if (empty($bidKey->location)) { return; } switch ($bidKey->bidtype) { case 'con': echo Console::renderColoredString('%y[공사]%n'); break; case 'ser': echo Console::renderColoredString('%g[용역]%n'); break; case 'pur': echo Console::renderColoredString('%b[구매]%n'); break; default: return; } echo $bidKey->constnm; echo '[' . $bidKey->notinum . ']'; echo '(' . $bidKey->state . ',' . $bidKey->bidproc . ')'; //------------------------------------------------------ // v3_bid_key //------------------------------------------------------ $v3bidkey = V3BidKey::findNew($bidKey->bidid); $this->stdout($v3bidkey->isNewRecord ? "[NEW]\n" : "\n", Console::FG_RED); $v3bidkey->attributes = ['whereis' => $bidKey->whereis, 'bidtype' => $bidKey->bidtype, 'con' => strpos($bidKey->bidview, 'con') === false ? 'N' : 'Y', 'ser' => strpos($bidKey->bidview, 'ser') === false ? 'N' : 'Y', 'pur' => strpos($bidKey->bidview, 'pur') === false ? 'N' : 'Y', 'notinum' => $bidKey->notinum, 'orgcode' => $bidKey->orgcode_i, 'constnm' => $bidKey->constnm, 'org' => $bidKey->org_i, 'bidproc' => $bidKey->bidproc, 'contract' => $bidKey->contract, 'bidcls' => $bidKey->bidcls, 'succls' => $bidKey->succls, 'conlevel' => $bidKey->toV3BidKey_conlevel(), 'ulevel' => $bidKey->opt, 'concode' => $bidKey->toV3BidKey_concode(), 'sercode' => $bidKey->toV3BidKey_sercode(), 'purcode' => $bidKey->toV3BidKey_purcode(), 'location' => $bidKey->location ? $bidKey->location : 0, 'convention' => $bidKey->convention == '3' ? '2' : $bidKey->convention, 'presum' => $bidKey->presum ? $bidKey->presum : 0, 'basic' => $bidKey->basic ? $bidKey->basic : 0, 'pct' => $bidKey->pct ? $bidKey->pct : '', 'registdate' => strtotime($bidKey->registdt) > 0 ? date('Y-m-d', strtotime($bidKey->registdt)) : '', 'explaindate' => strtotime($bidKey->explaindt) > 0 ? date('Y-m-d', strtotime($bidKey->explaindt)) : '', 'agreedate' => strtotime($bidKey->agreedt) > 0 ? date('Y-m-d', strtotime($bidKey->agreedt)) : '', 'opendate' => strtotime($bidKey->opendt) > 0 ? date('Y-m-d', strtotime($bidKey->opendt)) : '', 'closedate' => strtotime($bidKey->closedt) > 0 ? date('Y-m-d', strtotime($bidKey->closedt)) : '', 'constdate' => strtotime($bidKey->constdt) > 0 ? date('Y-m-d', strtotime($bidKey->constdt)) : '', 'writedate' => strtotime($bidKey->writedt) > 0 ? date('Y-m-d', strtotime($bidKey->writedt)) : '', 'reswdate' => strtotime($bidKey->resdt) > 0 ? date('Y-m-d', strtotime($bidKey->resdt)) : '', 'state' => $bidKey->state, 'in_id' => 91]; //------------------------------------------------------ // v3_bid_value //------------------------------------------------------ $v3BidValue = V3BidValue::findNew($v3bidkey->bidid); $v3BidValue->attributes = ['scrcls' => $bidvalue->scrcls, 'scrid' => $bidvalue->scrid, 'constno' => $bidvalue->constno, 'refno' => $bidvalue->refno, 'realorg' => $bidvalue->realorg, 'yegatype' => $bidvalue->yegatype, 'yegarng' => str_replace('|', '/', $bidvalue->yegarng), 'prevamt' => $bidvalue->prevamt, 'parbasic' => $bidvalue->parbasic, 'lvcnt' => $bidvalue->lvcnt, 'charger' => str_replace('|', '/', $bidvalue->charger), 'multispare' => str_replace('|', '/', str_replace(',', '', $bidvalue->multispare)), 'contper' => $bidvalue->contper, 'noticedt' => strtotime($bidKey->noticedt) > 0 ? strtotime($bidKey->noticedt) : 0, 'registdt' => strtotime($bidKey->registdt) > 0 ? strtotime($bidKey->registdt) : 0, 'explaindt' => strtotime($bidKey->explaindt) > 0 ? strtotime($bidKey->explaindt) : 0, 'agreedt' => strtotime($bidKey->agreedt) > 0 ? strtotime($bidKey->agreedt) : 0, 'opendt' => strtotime($bidKey->opendt) > 0 ? strtotime($bidKey->opendt) : 0, 'closedt' => strtotime($bidKey->closedt) > 0 ? strtotime($bidKey->closedt) : 0, 'constdt' => strtotime($bidKey->constdt) > 0 ? strtotime($bidKey->constdt) : 0, 'writedt' => strtotime($bidKey->writedt) > 0 ? strtotime($bidKey->writedt) : 0, 'editdt' => strtotime($bidKey->editdt) > 0 ? strtotime($bidKey->editdt) : 0]; //공동도급지역코드 (사용하나??) $arr = explode('|', $bidvalue->contloc); foreach ($arr as $val) { if (empty($val)) { continue; } $m = BidLocal::findOne(['bidid' => $v3bidkey->bidid, 'name' => iconv('utf-8', 'euckr', $val)]); if ($m !== null) { $v3BidValue->contloc = $m->code; break; //v3_bid_key.contloc char(4) 때문 1개 지역만 처리... } } //------------------------------------------------------ // v3_bid_itemcode //------------------------------------------------------ V3BidItemcode::deleteAll(['bidid' => $v3bidkey->bidid]); $bidItemcodes = $bidKey->toV3BidItemcodes_attributes(); foreach ($bidItemcodes as $row) { $v3BidItemcode = V3BidItemcode::findNew($v3bidkey->bidid, $row['bidtype'], $row['code']); $v3BidItemcode->name = $row['name']; $v3BidItemcode->save(); } //------------------------------------------------------ // v3_bid_local //------------------------------------------------------ V3BidLocal::deleteAll(['bidid' => $v3bidkey->bidid]); $bidlocals = $bidKey->bidLocals; foreach ($bidlocals as $bidlocal) { $v3BidLocal = new V3BidLocal(['bidid' => $v3bidkey->bidid, 'code' => $bidLocal->code, 'name' => $bidLocal->name]); $v3BidLocal->save(); } //------------------------------------------------------ // v3_bid_subcode //------------------------------------------------------ V3BidSubcode::deleteAll(['bidid' => $v3bidkey->bidid]); $subcodes = $bidKey->bidSubcodes; foreach ($subcodes as $subcode) { $v3BidSubcode = new V3BidSubcode(['bidid' => $v3bidkey->bidid, 'g2b_code' => $subcode->g2b_code, 'g2b_code_nm' => $subcode->g2b_code_nm, 'i2_code' => $subcode->i2_code, 'itemcode' => $subcode->itemcode, 'pri_cont' => $subcode->pri_cont, 'share' => $subcode->share]); $v3BidSubcode->save(); } //------------------------------------------------------- // v3_bid_content //------------------------------------------------------- $bidcontent = $bidKey->bidContent; if ($bidcontent !== null) { $v3content = V3BidContent::findNew($v3bidkey->bidid); $v3content->attributes = ['content_bid' => $bidcontent->bid_html, 'important_suc' => $bidcontent->nbidcomment, 'content_suc' => $bidcontent->nbid_html, 'upfile_bid' => $bidcontent->bid_file, 'upfile_suc' => $bidcontent->nbid_file, 'important_bid' => !empty($bidcontent->bidcomment_mod) ? $bidcontent->bidcomment_mod . '\\n<hr/>\\n' . $bidcontent->bidcomment : $bidcontent->bidcomment]; $v3content->save(); $v3BidValue->origin_lnk = $bidcontent->orign_lnk; $v3BidValue->attchd_lnk = $bidcontent->attchd_lnk; } //----------------------------------------------------- // v3_bid_goods //----------------------------------------------------- $bidGoods = $bidKey->bidGoods; V3BidGoods::deleteAll(['bidid' => $v3bidkey->bidid]); foreach ($bidGoods as $g) { $v3BidGood = new V3BidGoods(); $v3BidGood->attributes = $g->attributes; $v3BidGood->save(); } //------------------------------------------------------- // v3_bid_res,v3_bid_succom //------------------------------------------------------- $bidRes = $bidKey->bidRes; if (ArrayHelper::isIn($bidKey->bidproc, ['S', 'F']) && $bidRes !== null) { $v3BidResult = V3BidResult::findNew($v3bidkey->bidid); $v3BidResult->attributes = ['yega' => $bidRes->yega, 'innum' => $bidRes->innum, 'officenm1' => $bidRes->officenm1, 'prenm1' => $bidRes->prenm1, 'officeno1' => $bidRes->officeno1, 'success1' => $bidRes->success1, 'resdt' => strtotime($bidKey->resdt) > 0 ? strtotime($bidKey->resdt) : 0, 'reswdt' => strtotime($bidRes->reswdt) > 0 ? strtotime($bidRes->reswdt) : 0]; $arr = explode('|', $bidRes->selms); $selms = []; foreach ($arr as $v) { if ($v == '') { continue; } $selms[] = intval($v) - 1; } $v3BidResult->selms = implode('-', $selms); $v3BidResult->save(); if ($bidKey->whereis != '08' && $bidKey->bidproc != 'F') { $v3BidValue->multispare = str_replace('|', '/', str_replace(',', '', $bidRes->multispare)); } $v3BidValue->save(); if ($bidRes->innum > 0) { $succoms = $bidKey->succoms; if (count($succoms) == $bidRes->innum) { V3BidSuccom::deleteAll(['constdate' => $v3bidkey->constdate, 'bidid' => $v3bidkey->bidid]); Console::startProgress(0, $bidRes->innum); $n = 1; foreach ($succoms as $s) { $v3succom = V3BidSuccom::findNew($v3bidkey->constdate, $v3bidkey->bidid, $s->seq); $v3succom = new V3BidSuccom(['constdate' => $v3bidkey->constdate, 'bidid' => $v3bidkey->bidid, 'seq' => $s->seq, 'regdt' => strtotime($s->regdt) > 0 ? strtotime($s->regdt) : 0, 'pct' => $s->pct, 'prenm' => $s->prenm == null ? '' : $s->prenm, 'officenm' => $s->officenm, 'officeno' => $s->officeno, 'success' => $s->success, 'etc' => $s->etc, 'rank' => $s->rank]); $v3succom->save(); Console::updateProgress($n, $bidRes->innum); $n++; } Console::endProgress(); } } } $v3BidValue->save(); $v3bidkey->save(); $gman_client = new GearmanClient(); $gman_client->addServers($this->module->gman_server); $gman_client->doBackground('i2conv_legacy', Json::encode($workload)); } catch (\Exception $e) { echo Console::ansiFormat($e, [Console::FG_RED]), PHP_EOL; Yii::error($e, 'i2conv'); $gman_client = new GearmanClient(); $gman_client->addServers('192.168.1.242'); $gman_client->doBackground('send_chat_message_from_admin', Json::encode(['recv_id' => 149, 'message' => iconv('cp949', 'utf-8', $e) . "\n[i2conv]"])); } $this->stdout(sprintf("[%s] Peak memory usage: %s MB\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024), Console::FG_GREY); }
public function stdout($str) { $this->controller->stdout(Console::renderColoredString($str)); }
public function onSucData($event) { $row = $event->row; \Yii::info('[' . __METHOD__ . '] $row ' . VarDumper::dumpAsString($row), 'kwater'); $this->stdout(Console::renderColoredString("[KWATER] %g{$row['notinum']}%n {$row['constnm']} ({$row['status']})\n")); try { $bidkey = BidKey::find()->where(['whereis' => '07', 'notinum' => $row['notinum']])->orderBy('bidid desc')->limit(1)->one(); if ($bidkey === null) { $this->stdout(" > 입찰공고가 없습니다.\n", Console::FG_RED); return; } $bidvalue = BidValue::findOne($bidkey->bidid); if ($bidvalue === null) { throw new \Exception('bid_value is empty'); } $bidres = BidRes::findOne($bidkey->bidid); if ($bidres === null) { $bidres = new BidRes(['bidid' => $bidkey->bidid]); } BidSuccom::deleteAll(['bidid' => $bidkey->bidid]); if ($row['bidproc'] == 'F') { $bidres->yega = 0; $bidres->selms = ''; $bidres->multispare = ''; $bidres->officenm1 = '유찰'; $bidres->reswdt = date('Y-m-d H:i:s'); $bidres->save(); $bidkey->bidproc = 'F'; $bidkey->resdt = date('Y-m-d H:i:s'); $bidkey->editdt = date('Y-m-d H:i:s'); $bidkey->save(); return; } $bidres->yega = $row['yega']; $bidres->innum = $row['innum']; $bidres->selms = $row['selms']; $bidres->multispare = $bidvalue->multispare; $bidres->save(); Console::startProgress(0, $row['innum']); foreach ($row['succoms'] as $succom) { $bidsuccom = new BidSuccom(['bidid' => $bidkey->bidid, 'seq' => $succom['seq'], 'officeno' => '', 'officenm' => $succom['officenm'], 'prenm' => '', 'success' => $succom['success'], 'pct' => $succom['pct'], 'rank' => $succom['rank'], 'selms' => '', 'etc' => $succom['etc']]); $bidsuccom->save(); Console::updateProgress($succom['seq'], $row['innum']); } Console::endProgress(); $bidkey->bidproc = 'S'; $bidkey->resdt = date('Y-m-d H:i:s'); $bidkey->editdt = date('Y-m-d H:i:s'); $bidkey->save(); } catch (\Exception $e) { $this->stdout("{$e}\n", Console::FG_RED); \Yii::error($e, 'kwater'); } }
public function work($job) { \Yii::info('suc worker workload ' . $job->workload(), 'kwater'); $workload = Json::decode($job->workload()); $http = $this->module->http; $data = []; if ($workload['status'] == '유찰') { $event = new WatchEvent(); $event->row = ['notinum' => $workload['notinum'], 'bidproc' => 'F']; $this->trigger(WatchEvent::EVENT_ROW, $event); return; } $data['notinum'] = $workload['notinum']; $data['bidproc'] = 'S'; try { $html = $http->request('GET', static::URL_M, ['query' => ['BidNo' => $workload['notinum']]]); $html = strip_tags($html, '<tr><td>'); $html = preg_replace('/<tr[^>]*>/', '<tr>', $html); $html = preg_replace('/<td[^>]*>/', '<td>', $html); $html = str_replace(' ', ' ', $html); \Yii::info($workload['notinum'] . "\n{$html}", 'kwater'); //추첨번호 $p = '/추첨된번호: (?<no>\\d{1,2}) 번/'; $p = str_replace(' ', '\\s*', $p); if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { $selms = []; foreach ($matches as $m) { $selms[] = $m['no']; } sort($selms); $data['selms'] = join('|', $selms); if (count($selms) == 1) { $data['selms'] = ''; } } //개찰결과 $html = $http->request('GET', static::URL, ['query' => ['BidNo' => $workload['notinum']]]); $html = strip_tags($html, '<tr><td>'); $html = preg_replace('/<tr[^>]*>/', '<tr>', $html); $html = preg_replace('/<td[^>]*>/', '<td>', $html); $html = str_replace(' ', ' ', $html); $p = '#<tr> <td>예정가격</td>( <td>[^<]*</td>){2} </tr>' . ' <tr> <tr> <td> (?<yega>\\d{1,3}(,\\d{3})*) 원 </td>( <td>[^<]*</td>){2} </tr>#'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $data['yega'] = str_replace(',', '', $m['yega']); } //참여업체 $succoms = []; $s_plus = []; $s_minus = []; $p = '#<tr>' . ' <td>(?<seq>\\d+)</td>' . ' <td>(?<officenm>[^<]*)</td>' . ' <td>(?<pct>[^<]*)</td>' . ' <td>(?<success>[^<]*)</td>' . ' <td>(?<etc>[^<]*)</td>' . ' </tr>#'; $p = str_replace(' ', '\\s*', $p); if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $s = ['seq' => $m['seq'], 'officenm' => trim($m['officenm']), 'pct' => substr(str_replace('%', '', trim($m['pct'])), 0, 8), 'success' => str_replace(',', '', trim(str_replace('원', '', $m['success']))), 'etc' => trim($m['etc'])]; $succoms[$s['seq']] = $s; switch ($s['etc']) { case '적격심사 1 순위': case '낙찰예정자': case '우선협상대상자': $data['success1'] = $s['success']; $data['officenm1'] = $s['oficenm']; break; } if (isset($data['success1'])) { $s_plus[] = $s['seq']; } else { $s_minus[] = $s['seq']; } } } //최저가 if (empty($s_plus)) { $i = 1; foreach ($s_minus as $seq) { $succoms[$seq]['rank'] = $i; if ($i == 1) { $data['success1'] = $succoms[$seq]['success']; $data['officenm1'] = $succoms[$seq]['officenm1']; } $i++; } } else { $i = 1; foreach ($s_plus as $seq) { $succoms[$seq]['rank'] = $i; $i++; } $i = count($s_minus) * -1; foreach ($s_minus as $seq) { $succoms[$seq]['rank'] = $i; $i++; } } $data['succoms'] = $succoms; $data['innum'] = count($succoms); $event = new \kwater\WatchEvent(); $event->row = $data; $this->trigger(\kwater\WatchEvent::EVENT_ROW, $event); } catch (\Exception $e) { echo Console::renderColoredString("%r{$e}%n"), PHP_EOL; \Yii::error($e, 'kwater'); } $this->module->db->close(); echo sprintf("[%s] Peak memory usage: %sMb\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024); sleep(1); }
public function stdout2($string) { $this->stdout(Console::renderColoredString($string)); }
public function getGlobalOptionsHelp() { return Console::renderColoredString(<<<HEREDOC GLOBAL OPTIONS (for all methods): %r--responseFormat%n Possible values: %ypretty%n - format response in human readable representation. %yjson%n - raw JSON, as received from the server. Default: %ypretty%n %r--apiEndpoint%n %r--apiKey%n %r--userAgent%n %r--sslVerifyPeer%n HEREDOC , $this->color); }
public function onRow($event) { $row = $event->row; $out[] = "[KWATER] [{$row['bidtype']}] %g{$row['notinum']}%n {$row['constnm']} ({$row['contract']},{$row['status']})"; $bidkey = BidKey::find()->where(['whereis' => \kwater\Module::WHEREIS, 'notinum' => $row['notinum']])->orderBy('bidid desc')->limit(1)->one(); if ($bidkey === null) { if (!ArrayHelper::isIn($row['status'], ['입찰완료', '적격신청', '결과발표']) and !ArrayHelper::isIn($row['contract'], ['지명경쟁', '수의계약(시담)'])) { $out[] = "%rNEW%n"; $this->gman_client->doBackground('kwater_work_bid', Json::encode($row)); $sleep = 1; } } else { $out[] = "({$bidkey->bidproc})"; if ($bidkey->bidproc === 'B' and $bidkey->state === 'Y') { $bidcheck = BidModifyCheck::findOne($bidkey->bidid); if ($bidcheck === null) { $out[] = "%yCHECK%n"; $this->gman_client->doBackground('kwater_work_bid', Json::encode($row)); } else { $diff = time() - $bidcheck->check_at; if ($diff >= 60 * 60 * 1) { $out[] = "%yCHECK%n"; $this->gman_client->doBackground('kwater_work_bid', Json::encode($row)); $bidcheck->check_at = time(); $bidcheck->save(); $sleep = 1; } } } } $this->stdout(Console::renderColoredString(join(' ', $out)) . PHP_EOL); if (isset($sleep)) { sleep(3); } }
public function onSucPdb2Row($event) { $row = $event->row; $out[] = Console::renderColoredString(" %c{$row['constno']}%n %g{$row['degree']}%n {$row['constnm']} ({$row['bidproc']})"); $bidkey = BidKey::findOne(['whereis' => '10', 'notinum' => $row['hidAnmtNumb'] . '-' . $row['degree'], 'notinum_ex' => $row['constno'], 'state' => 'Y']); if ($bidkey !== null) { if ($row['bidproc'] === '유찰') { if ($bidkey->bidproc === 'F' or $bidkey->bidproc === 'M') { $out[] = 'PASS'; } else { $out[] = Console::renderColoredString("%yNEW%n"); } } else { if ($bidkey->bidproc === 'S') { $out[] = 'PASS'; } else { $out[] = Console::renderColoredString("%yNEW%n"); } } } else { $out[] = Console::renderColoredString("%rMISS%n"); } $this->stdout(join(' ', $out) . PHP_EOL); }
/** * Returns full description from the docblock. * * @param \Reflector $reflection * @return string */ protected function parseDocCommentDetail($reflection) { $comment = strtr(trim(preg_replace('/^\\s*\\**( |\\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", ''); if (preg_match('/^\\s*@\\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { $comment = trim(substr($comment, 0, $matches[0][1])); } if ($comment !== '') { return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment))); } return ''; }
public function run() { $apiMethod = $this->id; /** @var $api Api */ $api = Module::getInstance()->api; $requestModel = $this->model; // Walk through options and assign them into corresponding objects. $methodAttributes = $requestModel->getExtraAttributes(); $responseFormat = 'pretty'; foreach ($this->controller->getOptionValues($this->id) as $name => $value) { if (in_array($name, $methodAttributes)) { $requestModel->{$name} = $value; } elseif (!empty($value) && in_array($name, $this->controller->allowedApiOptions)) { $apiSetter = 'set' . $name; $api->{$apiSetter}($value); } elseif ('responseFormat' === $name) { if ('pretty' === $value || 'json' === $value) { $responseFormat = $value; } else { $this->controller->stderr(Console::renderColoredString("Error: Invalid value %y{$value}%n for %r--responseFormat%n.\nValid values are: %ypretty%n and %yjson%n\n", $this->controller->color)); return Controller::EXIT_CODE_ERROR; } } } if (null === $api->getApiEndpoint()) { $this->controller->stderr(Console::renderColoredString("Error: %r--apiEndpoint%n was not specified.\n\n"), $this->controller->color); return Controller::EXIT_CODE_ERROR; } if (null === $api->getApiKey()) { $this->controller->stderr(Console::renderColoredString("Error: %r--apiKey%n was not specified.\n\n"), $this->controller->color); return Controller::EXIT_CODE_ERROR; } $requestModel->r = $apiMethod; $requestModel->k = $api->apiKey; // Check whether all the parameter are OK for doing request if (!$requestModel->validate()) { $errors = $requestModel->getErrors(); $this->controller->stderr("Validation errors:\n"); foreach ($errors as $attribute => $attrErrors) { $this->controller->stderr(Console::renderColoredString(" %r--{$attribute}%n\n"), $this->controller->color); foreach ($attrErrors as $errMsg) { $this->controller->stderr(" {$errMsg}\n"); } $this->controller->stderr("\n"); } return Controller::EXIT_CODE_ERROR; } // If user selected RAW(JSON) response format if ('pretty' !== $responseFormat) { try { $responseText = $api->requestRawFromModel($requestModel); } catch (\Exception $e) { $responseText = 'Error: ' . $e->getMessage(); } $this->controller->stdout($responseText . "\n"); return Controller::EXIT_CODE_NORMAL; } $success = false; $time = null; try { $response = $api->requestFromModel($requestModel); if ($response->isSuccessful()) { $success = true; $message = $api->formatResponseValues($apiMethod, $response->getValues()); $time = $response->getTime(); } else { $message = $response->getErrorMessage(); } } catch (\Exception $e) { $message = 'Error: ' . $e->getMessage(); } $this->controller->stdout(($success ? 'Request was successful!' : 'Request failed!') . "\n\n"); $this->controller->stdout("{$message}\n"); $this->controller->stdout(isset($time) ? "It took: {$time} s.\n" : ''); return Controller::EXIT_CODE_NORMAL; }
public static function print_bid(BidKey $bidkey) { $out = []; switch ($bidkey->bidtype) { case 'con': $out[] = Console::renderColoredString('%y[공사]%n'); break; case 'ser': $out[] = Console::renderColoredString('%g[용역]%n'); break; case 'pur': $out[] = Console::renderColoredString('%b[구매]%n'); break; } $out[] = $bidkey->constnm; $out[] = "({$bidkey->notinum})"; echo join(' ', $out), PHP_EOL; }
public function work($job) { \Yii::info('[' . __METHOD__ . '] $workload' . PHP_EOL . VarDumper::dumpAsString($job->workload()), 'kwater'); $workload = Json::decode($job->workload()); $http = new \kwater\Http(); $data = []; try { if (empty($workload['notinum'])) { throw new \Exception('notinum is empty'); } if (empty($workload['bidtype'])) { throw new \Exception('bidtype is empty'); } $data['org_i'] = '한국수자원공사'; if ($workload['realorg']) { $data['org_i'] .= ' ' . str_replace('관리처', '지역본부', $workload['realorg']); } $data['notinum'] = $workload['notinum']; switch ($workload['bidtype']) { case '공사': $data['bidtype'] = 'con'; $data['bidview'] = 'con'; break; case '용역': $data['bidtype'] = 'ser'; $data['bidview'] = 'ser'; break; default: $data['bidtype'] = 'pur'; $data['bidview'] = 'pur'; } $html = $http->request('GET', static::URL, ['query' => ['BidNo' => $workload['notinum']]]); $thml = strip_tags($html, '<tr><td><a>'); $html = preg_replace('/<tr[^>]*>/', '<tr>', $html); $html = preg_replace('/<td[^>]*>/', '<td>', $html); $html = str_replace(' ', '', $html); $data['attchd_lnk'] = $this->attchd_lnk($html); $html = strip_tags($html, '<tr><td>'); //echo $html,PHP_EOL; $data['constnm'] = $this->constnm($html); $contract = $this->contract($html); if ($contract == '소액전자') { $data['contract'] = '40'; } $succls = $this->succls($html); switch ($succls) { case '적격심사': $data['succls'] = '01'; break; case '최저가': $data['succls'] = '02'; break; default: $data['succls'] = '00'; } $data['registdt'] = $this->registdt($html); $data['multispare'] = $this->multispare($html); $data['constdt'] = $this->constdt($html); //$data['bidcomment']=$this->bidcomment($thml); $data['charger'] = $this->charger($html); $data = ArrayHelper::merge($data, $this->closedt($html)); $convention = $this->convention($html); $data['convention'] = '0'; if (ArrayHelper::isIn($convention['convention1'], ['가능', '공동'])) { $data['convention'] = '2'; } if (ArrayHelper::isIn($convention['convention2'], ['가능', '공동'])) { $data['convention'] = '2'; } $data['orign_lnk'] = 'http://ebid.kwater.or.kr/fz?bidno=' . $workload['notinum']; $data['noticedt'] = $this->noticedt($html); $data['basic'] = $this->basic($html); $data['pqdt'] = $this->pqdt($html); //현장설명회 if ($data['pqdt']) { $data['bidcomment'] = 'PQ심사신청서 신청기한 : ' . $data['pqdt'] . '<hr>'; $data['succls'] = '05'; } $event = new \kwater\WatchEvent(); $event->row = $data; $this->trigger(\kwater\WatchEvent::EVENT_ROW, $event); } catch (\Exception $e) { echo Console::renderColoredString("%r{$e}%n"), PHP_EOL; \Yii::error($e, 'kwater'); } $this->module->db->close(); echo sprintf("[%s] Peak memory usage: %sMb\n", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024); sleep(1); }
public static function work($job) { $workload = $job->workload(); echo $workload, PHP_EOL; $workload = Json::decode($workload); $module = \ebidlh\Module::getInstance(); $pub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $sub = \Yii::createObject(['class' => \ebidlh\Redis::className(), 'hostname' => $module->redis_server]); $channel = \Yii::$app->security->generateRandomString(); try { if (ArrayHelper::keyExists('bidproc', $workload)) { switch ($workload['bidproc']) { case '취소공고': $bidproc = 'C'; break; //case '연기공고': $bidproc='L'; break; //case '연기공고': $bidproc='L'; break; default: $bidproc = 'B'; } $bidkey = BidKey::findOne(['whereis' => '05', 'notinum' => $workload['notinum'] . '-' . $workload['subno'], 'bidproc' => $bidproc]); if ($bidkey !== null) { throw new PassException(); } } switch ($workload['bidtype']) { case '공사': $url = self::URL_CON; break; case '용역': $url = self::URL_SER; break; case '물품': $url = self::URL_PUR; break; case '지급자재': $url = self::URL_PUR2; break; default: throw new \Exception('invalid bidtype'); } $pub->publish('ebidlh-bid', ['cmd' => 'open-work', 'channel' => $channel]); $sub->subscribe([$channel], function ($redis, $chan, $msg) use($pub, $channel, $workload, $url) { if ($msg === 'ready') { $pub->publish($channel . '-client', ['url' => $url, 'post' => http_build_query(['bidNum' => $workload['notinum'], 'bidDegree' => $workload['subno'], 'cstrtnJobGbCd' => $workload['param3'], 'emrgncyOrder' => $workload['param4']])]); return; } $html = iconv('euckr', 'utf-8//IGNORE', $msg); $html = strip_tags($html, '<th><tr><td><a>'); $html = preg_replace('/<th[^>]*>/i', '<th>', $html); if (strpos($html, '한국정보인증(주)의 보안S/W를 설치중입니다') > 0) { return; } $html = preg_replace('/<tr[^>]*>/i', '<tr>', $html); $html = preg_replace('/<td[^>]*>/i', '<td>', $html); $data = []; $files = []; $p = '#<tr>' . ' <td>(?<ftype>[^<]*)</td>' . ' <td><a.*fn_dds_open\\(\'\\d+\',\'(?<rname>[^\']*)\',[^>]*>(?<fname>[^<]*)</a></td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match_all($p, $html, $matches, PREG_SET_ORDER)) { foreach ($matches as $m) { $fname = trim($m['fname']); $rname = trim($m['rname']); $files[] = "{$fname}#('bidinfo','{$fname}','{$rname}')"; } } $data['attchd_lnk'] = implode('|', $files); $html = strip_tags($html, '<th><tr><td>'); //공고종류 $p = '#공고종류</th> <td>(?<bidproc>[^<]*)</td>#i'; $data['bidproc'] = self::match($p, $html, 'bidproc'); //공고명 $p = '#입찰공고건명</th> <td>(?<constnm>.+)본 공고는 지문인식#i'; $data['constnm'] = self::match($p, $html, 'constnm'); //공고부서 $p = '#공고부서</th> <td>(?<org>[^<]*)</td>#i'; $data['org'] = self::match($p, $html, 'org'); //추정가격 $p = '#추정가격</th> <td>(?<presum>\\d+(,\\d{1,3})*)원#i'; $data['presum'] = self::match($p, $html, 'presum'); //기초금액 $p = '#기초금액</th> <td>(?<basic>\\d+(,\\d{1,3})*)원#i'; $data['basic'] = self::match($p, $html, 'basic'); //계약방법 $p = '#계약방법</th> <td>(?<contract>[^<]*)</td>#i'; $data['contract'] = self::match($p, $html, 'contract'); //입찰방식 $p = '#입찰방식</th> <td>(?<bidcls>[^<]*)</td>#i'; $data['bidcls'] = self::match($p, $html, 'bidcls'); //낙찰자선정방법 $p = '#낙찰자선정방법</th> <td>(?<succls>[^<]*)</td>#i'; $data['succls'] = self::match($p, $html, 'succls'); //공동수급협정서접수마감일시 $p = '#공동수급협정서접수마감일시</th> <td>(?<hyupenddt>[^<]*)</td>#i'; $data['hyupenddt'] = self::match($p, $html, 'hyupenddt'); //입찰서접수개시일시 $p = '#입찰서접수개시일시</th> <td>(?<opendt>[^<]*)</td>#i'; $data['opendt'] = self::match($p, $html, 'opendt'); //입찰서접수마감일시 $p = '#입찰서접수마감일시</th> <td>(?<closedt>[^<]*)</td>#i'; $data['closedt'] = self::match($p, $html, 'closedt'); //입찰참가신청서접수마감일시 $p = '#입찰참가신청서접수마감일시</th> <td>(?<registdt>[^<]*)</td>#i'; $data['registdt'] = self::match($p, $html, 'registdt'); //개찰일시 $p = '#개찰일시</th> <td>(?<constdt>[^<]*)</td>#i'; $data['constdt'] = self::match($p, $html, 'constdt'); //현장설명일시 $p = '#현장설명일시</th> <td>(?<explaindt>[^<]*)</td>#i'; $data['explaindt'] = self::match($p, $html, 'explaindt'); //공고변경사유 $p = '#공고변경사유</th> <td>(?<bidcomment_mod>[^<]*)</td>#i'; $data['bidcomment_bid'] = self::match($p, $html, 'bidcomment_mod'); //투찰제한 $p = '#투찰제한정보 <tr>' . ' <th>참가지역1</th> <td>(?<local1>[^<]*)</td>' . ' <th>참가지역2</th> <td>(?<local2>[^<]*)</td>' . ' <th>참가지역3</th> <td>(?<local3>[^<]*)</td>' . ' <th>참가지역4</th> <td>(?<local4>[^<]*)</td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $data['local1'] = trim($m['local1']); $data['local2'] = trim($m['local2']); $data['local3'] = trim($m['local3']); $data['local4'] = trim($m['local4']); } //지역의무공동업체제한 $p = '#지역의무공동업체제한 <tr>' . ' <th>참가지역1</th> <td>(?<local1>[^<]*)</td>' . ' <th>참가지역2</th> <td>(?<local2>[^<]*)</td>' . ' <th>참가지역3</th> <td>(?<local3>[^<]*)</td>' . ' <th>참가지역4</th> <td>(?<local4>[^<]*)</td>' . ' </tr>#i'; $p = str_replace(' ', '\\s*', $p); if (preg_match($p, $html, $m)) { $data['contloc1'] = trim($m['local1']); $data['contloc2'] = trim($m['local2']); $data['contloc3'] = trim($m['local3']); $data['contloc4'] = trim($m['local4']); } print_r($data); if (strpos($data['bidproc'], '취소공고') !== false) { $bidproc = 'C'; } else { $bidproc = 'B'; } $bidkey = BidKey::findOne(['whereis' => '05', 'notinum' => $workload['notinum'] . '-' . $workload['subno'], 'bidproc' => $bidproc]); if ($bidkey === null) { if (strpos($data['bidproc'], '취소공고') !== false) { $bidproc = 'C'; } } $pub->publish($channel . '-client', ['url' => 'close', 'post' => '']); $redis->close(); return; }); } catch (PassException $e) { } catch (\RedisException $e) { $sub->close(); echo Console::renderColoredString('%r' . $e->getMessage() . '%n'), PHP_EOL; $gman_client = new \GearmanClient(); $gman_client->addServers($module->gman_server); $gman_client->doBackground('ebidlh_bid_work', $job->workload()); } catch (\Exception $e) { $sub->close(); echo Console::renderColoredString("%r{$e}%n"), PHP_EOL; \Yii::error($job->workload() . "\n" . $e, 'ebidlh'); } $module->db->close(); echo Console::renderColoredString("%c" . sprintf("[%s] Peak memory usage: %sMb", date('Y-m-d H:i:s'), memory_get_peak_usage(true) / 1024 / 1024) . "%n"), PHP_EOL; }
/** * Displays the detailed information of a command action. * @param Controller $controller the controller instance * @param string $actionID action ID * @throws Exception if the action does not exist */ protected function getActionHelp($controller, $actionID) { $action = $controller->createAction($actionID); if ($action === null) { throw new Exception(Yii::t('yii', 'No help for unknown sub-command "{command}".', ['command' => rtrim($controller->getUniqueId() . '/' . $actionID, '/')])); } if ($action instanceof InlineAction) { $method = new \ReflectionMethod($controller, $action->actionMethod); } else { $method = new \ReflectionMethod($action, 'run'); } $tags = $this->parseComment($method->getDocComment()); $options = $this->getOptionHelps($controller); if ($tags['description'] !== '') { $this->stdout("\nDESCRIPTION\n", Console::BOLD); echo "\n" . Console::renderColoredString($tags['description']) . "\n\n"; } $this->stdout("\nUSAGE\n\n", Console::BOLD); $scriptName = $this->getScriptName(); if ($action->id === $controller->defaultAction) { echo $scriptName . ' ' . $this->ansiFormat($controller->getUniqueId(), Console::FG_YELLOW); } else { echo $scriptName . ' ' . $this->ansiFormat($action->getUniqueId(), Console::FG_YELLOW); } list($required, $optional) = $this->getArgHelps($method, isset($tags['param']) ? $tags['param'] : []); foreach ($required as $arg => $description) { $this->stdout(' <' . $arg . '>', Console::FG_CYAN); } foreach ($optional as $arg => $description) { $this->stdout(' [' . $arg . ']', Console::FG_CYAN); } if (!empty($options)) { $this->stdout(' [...options...]', Console::FG_RED); } echo "\n\n"; if (!empty($required) || !empty($optional)) { echo implode("\n\n", array_merge($required, $optional)) . "\n\n"; } $options = $this->getOptionHelps($controller); if (!empty($options)) { $this->stdout("\nOPTIONS\n\n", Console::BOLD); echo implode("\n\n", $options) . "\n\n"; } }
/** * 개찰 처리 */ private function suc_s($workload) { $bidkey = BidKey::findOne($workload['bidid']); if ($bidkey === null) { return; } $out[] = "[i2] [{$bidkey->bidid}] %g{$bidkey->notinum}%n {$bidkey->constnm}"; $bidres = BidRes::findOne($bidkey->bidid); if ($bidres === null) { $bidres = new BidRes(['bidid' => $bidkey->bidid]); } $bidres->yega = $workload['yega']; $bidres->innum = $workload['innum']; $bidres->selms = $workload['selms']; $bidres->multispare = $workload['multispare']; $bidres->officenm1 = $workload['officenm1']; $bidres->prenm1 = $workload['prenm1']; $bidres->officeno1 = $workload['officeno1']; $bidres->success1 = $workload['success1']; $bidres->reswdt = date('Y-m-d H:i:s'); $bidres->save(); $out[] = "%y개찰%n"; $this->stdout(Console::renderColoredString(join(' ', $out)) . "\n"); BidSuccom::deleteAll(['bidid' => $bidkey->bidid]); if (is_array($workload['succoms'])) { $total = $bidres->innum; $cur = 1; Console::startProgress(0, $total); foreach ($workload['succoms'] as $r) { $bidsuccom = new BidSuccom(['bidid' => $bidkey->bidid, 'seq' => $r['seq'], 'officeno' => $r['officeno'], 'officenm' => $r['officenm'], 'prenm' => $r['prenm'], 'success' => $r['success'], 'pct' => $r['pct'], 'rank' => $r['rank'], 'selms' => $r['selms'], 'etc' => $r['etc']]); $bidsuccom->save(); Console::updateProgress($cur++, $total); } Console::endProgress(); } if (($bidkey->opt & pow(2, 5)) == 0) { $bidkey->opt += pow(2, 5); } $bidkey->bidproc = 'S'; $bidkey->resdt = date('Y-m-d H:i:s'); $bidkey->editdt = date('Y-m-d H:i:s'); $bidkey->save(); }
public function onSessionLeave($args, $kwArgs, $options) { // VarDumper::dump([$args, $kwArgs, $options]); try { $sessionId = (int) $args[0]->session; // $this->removeSessionFromList($sessionId); echo "Session {$sessionId} leaved\n"; } catch (\Exception $e) { echo Console::renderColoredString('%rError: %w' . (string) $e . '%n') . PHP_EOL; } }
protected static function msg($msg) { if (\Yii::$app instanceof ConsoleApplication) { Console::output(Console::renderColoredString($msg)); } }