];
}
- public static function getWeekRangeForDate($date = null)
- {
-
- $date = $date ?? strtotime(date('Y-m-d'));
-
+ public static function getWeekRange($date = null, $weekNumber = null, $month = null, $year = null) {
+ // Если дата передана, извлекаем из неё день, месяц и год
+ if ($date && !$weekNumber && !$month && !$year) {
+ $date = is_numeric($date) ? $date : strtotime($date); // Если дата передана как timestamp или строка
+ $day = date('d', $date);
+ $month = date('m', $date);
+ $year = date('Y', $date);
+ $weekNumber = intdiv($day - 1, 7) + 1;
+ }
+
+ // Если переданы номер недели, месяц и год, рассчитываем диапазон для указанной недели
+ if ($weekNumber && $month && $year) {
+ $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
+
+ // Определяем стартовый и конечный день недели
+ $startDay = ($weekNumber - 1) * 7 + 1;
+ $endDay = min($weekNumber * 7, $daysInMonth);
+
+ // Форматируем даты
+ $startDate = sprintf('%04d-%02d-%02d', $year, $month, $startDay);
+ $endDate = sprintf('%04d-%02d-%02d', $year, $month, $endDay);
+
+ return [
+ 'start_time' => $startDate,
+ 'end_time' => $endDate,
+ ];
+ }
+
+ // Если не переданы параметры, используем текущую дату
+ $date = strtotime(date('Y-m-d'));
$day = date('d', $date);
$month = date('m', $date);
$year = date('Y', $date);
-
$weekNumber = intdiv($day - 1, 7) + 1;
$startDay = ($weekNumber - 1) * 7 + 1;
$endDay = min($weekNumber * 7, date('t'));
- $startDate = \DateTime::createFromFormat('Y-m-d', "$year-$month-$startDay");
- $endDate = \DateTime::createFromFormat('Y-m-d', "$year-$month-$endDay");
+ $startDate = sprintf('%04d-%02d-%02d', $year, $month, $startDay);
+ $endDate = sprintf('%04d-%02d-%02d', $year, $month, $endDay);
return [
- 'start_time' => $startDate->format('Y-m-d'),
- 'end_time' => $endDate->format('Y-m-d'),
+ 'start_time' => $startDate,
+ 'end_time' => $endDate,
];
}
}
+
+
public static function getAdjustmentEditors() {
return array(
AdminGroup::GROUP_IT,
<?php
/**
- * @var $time integer
+ * @var $time integer|null
*/
use yii\db\Exception;
use yii_app\records\MotivationBuhValue;
use yii_app\records\MotivationCostsItem;
use yii_app\records\MotivationValue;
-use yii_app\records\MotivationValueGroup;
use yii_app\records\SchedulerTaskLog;
ini_set('max_execution_time', (string)(60 * 60 * 1)); // 1 час
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
+$time = $time ?? time(); // Использовать текущее время, если параметр не передан
+
echo "time2_" . $time . "_time2 ";
$taskNum = 33;
-$dateTask = date('Y-m-d H:i:s');
+$dateTask = date('Y-m-d H:i:s', $time);
$dateTaskStart = null;
$dateTaskStop = null;
$log = '';
$start = false;
$force = false;
-$minuetTimeInTask = date('i', $time);
+$minuteTimeInTask = date('i', $time);
$fullTimeInTask = date('Y-m-d H:i:s', $time);
try {
&& $enable
) {
- $dateTaskStart = date('Y-m-d H:i:s');
- $info = ' ================ test Task ' . $taskNum . ' start ================';
- echo $info;
- $log .= $info;
- $log .= $time;
-
- $schedulerTaskLog = new SchedulerTaskLog();
- $schedulerTaskLog->setTaskNum($taskNum)
- ->setName('Task ' . $taskNum)
- ->setDate($dateTask)
- ->setDateStart($dateTaskStart);
- $validate = $schedulerTaskLog->validate();
- if ($validate) {
- $schedulerTaskLog->save();
- }
-
-
-
-
+ // Проверяем, является ли текущий день одним из указанных
$currentDay = date('d', $time);
+ $specifiedDays = ['08', '15', '22', '29'];
+ if (
+ in_array($currentDay, $specifiedDays)
+ || $currentDay == '01'
+ || $force
+ ) {
+
+ $dateTaskStart = date('Y-m-d H:i:s', $time);
+ $info = ' ================ test Task ' . $taskNum . ' start ================';
+ echo $info;
+ $log .= $info;
+ $log .= $time;
+
+ $schedulerTaskLog = new SchedulerTaskLog();
+ $schedulerTaskLog->setTaskNum($taskNum)
+ ->setName('Task ' . $taskNum)
+ ->setDate($dateTask)
+ ->setDateStart($dateTaskStart);
+ $validate = $schedulerTaskLog->validate();
+ if ($validate) {
+ $schedulerTaskLog->save();
+ }
- if ($currentDay == '01') {
-
- $monthValue = intval(date('m', strtotime('-1 month', $time)));
- $yearValue = intval(date('Y', strtotime('-1 month', $time)));
- } else {
-
- $monthValue = intval(date('m', $time));
- $yearValue = intval(date('Y', $time));
- }
-
-
-
-
- $month = MotivationBuh::find()
- ->select('id')
- ->andWhere(['month' => $monthValue])
- ->andWhere(['year' => $yearValue])
- ->asArray()
- ->column();
-
-
- $motivationBuhValue = MotivationBuhValue::find()
- ->andWhere(['motivation_buh_id' => $month])
- ->groupBy('store_id, value_id, motivation_buh_id, motivation_group_id')
- ->select([
- new Expression(
- 'sum(value_float) as value_float,
- motivation_buh_id as motivation_buh_id,
- value_id as value_id,
- store_id as store_id,
- motivation_group_id as motivation_group_id'
- )
- ])
- ->all();
-
- foreach ($motivationBuhValue as $value) {
- $motivationBuh = MotivationBuh::findOne([$value->motivation_buh_id]);
-
- $motivation = Motivation::findOne([
- 'year' => $motivationBuh->year,
- 'month' => $motivationBuh->month,
- 'store_id' => $value->store_id,
- ]);
+ // Определяем месяц и год для обработки данных
+ if ($currentDay == '01') {
+ // 1-го числа обрабатываем данные за предыдущий месяц
+ $monthValue = intval(date('m', strtotime('-1 month', $time)));
+ $yearValue = intval(date('Y', strtotime('-1 month', $time)));
+ } else {
+ $monthValue = intval(date('m', $time));
+ $yearValue = intval(date('Y', $time));
+ }
- if (!$motivation) {
- $motivation = new Motivation();
- $motivation->setAttributes([
+ $month = MotivationBuh::find()
+ ->select('id')
+ ->andWhere(['month' => $monthValue])
+ ->andWhere(['year' => $yearValue])
+ ->asArray()
+ ->column();
+
+ $motivationBuhValue = MotivationBuhValue::find()
+ ->andWhere(['motivation_buh_id' => $month])
+ ->groupBy('store_id, value_id, motivation_buh_id, motivation_group_id')
+ ->select([
+ new Expression(
+ 'sum(value_float) as value_float,
+ motivation_buh_id as motivation_buh_id,
+ value_id as value_id,
+ store_id as store_id,
+ motivation_group_id as motivation_group_id'
+ )
+ ])
+ ->all();
+
+ $motivationVal = [];
+ foreach ($motivationBuhValue as $value) {
+ $motivationBuh = MotivationBuh::findOne([$value->motivation_buh_id]);
+
+ $motivation = Motivation::findOne([
'year' => $motivationBuh->year,
'month' => $motivationBuh->month,
- 'store_id' => $value->store_id
+ 'store_id' => $value->store_id,
+ ]);
+
+ if (!$motivation) {
+ $motivation = new Motivation();
+ $motivation->setAttributes([
+ 'year' => $motivationBuh->year,
+ 'month' => $motivationBuh->month,
+ 'store_id' => $value->store_id
+ ]);
+ $motivation->save();
+ }
+
+ $motivationValue = new MotivationValue();
+ $motivationValue->setAttributes([
+ 'motivation_id' => $motivation->id,
+ 'motivation_group_id' => $value->motivation_group_id,
+ 'value_id' => $value->value_id,
+ 'value_type' => MotivationCostsItem::DATA_TYPE_FLOAT,
+ 'value_float' => $value->value_float,
]);
- $motivation->save();
+ $motivationVal[] = $value->value_float;
+ $motivationValue->save();
}
- $motivationValue = new MotivationValue();
- $motivationValue->setAttributes([
- 'motivation_id' => $motivation->id,
- 'motivation_group_id' => $value->motivation_group_id,
- 'value_id' => $value->value_id,
- 'value_type' => MotivationCostsItem::DATA_TYPE_FLOAT,
- 'value_float' => $value->value_float,
- ]);
- $motivationValue->save();
+ $info = ' ================ test Task ' . $taskNum . ' stop ================';
+ echo $info;
+ $log .= $info;
+ $log .= ' date >= ' . strtotime("-1 week", $time);
+ $dateTaskStop = date('Y-m-d H:i:s', $time);
+ } else {
+ $info = ' Task ' . $taskNum . ' skip ';
+ echo $info;
+ $log .= $info;
}
-
- $info = ' ================ test Task ' . $taskNum . ' stop ================';
- echo $info;
- $log .= $info;
- $log .= ' date >= ' . strtotime("-1 week", time());
- $dateTaskStop = date('Y-m-d H:i:s');
} else {
$info = ' Task ' . $taskNum . ' skip ';
echo $info;
<?php
+
/**
- * @var $time integer
+ * @var $time integer|null
*/
use yii\helpers\Json;
-use yii_app\records\SchedulerTaskLog;
+use yii_app\records\Admin;
+use yii_app\records\AdminGroup;
+use yii_app\records\ApiCronBuh;
use yii_app\records\Firms;
use yii_app\records\Motivation;
-use yii_app\records\ApiCronBuh;
+use yii_app\records\SchedulerTaskLog;
ini_set('max_execution_time', (string)(60 * 60 * 1)); // 1 час
ini_set('display_errors', 'on');
+ini_set('display_errors', 1);
+ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
-// Если переменная $time передана, используем ее, иначе берем текущее время
-if (!isset($time)) {
- $time = time();
-}
+$time = $time ?? time(); // Использовать текущее время, если параметр не передан
echo "time2_" . $time . "_time2 ";
-$taskNum = 34;
+$taskNum = 32;
$dateTask = date('Y-m-d H:i:s', $time);
-echo "Текущее время задачи: " . $dateTask;
$dateTaskStart = null;
$dateTaskStop = null;
$log = '';
$result = 0;
$enable = true;
+$start = false;
$force = false;
+$minuetTimeInTask = date('i', $time);
+$fullTimeInTask = date('Y-m-d H:i:s', $time);
+
try {
- // Начинаем выполнение задачи только в определенное время или если принудительно (force) разрешено
if (
(
- date('H:i', $time) == "06:00" ||
- date('H:i', $time) == "18:00" ||
- $force
+ (
+ date('H:i', $time) == "06:00" ||
+ date('H:i', $time) == "18:00"
+ )
+ || $force
)
&& $enable
) {
+
$dateTaskStart = date('Y-m-d H:i:s', $time);
- echo '=============== Task ' . $taskNum . ' start ================';
+ $info = ' ================ test Task ' . $taskNum . ' start ================';
+ echo $info;
+ $log .= $info;
+ $log .= $time;
$schedulerTaskLog = new SchedulerTaskLog();
$schedulerTaskLog->setTaskNum($taskNum)
->setName('Task ' . $taskNum)
->setDate($dateTask)
- ->setDateStart($dateTaskStart);
-
- if ($schedulerTaskLog->validate()) {
+ ->setDateStart($dateTaskStart)
+ ;
+ $validate = $schedulerTaskLog->validate();
+ if ($validate) {
$schedulerTaskLog->save();
}
- // Текущий день, месяц и год из переданного времени
- $currentDay = date('d', $time);
- echo "Текущее время задачи день: " . $currentDay;
- $currentMonth = date('m', $time);
- echo "Текущее время задачи месяц: " . $currentMonth;
- $currentYear = date('Y', $time);
- echo "Текущее время задачи год: " . $currentYear;
-
- // Если это первый день месяца, вычисляем предыдущий месяц
- if ($currentDay == 1) {
- // Получаем предыдущий месяц и год
+ $dayOfMonth = date('d', $time);
+ $month = date('m', $time);
+ $year = date('Y', $time);
+ $lastDayOfMonth = date('t', $time);
+
+ // Определяем, за какие недели нужно запросить данные
+ if ($dayOfMonth == '08') {
+ $weeksToFetch = [1]; // 1-я неделя текущего месяца
+ } elseif ($dayOfMonth == '15') {
+ $weeksToFetch = [1, 2]; // 1-я и 2-я недели текущего месяца
+ } elseif ($dayOfMonth == '22') {
+ $weeksToFetch = [1, 2, 3]; // 1-я, 2-я и 3-я недели текущего месяца
+ } elseif ($dayOfMonth == '29') {
+ $weeksToFetch = [1, 2, 3, 4]; // 1-я, 2-я, 3-я и 4-я недели текущего месяца
+ } elseif ($dayOfMonth == '01') {
+ // 1-го числа запрашиваем данные за весь предыдущий месяц
$previousMonth = date('m', strtotime('-1 month', $time));
- echo "Текущее время задачи месяц: " . $previousMonth;
$previousYear = date('Y', strtotime('-1 month', $time));
- echo "Текущее время задачи год: " . $previousYear;
- for ($week = 1; $week <= 5; $week++) {
- $weekRange = Motivation::getWeekRangeForDate($week, $previousMonth, $previousYear);
- processFirms($weekRange, $time);
- }
+
+ // Определяем количество дней в предыдущем месяце
+ $lastDayOfPreviousMonth = cal_days_in_month(CAL_GREGORIAN, $previousMonth, $previousYear);
+
+ // Запрашиваем данные за весь предыдущий месяц
+ $weeksInPreviousMonth = ceil($lastDayOfPreviousMonth / 7);
+ $weeksToFetch = range(1, $weeksInPreviousMonth);
+ $month = $previousMonth;
+ $year = $previousYear;
} else {
- // Выполняем логику для текущего месяца
- processCurrentMonth($currentDay, $currentMonth, $currentYear, $time);
+ // Если текущий день не попадает под условия, запросы не выполняем
+ $weeksToFetch = [];
+ }
+
+ foreach (Firms::getInn() as $key => $firm) {
+ foreach ($weeksToFetch as $week) {
+ sleep(1);
+ // Получаем диапазон дат для указанной недели
+ $weekRange = Motivation::getWeekRange(null, $week, $month, $year);
+ createApiCron($key, $weekRange);
+ }
}
- echo '=============== Task ' . $taskNum . ' stop ================';
+ $info = ' ================ test Task ' . $taskNum . ' stop ================';
+ echo $info;
+ $log .= $info;
+ $log .= ' date >= ' . strtotime("-1 week", $time);
$dateTaskStop = date('Y-m-d H:i:s', $time);
} else {
- echo 'Task ' . $taskNum . ' skipped';
+ $info = ' Task ' . $taskNum . ' skip ';
+ echo $info;
+ $log .= $info;
}
} catch (Exception $e) {
- $error = 'Exception: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
- echo $error;
+ $error = 'Exception: ' . $e->getMessage() . ' ' . $e->getFile() . ' >>> ' . $e->getLine();
}
-// Сохраняем лог выполнения задачи
if (empty($schedulerTaskLog)) {
$schedulerTaskLog = new SchedulerTaskLog();
$schedulerTaskLog->setTaskNum($taskNum)
->setDescription($description)
->setError($error)
->setInfo($infoText)
- ->setLog($log);
+ ->setLog($log)
+ ;
} else {
$schedulerTaskLog->setDateStop($dateTaskStop)
->setDescription($description)
->setError($error)
->setInfo($infoText)
- ->setLog($log);
+ ->setLog($log)
+ ;
}
-
-if ($schedulerTaskLog->validate()) {
+$validate = $schedulerTaskLog->validate();
+if ($validate) {
$schedulerTaskLog->save();
}
-// Функция для обработки фирм по неделям
-function processFirms($weekRange, $time)
-{
- foreach (Firms::getInn() as $key => $firm) {
- createApiCron($key, $weekRange, $time);
- }
-}
-
-// Функция для создания и сохранения запроса в API
-function createApiCron($key, $weekRange, $time)
-{
+function createApiCron($key, $weekRange) {
$model = new ApiCronBuh();
- $model->date = date('Y-m-d H:i:s', $time);
- echo "время задачи: " . $model->date;
- $model->request_id = strval($time . '_' . $key);
-
- // Формирование правильных дат на основе $weekRange
+ $model->date = date('Y-m-d H:i:s');
+ $model->request_id = strval(strtotime($model->date) . '_' . $key);
$model->json_post = Json::encode([
'request_id' => $model->request_id,
'cost_items' => [
'end_time' => date('Y-m-d 23:59:59', strtotime($weekRange['end_time'])),
]
]);
-
$model->inn = $key;
try {
$model->save();
}
}
-// Логика обработки для текущего месяца
-function processCurrentMonth($currentDay, $currentMonth, $currentYear, $time)
-{
- if ($currentDay == 8) {
- // 1-я неделя
- $weekRange = Motivation::getWeekRangeForDate(1, $currentMonth, $currentYear);
- processFirms($weekRange, $time);
- } elseif ($currentDay == 15) {
- // 1-я и 2-я недели
- for ($week = 1; $week <= 2; $week++) {
- $weekRange = Motivation::getWeekRangeForDate($week, $currentMonth, $currentYear);
- processFirms($weekRange, $time);
- }
- } elseif ($currentDay == 22) {
- // 1-я, 2-я и 3-я недели
- for ($week = 1; $week <= 3; $week++) {
- $weekRange = Motivation::getWeekRangeForDate($week, $currentMonth, $currentYear);
- processFirms($weekRange, $time);
- }
- } elseif ($currentDay == 29) {
- // 1-я, 2-я, 3-я и 4-я недели
- for ($week = 1; $week <= 4; $week++) {
- $weekRange = Motivation::getWeekRangeForDate($week, $currentMonth, $currentYear);
- processFirms($weekRange, $time);
- }
- } elseif (date('t', $time) == $currentDay) {
- // Последний день месяца — все 5 недель
- for ($week = 1; $week <= 5; $week++) {
- $weekRange = Motivation::getWeekRangeForDate($week, $currentMonth, $currentYear);
- processFirms($weekRange, $time);
- }
- }
-}
\ No newline at end of file