use yii\db\Exception;
use yii\helpers\Json;
use yii\web\Controller;
+use yii_app\records\ApiCron;
use yii_app\records\ApiCronBuh;
+use yii_app\records\ApiLogs;
use yii_app\records\Firms;
class CronController extends Controller
{
public function action1c()
{
- return $this->render('1c');
+ $items = [
+ "stores" => ["name" => "Магазины"],
+ "nomenclature" => ["name" => "Номенклатура"],
+ "sellers" => ["name" => "Продавцы"],
+ "balances" => ["name" => "Складские остатки"],
+ "counteragents" => ["name" => "Контрагенты"],
+ "employee" => ["name" => "Физ лица в 1с - продавцы"],
+ "prices" => ["name" => "Типы цен", "array" => ["type_price" => "Розничная цена"]],
+ "checks_dell" => ["name" => "Удаление чеков"],
+ "checks" => [
+ "name" => "Чеки-продажи",
+ "array" => [
+ "start_time" => date("Y-m-d 00:00:00", time() - 2 * 86400),
+ "end_time" => date("Y-m-d 00:00:00", time())
+ ]
+ ],
+ "write_offs" => [
+ "name" => "Списания",
+ "array" => [
+ "start_time" => date("Y-m-d 00:00:00", time() - 2 * 86400),
+ "end_time" => date("Y-m-d 00:00:00", time())
+ ]
+ ],
+ "self_cost" => [
+ "name" => "Себестоимость",
+ "array" => [
+ "start_time" => date("Y-m-d 00:00:00", time() - 2 * 86400),
+ "end_time" => date("Y-m-d 00:00:00", time())
+ ]
+ ],
+ "incomings" => [
+ "name" => "Документы",
+ "array" => [
+ "start_time" => date("Y-m-d 00:00:00", time() - 2 * 86400),
+ "end_time" => date("Y-m-d 00:00:00", time())
+ ]
+ ],
+ "payment_types" => ["name" => "Виды оплат"]
+ ];
+
+ // Обработка формы
+ if (\Yii::$app->request->isPost) {
+ $m = [];
+ $request_id = (string)time(); // Преобразуем в строку
+ $m["request_id"] = $request_id;
+
+ foreach ($_POST['in'] ?? [] as $n => $array5) {
+ $m3 = [];
+ foreach ($_POST['in_in'][$n] ?? [] as $t => $ar) {
+ $m[$n][$t] = "" . $ar;
+ }
+ if (empty($m[$n])) {
+ $m[$n] = true;
+ }
+ }
+
+ $json2 = json_encode($m, JSON_UNESCAPED_UNICODE);
+
+ if (!empty($_POST["in"]) && $json2 != "[]") {
+ $model = new ApiCron();
+ $model->date = date('Y-m-d H:i:s');
+ $model->date_up = date('Y-m-d H:i:s');
+ $model->status = 0;
+ $model->json_post = $json2;
+ $model->request_id = $request_id;
+
+ if (!$model->validate()) {
+ var_dump($model->getErrors());
+ die();
+ } else {
+ // Если валидация прошла, сохраняем
+ $model->save();
+ }
+ }
+
+ return $this->redirect(\Yii::$app->request->referrer);
+ }
+
+ $status_arr = [0 => "ожидает выполнения", 1 => "выполнено"];
+
+ $tasksDataProvider = new ActiveDataProvider([
+ 'query' => ApiCron::find()
+ ->orderBy(['date' => SORT_DESC])
+ ->limit(30),
+ 'pagination' => false
+ ]);
+
+ $logsDataProvider = new ActiveDataProvider([
+ 'query' => ApiLogs::find()
+ ->orderBy(['date' => SORT_DESC])
+ ->limit(100),
+ 'pagination' => false
+ ]);
+
+ return $this->render('1c', [
+ 'items' => $items,
+ 'status_arr' => $status_arr,
+ 'tasksDataProvider' => $tasksDataProvider,
+ 'logsDataProvider' => $logsDataProvider,
+ ]);
}
/**
$request = \Yii::$app->request->post();
if ($request && !empty($request['start_date']) && !empty($request['end_date'])) {
- foreach (Firms::getInn() as $key => $firm ) {
+ foreach (Firms::getInn() as $key => $firm) {
$model = new ApiCronBuh();
$model->date = date('Y-m-d H:i:s');
- $model->request_id = strval(strtotime($model->date). '_' .$key);
+ $model->request_id = strval(strtotime($model->date) . '_' . $key);
$model->json_post = Json::encode([
'request_id' => $model->request_id,
'cost_items' => [
<?php
-include_once(dirname(__DIR__, 2) . "/startup.php");
-include_once(dirname(__DIR__, 2) . "/inc/db.php");
-include_once(dirname(__DIR__, 2) . "/inc/base_new.php");
-include_once(dirname(__DIR__, 2) . "/inc/design_new.php");
-include_once(dirname(__DIR__, 2) . "/inc/uni.php");
-
-//include_once("templates/top.php");
-
-
-//$data=$db::getRows("SELECT id, name FROM city_store WHERE 1");
-// foreach ($data as $row) $store_arr[$row["id"]]=$row["name"];
-
-
-echo'<h1>Создание задания для 1с</h1>';
-
-$items=array(
- "stores"=>array("name"=>"Магазины"),
- "nomenclature"=>array("name"=>"Номенклатура"),
- "sellers"=>array("name"=>"Продавцы"),
- "balances"=>array("name"=>"Складские остатки"),
- "counteragents"=>array("name"=>"Контрагенты"),
- "employee"=>array("name"=>"Физ лица в 1с - продавцы"),
- "prices"=>array("name"=>"Типы цен", "array"=>array("type_price" =>"Розничная цена")),
- "checks_dell"=>array("name"=>"Удаление чеков"),
- "checks"=>array("name"=>"Чеки-продажи", "array"=>array("start_time" =>date("Y-m-d 00:00:00",time()-2*86400),"end_time"=>date("Y-m-d 00:00:00",time()))),
- "write_offs"=>array("name"=>"Списания", "array"=>array("start_time" =>date("Y-m-d 00:00:00",time()-2*86400),"end_time"=>date("Y-m-d 00:00:00",time()))),
- "self_cost"=>array("name"=>"Себестоимость", "array"=>array("start_time" =>date("Y-m-d 00:00:00",time()-2*86400),"end_time"=>date("Y-m-d 00:00:00",time()))),
- "incomings"=>array("name"=>"Документы", "array"=>array("start_time" =>date("Y-m-d 00:00:00",time()-2*86400),"end_time"=>date("Y-m-d 00:00:00",time()))),
- "payment_types"=>array("name"=>"Виды оплат")
-
-
-//"prices"=>array("name"=>"Цены"),
-);
-
-echo'<form action="" method=post>';
-echo '<input type="hidden" name="_csrf" value="' . Yii::$app->request->getCsrfToken() . '" />';
-foreach($items as $name => $ar) {
- echo'<br><input type=checkbox name=in['.$name.']> '.$ar["name"].'';
- echo"<table>";
- foreach($ar["array"] ?? [] as $tip => $val) {
-// if($name=="checks") $type="date"; else $type="text";
- echo'<td> '.$tip.'</td><td> <input type="text" ';
- if(isset($type) && $type=="date") echo' style="width:220px;"';
-
- echo' class="form-control" name=in_in['.$name.']['.$tip.'] value="'.$val.'"></td>';
- }
- echo '</table>';
-}
-echo'<br><button name=save value=1 type=submit class="btn btn-success">Сохранить</button></form>';
-echo'<p><button class="btn"><a href="/cron/1c">Обновить</a></button></p>';
-$m=array();
-$request_id=time();
-$m["request_id"]=$request_id;
-foreach($_POST["in"] ?? [] as $n => $array5) {
- $m3=array();
- foreach($_POST["in_in"][$n] ?? [] as $t => $ar) {
- $m[$n][$t]="".$ar;
- }
- if(empty($m[$n])) $m[$n]=true;
-}
-
-$json2=json_encode($m,JSON_UNESCAPED_UNICODE);
-echo $json2;
-
-if(!empty($_POST["in"]) and $json2!="[]") {
-
-
-
- $db::sql("INSERT INTO api_cron (date, date_up, status,json_post,request_id) VALUES (NOW(), NOW(), 0, ?, ?)",[$json2,$request_id]);
-
-}
-
-$status_arr=[0=>"ожидает выполнения",1=>"выполнено"];
-$data = $db::getRows("SELECT * FROM api_cron WHERE 1=1 order by date DESC LIMIT 30 ");
-echo"<h3>Здания для 1с</h3><table class=\"table table-hover table-sm\"><tbody>";
-foreach($data as $row) {
- echo"<tr"; if($row["status"]==0) echo" class=\"bg-warning\" ";
- echo"><td><a href=\"https://api2.erp.erp-flowers.ru/json/upload_request_id_".$row["request_id"].".json\" target=new>".$row["request_id"]."</a></td><td>".$row["date"]."</td><td>".$row["json_post"]."</td><td>".$status_arr[$row["status"]]."";
-
- if($row["status"]==1 and $row["date_up"]!="0000-00-00 00:00:00") echo $row["date_up"];
-
- echo"</td></tr>";
-
-}
-echo"</tbody></table>";
-
-
-
-
-
-
-
-$data = $db::getRows("SELECT * FROM api_logs WHERE request_id!='' order by date DESC LIMIT 100 ");
-echo"<h3>Логи от 1с</h3>
-
-<table class=\"table table-hover table-sm\"><tbody>";
-foreach($data as $row) {
- echo"<tr"; if($row["status"]==0) echo" class=\"bg-warning\" ";
- echo"><td><a href=\"https://api2.erp.erp-flowers.ru/json/upload_request_id_".$row["request_id"].".json\" target=new>
-".$row["request_id"]." </a></td><td>".$row["date"]."</td><td>".$row["url"]." ".$row["content"]."</td></tr>";
-
-}
-echo"</tbody></table>";
-
-
-echo'
-<h4>запрос на каждые 12 часов</h4>
-
-<pre>{"request_id": "'.$request_id.'", "nomenclature":true,"balances":true,"prices":{"type_price":"Розничная цена"},"checks":{"start_time":"'.date("Y-m-d",time()-86400).' 00:00:00","end_time":"'.date("Y-m-d",time()).' 23:59:59"},"write_offs":{"start_time":"'.date("Y-m-d",time()-86400*7).' 00:00:00","end_time":"'.date("Y-m-d",time()).' 23:59:59"}}</pre>';
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+use kartik\grid\GridView;
+
+$this->title = 'Создание задания для 1с';
+?>
+
+
+<h1 class="text-center mb-4">Создание задания для 1с</h1>
+
+<?php $form = ActiveForm::begin(['options' => ['class' => 'form-horizontal']]); ?>
+
+<?= Html::hiddenInput('_csrf', Yii::$app->request->getCsrfToken()) ?>
+
+<div class="row">
+ <?php foreach ($items as $name => $ar): ?>
+ <div class="col-md-4 mb-3">
+ <div class="card" style="padding: 10px;">
+ <div class="card-body">
+ <div class="form-check">
+ <?= Html::checkbox("in[{$name}]", false, ['class' => 'form-check-input']) ?>
+ <label class="form-check-label"><?= Html::encode($ar['name']) ?></label>
+ </div>
+
+ <table class="table table-sm mt-3" style="table-layout: fixed;">
+ <tbody>
+ <?php foreach ($ar['array'] ?? [] as $tip => $val): ?>
+ <tr>
+ <td style="width: 120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
+ <strong><?= Html::encode($tip) ?></strong>
+ </td>
+ <td>
+ <?= Html::input('text', "in_in[{$name}][{$tip}]", $val, [
+ 'class' => 'form-control',
+ 'style' => 'width: 100%; max-width: 220px;',
+ ]) ?>
+ </td>
+ </tr>
+ <?php endforeach; ?>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ <?php endforeach; ?>
+</div>
+
+<div class="form-group text-center mt-4">
+ <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success btn-lg']) ?>
+</div>
+
+<?php ActiveForm::end(); ?>
+
+<h3>Задания для 1с</h3>
+<?php
+echo GridView::widget([
+ 'dataProvider' => $tasksDataProvider,
+ 'columns' => [
+ [
+ 'attribute' => 'request_id',
+ 'label' => 'ID запроса',
+ 'format' => 'raw',
+ 'value' => function ($task) {
+ return Html::a($task->request_id, "https://api2." . (YII_ENV_PROD ? 'erp.erp-flowers.ru' : 'dev.erp-flowers.ru')
+ . "/json/upload_request_id_{$task->request_id}", ['target' => '_blank']);
+ }
+ ],
+ [
+ 'attribute' => 'date',
+ 'label' => 'Дата',
+ ],
+ [
+ 'attribute' => 'json_post',
+ 'label' => 'JSON данные',
+ 'format' => 'raw',
+ 'value' => function ($task) {
+ if (empty($task->json_post)) {
+ return '';
+ }
+ $decodedJson = json_decode($task->json_post, true);
+ if ($decodedJson === null && json_last_error() !== JSON_ERROR_NONE) {
+ return 'Ошибка в JSON';
+ }
+ $jsonPretty = json_encode($decodedJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
+ return Html::tag('pre', $jsonPretty);
+ },
+ 'contentOptions' => ['style' => 'white-space: pre-wrap; word-wrap: break-word;']
+ ],
+ [
+ 'attribute' => 'status',
+ 'label' => 'Статус',
+ 'value' => function ($task) {
+ return Html::encode(\yii_app\records\ApiCron::getStatus()[$task->status]);
+ }
+ ],
+ [
+ 'attribute' => 'date_up',
+ 'label' => 'Дата обновления',
+ 'value' => function ($task) {
+ return $task->status == \yii_app\records\ApiCron::COMPLETE && $task->date_up != '0000-00-00 00:00:00' ? Html::encode($task->date_up) : '';
+ }
+ ],
+ ],
+ 'rowOptions' => function ($task) {
+ $class = '';
+ if ($task->status == \yii_app\records\ApiCron::AWAITING_COMPLETION) {
+ $class = 'bg-warning';
+ }
+ return ['class' => $class];
+ },
+ 'tableOptions' => ['class' => 'table table-hover table-sm'],
+ 'pager' => [],
+ 'layout' => '{items}',
+]);
+?>
+
+<h3>Логи от 1с</h3>
+<?php
+echo GridView::widget([
+ 'dataProvider' => $logsDataProvider,
+ 'columns' => [
+ [
+
+ 'format' => 'raw',
+ 'value' => function ($log) {
+ return Html::a($log->request_id, "https://api2.erp.erp-flowers.ru/json/upload_request_id_{$log->request_id}", ['target' => '_blank']);
+ }
+ ],
+ [
+ 'attribute' => 'date',
+ 'label' => 'Дата',
+ ],
+ [
+ 'attribute' => 'url',
+ 'label' => 'URL',
+ 'value' => function ($log) {
+ return Html::encode($log->url);
+ }
+ ],
+ [
+ 'attribute' => 'content',
+ 'label' => 'Контент',
+ 'format' => 'raw',
+ 'value' => function ($task) {
+ if (empty($task->content)) {
+ return '';
+ }
+ $decodedJson = json_decode($task->content, true);
+ if ($decodedJson === null && json_last_error() !== JSON_ERROR_NONE) {
+ return 'Ошибка в JSON';
+ }
+ $jsonPretty = json_encode($decodedJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
+ return Html::tag('pre', $jsonPretty);
+ },
+ 'contentOptions' => ['style' => 'white-space: pre-wrap; word-wrap: break-word;'] // Разрыв слов и переносы
+ ],
+
+ ],
+ 'tableOptions' => ['class' => 'table table-hover table-sm'],
+ 'pager' => [],
+ 'layout' => '{items}',
+]);
+?>
-//include_once dirname(__DIR__, 2) . '/templates/bottom_light.php';