From: Aleksey Filippov Date: Wed, 20 Mar 2024 13:53:30 +0000 (+0300) Subject: command add X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=775616ebebb4de669aea9f26352b658d3fccaed3;p=yii-erp24%2F.git command add --- diff --git a/.gitignore b/.gitignore index 0a01b81..632ef4f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,10 @@ -erp24/web/uploads -erp24/node_modules -erp24/vendor -erp24/cache -erp24/runtime -erp24/web/dist +erp/web/uploads +erp/node_modules +erp/vendor +erp/cache +erp/runtime +erp/web/dist .idea -erp24/api1/runtime -erp24/api1/views/cron/txt/ -erp24/api1/views/cron/xml/ +erp/api1/runtime +erp/api1/views/cron/txt/ +erp/api1/views/cron/xml/ diff --git a/erp24/.gitignore b/erp24/.gitignore index 3d131f0..edbf380 100644 --- a/erp24/.gitignore +++ b/erp24/.gitignore @@ -34,3 +34,4 @@ tests/_support/_generated #vagrant folder /.vagrant +/cron_last_run.txt diff --git a/erp24/commands/AdminController.php b/erp24/commands/AdminController.php new file mode 100644 index 0000000..8180d1e --- /dev/null +++ b/erp24/commands/AdminController.php @@ -0,0 +1,51 @@ +where(['!=', 'store_arr', '']) + ->andWhere(['!=', 'store_arr_guid', '']) + ->all(); + + $eit = ExportImportTable::find()->where(["entity" => "city_store", 'export_id' => 1])->all(); + $storeIdByGuid = ArrayHelper::map($eit, 'export_val', 'entity_id'); + + foreach ($admins as $admin) { + + $stores_ids = explode(',', $admin->store_arr); + $stores_guids = explode(',', $admin->store_arr_guid); + $store_ids_with_guids = []; + + foreach ($stores_guids as $guid) { + if (mb_strlen($guid) < 36) { + continue; + } + $store_ids_with_guids [] = $storeIdByGuid[$guid] ?? 0; + + $adminStore = new AdminStores; + $adminStore->admin_id = $admin->id; + $adminStore->store_id = $storeIdByGuid[$guid] ?? 0; + $adminStore->store_guid = $guid; + $adminStore->save(); + } + + foreach ($stores_ids as $id) { + if (!in_array($id, $store_ids_with_guids)) { + $adminStore = new AdminStores; + $adminStore->admin_id = $admin->id; + $adminStore->store_id = $id; + $adminStore->store_guid = ''; + $adminStore->save(); + } + } + } + } +} \ No newline at end of file diff --git a/erp24/commands/AlertsController.php b/erp24/commands/AlertsController.php new file mode 100755 index 0000000..53037e4 --- /dev/null +++ b/erp24/commands/AlertsController.php @@ -0,0 +1,114 @@ +all(); + $statuses = TaskStatus::find()->where(['and', ['>', 'id', '0'], ['<', 'id', '6']])->all(); + $taskAlertLevels = TaskAlertLevel::find()->all(); + foreach ($statuses as $status) { + foreach ($tasks as $task) { + if ($task->status == $status->id) { + $time = $task->status_updated_at; + if (!isset($time)) { + $time = $task->created_at; + } + foreach ($taskAlertLevels as $taskAlertLevel) { + $taskAlertLevelDatas = TaskAlertLevelData::find()->where(['level_id' => $taskAlertLevel->id])->andWhere(['status_id' => $status->id])->asArray()->all(); + foreach ($taskAlertLevelDatas as $taskAlertLevelData) { + $t = new \DateTime($time); + $t->add(new \DateInterval('PT' . $taskAlertLevelData['trigger_time'] . 'M' )); + $stamp = $t->format('Y-m-d H:i'); + if (strtotime("now") > strtotime($stamp)) { + $taskAlertLogs = TaskAlertLog::find()->where(['task_id' => $task->id])->andWhere(['alert_id' => $taskAlertLevelData['id']])->all(); + if (count($taskAlertLogs) == 0) { + Yii::$app->queue->push(new AlertsJob(compact('taskAlertLevelData', 'task'))); + die; + $taskAlertLog = new TaskAlertLog(); + $taskAlertLog->task_id = $task->id; + $taskAlertLog->alert_id = $taskAlertLevelData->id; + $taskAlertLog->created_at = date("Y-m-d H:i:s"); + $taskAlertLog->save(false); + } + } + } + } + } + } + } + } + + public function actionTriggerByTime() { + // цикл по триггерам -> попадание в текущий момент + // результат: task_template_id список + // пробегаемся по шаблонам и создаём задачи по функции, которой они принадлежат + $task_template_ids = []; + $taskTriggerTimeConditions = TaskTriggerTimeConditions::find()->all(); + foreach ($taskTriggerTimeConditions as $taskTriggerTimeCondition) { + if ($taskTriggerTimeCondition->minutes != '*') { + $minutes = explode(',', $taskTriggerTimeCondition->minutes); + if (!in_array(date('i'), $minutes)) { +// var_dump('i ' . date('i')); + continue; + } + } + if ($taskTriggerTimeCondition->hours != '*') { + $hours = explode(',', $taskTriggerTimeCondition->hours); + if (!in_array(date('H'), $hours)) { +// var_dump('H ' . date('H')); + continue; + } + } + if ($taskTriggerTimeCondition->days != '*') { + $days = explode(',', $taskTriggerTimeCondition->days); + if (!in_array(date('d'), $days)) { +// var_dump('d ' . date('d')); + continue; + } + } + if ($taskTriggerTimeCondition->months != '*') { + $months = explode(',', $taskTriggerTimeCondition->months); + if (!in_array(date('m'), $months)) { +// var_dump('m ' . date('m')); + continue; + } + } + if ($taskTriggerTimeCondition->weekday != '*') { + $weekday = explode(',', $taskTriggerTimeCondition->weekday); + if (!in_array(date('w'), $weekday)) { +// var_dump('w ' . date('w')); + continue; + } + } + $task_template_ids[] = $taskTriggerTimeCondition->task_template_id; + } + + foreach ($task_template_ids as $task_template_id) { + $taskTemplate = TaskTemplates::findOne($task_template_id); + $companyFunction = CompanyFunctions::findOne($taskTemplate->company_function_id); + if (isset($companyFunction->entity)) { + $entities = TaskService::getFunctionEntitiesByAlias($companyFunction->entity); + foreach ($entities as $entity_id => $name) { + TaskService::createByTemplate($task_template_id, $entity_id); + } + } + TaskService::createByTemplate($task_template_id); + } + } +} diff --git a/erp24/commands/AlertsJob.php b/erp24/commands/AlertsJob.php new file mode 100755 index 0000000..27213d7 --- /dev/null +++ b/erp24/commands/AlertsJob.php @@ -0,0 +1,56 @@ +name = $this->taskAlertLevelData['message']; + switch (AlertReceiverType::findOne($this->taskAlertLevelData['recipient_type_id'])->alias) { + case "person": $task->updated_by = $this->taskAlertLevelData['recipient_id']; break; + case "creator": $task->updated_by = $this->task->created_by; break; + } + $task->created_at = date("Y-m-d H:i:s"); + $task->description = "Задача создана из-за сработавшего уведомления"; + $task->entity_type = 1; // task_entity + $task->task_type_id = 1; // tasks_type + $task->duration = 30; + $task->save(false); + } + + public function createMessage() { + $message = new Messager(); + $message->created_at = date("Y-m-d H:i:s"); + $message->task_id = $this->task->id; + $message->from_id = 1; +// $message->to_id = $this->task->status < 5 ? $this->task->updated_by : $this->task->controller_id; + $message->to_id = 1; + $message->msg = "Уведомлении о простое задачи на данном статусе"; + $message->type_id = 1; + $message->read_status = 0; + $message->save(); + } + + public function createTelegram() { + TelegramService::sendMessage($this->task->updated_by ? $this->task->updated_by : ($this->task->controller_id ? $this->task->controller_id : ($this->task->created_by ? $this->task->created_by : 1)), $this->taskAlertLevelData['message']); + } + + public function execute($queue) + { + switch (CommunicationType::findOne($this->taskAlertLevelData['type_id'])->alias) { + case 'task': $this->createTask(); break; + case 'message': $this->createMessage(); break; + case 'telegram': $this->createTelegram(); break; + } + } +} \ No newline at end of file diff --git a/erp24/commands/AssignmentController.php b/erp24/commands/AssignmentController.php new file mode 100644 index 0000000..67790b7 --- /dev/null +++ b/erp24/commands/AssignmentController.php @@ -0,0 +1,296 @@ +cache->get("addAssignmentTask"); + + if (!empty($val)) { + $decodeString = base64_decode($val); + $uploadArrayInfo = json_decode($decodeString,true,512,JSON_UNESCAPED_UNICODE); + + if (array_key_exists('taskName', $uploadArrayInfo)){ + if ($uploadArrayInfo['taskName'] === 'payrollMake') { + + if (!empty($uploadArrayInfo['start'])) { + $start = $uploadArrayInfo['start']; + $startCheck = time() - 180; +// $startCheck = time() - 7200; + if ($start < $startCheck) { + echo time(); + echo ' '; + $errors[] = 'error: start time is wrong!'; + } + } else { + echo time(); + echo ' '; + $errors[] = 'error: start time is not found!'; + } + if (!empty($errors)) { + Yii::$app->cache->set("addAssignmentTask", false); + } + } else { + Yii::$app->cache->set("addAssignmentTask", false); + } + } + } else { + $text .= "Нет назначенных заданий"; + echo $text . "\n"; + + return 'ok'; + } + if (!array_key_exists('taskName', $uploadArrayInfo)) { + $errors[] = 'error: taskName is not found!'; + } + + $scriptLauncherLog = new ScriptLauncherLog(); + $scriptLauncherLog->source = 'AssignmentController'; + $scriptLauncherLog->category = 'auto start addAssignmentTask'; + $scriptLauncherLog->prefix = 'command'; + $scriptLauncherLog->year = (int) $uploadArrayInfo['year']; + $scriptLauncherLog->month = (int) $uploadArrayInfo['month']; + $scriptLauncherLog->name = 'taskPayrollMake'; + $scriptLauncherLog->file = 'command/AssignmentController.php'; + + $scriptLauncherLog->context = $decodeString; + $scriptLauncherLog->save(); + + $adminsCount = 0; + + if (empty($errors)){ + if ( + (!empty($uploadArrayInfo)) + && + ($uploadArrayInfo['taskName'] === 'payrollMake') + ) { + Yii::$app->cache->set("addAssignmentTask", false); + $text = "В назначенных заданиях есть изменения. Продолжаю выполнение..."; + + $notInStoreIds = Admin::NOT_IN_STORE_IDS; + $ids = null; + + $dateFromText = $uploadArrayInfo['year'] . '-' . $uploadArrayInfo['month'] . '-01'; + + $dateFrom = date("Y-m-01", strtotime($dateFromText)); + + $yearSelect = date("Y", strtotime($dateFrom)); + $monthSelect = date("n", strtotime($dateFrom)); + $monthWithZeroSelect = date("m", strtotime($dateFrom)); + $dateFromBeginMonth = date("Y-m-01", strtotime($dateFrom)); + $dateToEndMonth = date("Y-m-t", strtotime($dateFrom)); + $dateTo = $dateToEndMonth; + if ($monthSelect == date("n")) { + $dateTo = date('Y-m-d', strtotime("-1 day")); + } + + AdminPayroll::clearPayrollFiredAdmin($yearSelect, $monthSelect); + AdminPayroll::clearPayrollWithoutShiftAdmin($yearSelect, $monthSelect); + + $cabinetService = new CabinetService(); + + $idsTimeTableArray = $cabinetService->getTimetableDataList($dateFrom, $dateTo); + $idsTimeTable = ArrayHelper::getColumn($idsTimeTableArray, 'admin_id'); + $ids = $idsTimeTable; + + $adminPayrollAdminIds = []; + $adminPayrollAdminIdsKeys = []; + + $groupIds = Admin::ADMIN_PAYROLL_MAKE_GROUP_IDS; + + $admins = Admin::getAdmins( + $ids, + $groupIds, + 'ASC', + null, + $adminPayrollAdminIds, + $notInStoreIds, + true + ); + + $adminsCountAdd = 0; + if (empty($admins)) { + $info[] = 'admins is empty'; + } else { + $adminsCountStart = count($admins); + $adminsCount = $adminsCountStart; + $scriptLauncherLog->count_start = $adminsCount; + $scriptLauncherLog->save(); + + $entityCityStore = ExportImportService::getEntityByType('city_store'); + + $exportCityStore = ArrayHelper::map($entityCityStore, 'entity_id', 'export_val'); + + $entityAdmin = ExportImportService::getEntityByType('admin'); + + $exportAdmin = ArrayHelper::map($entityAdmin, 'entity_id', 'export_val'); + + $employeePosition = EmployeePosition::getAllIdName(); + $employeeAdminGroup = AdminGroup::getNames(); + + $cityStoreNames = CityStore::getNames(); + $monthNameSelect = HtmlHelper::getMonthName($monthWithZeroSelect); + + $winStoreIdDayChallenge = []; + if ($dateFrom < '2023-10-01') { + $winStoreIdDayChallenge = $cabinetService->getStoreIdDayChallenge($dateFrom, $dateTo); + } + + $calculateValue = true; + + $errors = []; + $adminInfo = []; + + if ($calculateValue) { + foreach ($admins as $employeeSelect) { + $employeeId = $employeeSelect['id']; + ++$adminsCountAdd; + $scriptLauncherLog->current_work = $employeeId; + $scriptLauncherLog->save(); + + $controller = null; + $employeeGroupId = $employeeSelect['group_id']; + + $isAdministrator = Admin::isAdministrator($employeeGroupId); + $ratingId = RatingService::getRatingId($employeeGroupId); + + + if ($dateFrom >= '2023-10-01') { + $payrollValues = $cabinetService->getDataDynamic202310( + $employeeId, + $employeeSelect, + $employeeGroupId, + $isAdministrator, + $ratingId, + $dateFrom, + $dateTo, + $controller, + $winStoreIdDayChallenge, + $exportCityStore, + $exportAdmin, + $yearSelect, + $monthSelect, + $monthWithZeroSelect, + $monthNameSelect, + $dateFromBeginMonth, + $dateToEndMonth, + $employeePosition, + $employeeAdminGroup, + $cityStoreNames + ); + } else { + $payrollValues = $cabinetService->getDataDynamic( + $employeeId, + $employeeSelect, + $employeeGroupId, + $isAdministrator, + $ratingId, + $dateFrom, + $dateTo, + $controller, + $winStoreIdDayChallenge, + $exportCityStore, + $exportAdmin, + $yearSelect, + $monthSelect, + $monthWithZeroSelect, + $monthNameSelect, + $dateFromBeginMonth, + $dateToEndMonth, + $employeePosition, + $employeeAdminGroup, + $cityStoreNames + ); + } + + if (array_key_exists('errorText', $payrollValues)) { + $errors[] = $errorRow = $payrollValues['errorText']; + InfoLogService::setInfoLog(__FILE__, __LINE__, $error ?? [] , 'error payrollValues'); + } else { + AdminPayroll::setValues($payrollValues); + --$adminsCount; + $scriptLauncherLog->count_current = $adminsCountAdd; + $scriptLauncherLog->count_remain = $adminsCount; + $scriptLauncherLog->save(); + if (!empty($adminsCountStart)) { + $scriptLauncherLog->progress = (int)(round(($adminsCountAdd*100) / $adminsCountStart, 0)); + $scriptLauncherLog->save(); + } + + $scriptLauncherLog->save(); + + } + + $adminInfo[$employeeId] = $payrollValues; + } + } + } + + if (!empty($errors)) { + $scriptLauncherLog->error_message = json_encode($errors, JSON_UNESCAPED_UNICODE); + $scriptLauncherLog->error_count = count($errors); + $scriptLauncherLog->save(); + } + if (!empty($dateFrom)) { + (new AdminPayrollMonthInfoService($dateFrom))->setAdminPayrollHistory(); + } + } else { + $text = "Нет назначенных заданий"; + } + } else { + $scriptLauncherLog->error_message = json_encode($errors, JSON_UNESCAPED_UNICODE); + $scriptLauncherLog->error_count = count($errors); + $scriptLauncherLog->save(); + $text = "Ошибка запуска"; + } + + echo $text . "\n"; + + if (!empty($info)) { + $scriptLauncherLog->info = json_encode($info, JSON_UNESCAPED_UNICODE); + } + + $scriptLauncherLog->count_finish = $adminsCount; + + $scriptLauncherLog->message = $text; + $scriptLauncherLog->date_finish = date("Y-m-d H:i:s"); + $scriptLauncherLog->active = 0; + $scriptLauncherLog->status = 2; + + $scriptLauncherLog->save(); + if ($scriptLauncherLog->getErrors()) { + LogService::apiErrorLog(json_encode(["error_id" => 8, "error" => $scriptLauncherLog->getErrors()], JSON_UNESCAPED_UNICODE)); + } + + return 'ok'; + } +} diff --git a/erp24/commands/BonusController.php b/erp24/commands/BonusController.php new file mode 100644 index 0000000..a97e053 --- /dev/null +++ b/erp24/commands/BonusController.php @@ -0,0 +1,288 @@ +select(['SUM(bonus) as sum', 'phone'])->where(['tip' => 'plus']) + ->andWhere(['<=', 'date_start', date('Y-m-d H:i:s')])->groupBy('phone')->all(); + $minusQuery = UsersBonus::find()->select(['SUM(bonus) as sum', 'phone'])->where(['tip' => 'minus'])->groupBy('phone')->all(); + $resultMap = []; + foreach ($plusQuery as $plus) { + $resultMap[$plus->phone] = $plus->sum; + } + foreach ($minusQuery as $minus) { + $resultMap[$minus->phone] = ($resultMap[$minus->phone] ?? 0) - $minus->sum; + } + $i = 0; + foreach ($resultMap as $phone => $sum) { + if ($sum < 0) { + $i++; + echo $i . ') ' . $phone . ' ' . $sum . PHP_EOL; + + $usersBonus = new UsersBonus; + $usersBonus->date = date('Y-m-d H:i:s'); + $usersBonus->tip = 'plus'; + $usersBonus->tip_sale = 'podarok'; + $usersBonus->phone = "" . $phone; + $usersBonus->name = "Корректировка баланса. Выход из минуса."; + $usersBonus->store_id = 0; + $usersBonus->site_id = 0; + $usersBonus->referal_id = 0; + $usersBonus->admin_id = 0; + $usersBonus->price = 0; + $usersBonus->price_skidka = 0; + $usersBonus->bonus = -$sum; + $usersBonus->store_id_1c = "-"; + $usersBonus->seller_id_1c = "-"; + $usersBonus->date_start = date('Y-m-d 08:00:00', strtotime('+0 day', strtotime($usersBonus->date))); + $usersBonus->date_end = date('Y-m-d H:i:s', strtotime('+15 years', strtotime($usersBonus->date_start))); + $usersBonus->save(); + if ($usersBonus->getErrors()) { + var_dump($usersBonus->getErrors()); + } + } + } + } + + public function actionAdd() { + $date_day_now = (int)date("d", time()); // Сегодняшний день + $date_month_now = (int)date("m", time()); // Сегодняшний месяц + + $userEventsQuery = UsersEvents::find()->select(['phone', 'date', 'date_add', 'date_day', 'date_month'])->where(['and', ['date_day' => $date_day_now], ['date_month' => $date_month_now]]); + + for ($ind = 1; $ind <= self::DAYS_BEFORE; $ind++) { + $t = 86400 * $ind; + $date_day = (int)date("d",time() + $t); // день за DAYS_BEFORE и меньше дней до памятной даты + $date_month = (int)date("m",time() + $t); // месяц тоже самое + echo "\nИщем события на дату $date_day.$date_month"; + + $userEventsQuery = $userEventsQuery->orWhere(['and', ['date_day' => $date_day], ['date_month' => $date_month]]); + } + + $userEvents = $userEventsQuery->all(); + + foreach ($userEvents as $event) { + echo "\n " . $event->phone . " " . $event->date . " " . $event->date_add . " "; + + $date_end = date("Y-m-d 23:59:59", + strtotime(date("Y", time() + self::DAYS_AFTER * 86400) + . "-" . $event->date_month . "-" . $event->date_day) + 86400 * self::DAYS_AFTER); + $date_start = date("Y-m-d", time()); + + $tip = "plus"; + $bonus = 200; + $ip = "tst"; + $tip_sale = "date"; + echo "\n date_start=$date_start date_end=$date_end"; + + $userBonus = UsersBonus::find()->select(['date'])->where(['phone' => $event->phone])->andWhere(['tip' => $tip]) + ->andWhere(['tip_sale' => $tip_sale])->andWhere(['date_start' => $date_start])->one(); + + $do = false; + + $name = "Автоматическое начисление бонусов на дату " . date("Y", time() + self::DAYS_AFTER * 86400) + . "-" . $event->date_month . "-" . $event->date_day . " на " . (self::DAYS_BEFORE + self::DAYS_AFTER + 1) . " дня"; + // если дата еще не вносилась + if (!$userBonus) { + $do = true; + } + // проверяем были ли начислены бонусы на сегодняшнюю дату от вчера до DAYS_BEFORE до этого + $userBonus2Query = UsersBonus::find()->select(['date', 'date_end', 'date_start'])->where(['phone' => $event->phone])->andWhere(['tip' => $tip]) + ->andWhere(['tip_sale' => $tip_sale]); + + for ($ind = 1; $ind <= self::DAYS_BEFORE; $ind++) { + $date_start_old = date("Y-m-d",time() - 86400 * $ind); + $userBonus2Query = $userBonus2Query->andWhere(['date_start' => $date_start_old]); + } + + $userBonus2 = $userBonus2Query->one(); + if ($userBonus2) { + // если от вчера до DAYS_BEFORE было начисление, то сегодня не начисляем + $do = false; + echo "есть ли cтарая дата ??? date_start=" . $userBonus2->date_start . " date=" . $userBonus2->date + . " date_end=" . $userBonus2->date_end . "==="; + } + + if ($do) { + $userBonus4 = new UsersBonus; + $userBonus4->phone = '' . $event->phone; + $userBonus4->name = $name; + $userBonus4->tip = $tip; + $userBonus4->tip_sale = $tip_sale; + $userBonus4->bonus = $bonus; + $userBonus4->date = date('Y-m-d H:i:s'); + $userBonus4->date_start = $date_start; + $userBonus4->date_end = $date_end; + $userBonus4->ip = $ip; + $userBonus4->save(); + if ($userBonus4->getErrors()) { + echo '\n' . json_encode($userBonus4->getErrors(), JSON_UNESCAPED_UNICODE); + } + } else { + echo "\n" . $event->phone . " уже начисляли бонусы на эту дату "; + } + } + } + + public function actionDell() { + // собираем записи "миносов" - "сгорания" дат по ключу tip='plus' AND tip_sale='date' date_start + $userBonuses = UsersBonus::find()->select(['phone', 'date_start', 'bonus'])->where(['>', 'bonus', '0'])->andWhere(['tip' => 'minus']) + ->andWhere(['tip_sale' => 'date']) + ->andWhere(['>=', 'date_start', date('Y-m-d H:i:s', time() - (self::DAYS_BEFORE + self::DAYS_AFTER + 1) * 86400)]) + ->andWhere(['<=', 'date_start', date('Y-m-d H:i:s', time())]) + ->all(); + $minusYes = []; + foreach ($userBonuses as $userBonus) { + $minusYes[$userBonus->phone][$userBonus->date_start] = $userBonus->bonus; + } + //пробегаемся оп записям начилений для дат "плюс" у которых вышло время начисленных бонусов. + $userBonus1 = UsersBonus::find()->select(['id', 'phone', 'date_start', 'date_end', 'bonus', 'dell']) + ->where(['tip' => 'plus'])->andWhere(['tip_sale' => 'date']) + ->andWhere(['<=', 'date_end', date('Y-m-d H:i:s', time())]) + ->andWhere(['>=', 'date_end', date('Y-m-d H:i:s', time() - (self::DAYS_AFTER + 1) * 86400)]) + ->all(); + foreach ($userBonus1 as $userBonus) { + // если по этой записи на дату старта мы уже вносили запись то выдаем сообщение + if (isset($minusYes[$userBonus->phone][$userBonus->date_start]) || $userBonus->dell > 0) { + echo "\n" . $userBonus->date_start . " " . $userBonus->phone . " минуc есть"; + } elseif ($userBonus->bonus > 0) { + $sale = UsersBonus::find()->select(['SUM(bonus) as sum', 'phone'])->where(['tip' => 'minus']) + ->andWhere(['tip_sale' => 'sale']) + ->andWhere(['phone' => $userBonus->phone]) + ->andWhere(['>=', 'date', $userBonus->date_start]) + ->andWhere(['<=', 'date', $userBonus->date_end]) + ->groupBy(['phone']) + ->one(); + // если не вносили формируем запрос на внесение сгорания + $name = "Автоматическое сгорание бонусов на дату " . $userBonus->date_start . ""; + $userBonus2 = new UsersBonus; + $userBonus2->phone = $userBonus->phone; + $userBonus2->name = $name; + $userBonus2->tip_sale = 'date'; + $userBonus2->tip = 'minus'; + $userBonus2->bonus = isset($sale) ? max(0, $userBonus->bonus - $sale->sum) : $userBonus->bonus; + $userBonus2->date = date('Y-m-d H:i:s'); + $userBonus2->date_start = $userBonus->date_start; + $userBonus2->date_end = $userBonus->date_end; + $userBonus2->ip = 'tst2'; + $userBonus2->save(); + if ($userBonus2->getErrors()) { + echo '\n 1: ' . json_encode($userBonus2->getErrors(), JSON_UNESCAPED_UNICODE); + } + $userBonus->dell = '1'; + $userBonus->date_dell = date('Y-m-d H:i:s'); + $userBonus->save(); + if ($userBonus->getErrors()) { + echo '\n 2: ' . json_encode($userBonus->getErrors(), JSON_UNESCAPED_UNICODE); + } + echo "\n" . $userBonus2->phone . " " . $name; + } + } + } + + public function actionDellPromo() { + $userBonus1 = UsersBonus::find()->select(['id', 'phone', 'date_start', 'date_end', 'bonus', 'dell', 'tip', 'tip_sale']) + ->where(['tip' => 'plus'])->andWhere(['not in', 'tip_sale', ['date', 'off']]) + ->andWhere(['<=', 'date_end', date('Y-m-d 00:00:00', time())]) + ->andWhere(['>=', 'date_end', date('Y-m-d 23:59:59', time())]) + ->all(); + foreach ($userBonus1 as $userBonus) { + if ($userBonus->dell > 0) { + echo "\n" . $userBonus->date_start . " " . $userBonus->phone . " минуc есть"; + } else { + $sale = UsersBonus::find()->select(['SUM(bonus) as sum', 'phone'])->where(['tip' => 'minus']) + ->andWhere(['tip_sale' => 'sale']) + ->andWhere(['phone' => $userBonus->phone]) + ->andWhere(['>=', 'date', $userBonus->date_start]) + ->andWhere(['<=', 'date', $userBonus->date_end]) + ->groupBy(['phone']) + ->one(); + $name = "Автоматическое сгорание бонусов на дату " . $userBonus->date_start . ""; + $userBonus2 = new UsersBonus; + $userBonus2->phone = $userBonus->phone; + $userBonus2->name = $name; + $userBonus2->tip_sale = $userBonus->tip_sale; + $userBonus2->tip = 'minus'; + $userBonus2->bonus = isset($sale) ? max(0, $userBonus->bonus - $sale->sum) : $userBonus->bonus; + $userBonus2->date = date('Y-m-d H:i:s'); + $userBonus2->date_start = $userBonus->date_start; + $userBonus2->date_end = $userBonus->date_end; + $userBonus2->ip = 'tst2'; + $userBonus2->save(); + if ($userBonus2->getErrors()) { + echo '\n 1: ' . json_encode($userBonus2->getErrors(), JSON_UNESCAPED_UNICODE); + } + $userBonus->dell = '1'; + $userBonus->date_dell = date('Y-m-d H:i:s'); + $userBonus->save(); + if ($userBonus->getErrors()) { + echo '\n 2: ' . json_encode($userBonus->getErrors(), JSON_UNESCAPED_UNICODE); + } + echo "\n" . $userBonus2->phone . " " . $name; + } + } + } + + public function actionPlus100Contest() { + $data = file_get_contents(__DIR__ . '/plus100rubles.txt'); + $arr = preg_split("/\r\n|\n|\r/", $data); + foreach ($arr as $phone) { + if (!empty($phone)) { + $userBonus = new UsersBonus; + $userBonus->phone = $phone; + $userBonus->name = "100 бонусов за участие в розыгрыше iPhone"; + $userBonus->date = date('Y-m-d H:i:s'); + $userBonus->site_id = 1; + $userBonus->setka_id = 1; + $userBonus->tip = 'plus'; + $userBonus->tip_sale = 'contest202310'; + $userBonus->bonus = 100; + $userBonus->date_start = $userBonus->date; + $userBonus->date_end = date('Y-m-d H:i:s', strtotime('+366 day', strtotime($userBonus->date))); + $userBonus->save(); + if ($userBonus->getErrors()) { + var_dump($userBonus->getErrors()); + } + } + } + } + + public function actionPlus300On14Feb() { + $existingPhones = ArrayHelper::getColumn(UsersBonus::find()->where(['tip_sale' => '14feb'])->all(), 'phone'); + foreach (Users::find()->select(['phone'])->where(['pol' => 'man', 'telegram_is_subscribed' => 1])->all() as $user) { + $phone = $user->phone; + if (ClientHelper::phoneVerify($phone) && !in_array($phone, $existingPhones)) { + $userBonus = new UsersBonus; + $userBonus->phone = $phone; + $userBonus->name = "Ко Дню Влюблённых"; + $userBonus->date = date('Y-m-d H:i:s'); + $userBonus->site_id = 1; + $userBonus->setka_id = 1; + $userBonus->tip = 'plus'; + $userBonus->tip_sale = '14feb'; + $userBonus->bonus = 300; + $userBonus->date_start = $userBonus->date; + $userBonus->date_end = date('Y-m-d H:i:s', strtotime('+2 day', strtotime($userBonus->date))); + $userBonus->save(); + if ($userBonus->getErrors()) { + var_dump($userBonus->getErrors()); + } + } + } + } +} diff --git a/erp24/commands/ClientController.php b/erp24/commands/ClientController.php new file mode 100644 index 0000000..34fb1c0 --- /dev/null +++ b/erp24/commands/ClientController.php @@ -0,0 +1,187 @@ +request('GET', 'https://chatter.salebot.pro/api/325aa5519d0e65ea8c4759a3e6143584/get_clients?offset=' . $offset)->getBody(); + $result = ''; + while (!$body->eof()) { + $result .= $body->read(10000); + } + $json = json_decode($result, true); + foreach ($json['clients'] as $data) { + $client_id = $data['id']; + $platform_id = $data['platform_id']; + $client_type = $data['client_type']; + + if (!isset($clients[$client_id])) { + $clients[$client_id] = []; + } + + $clients[$client_id]['platform_id'] = $platform_id; + $clients[$client_id]['client_type'] = $client_type; + + $finalResult [] = $data; + } + if (count($json['clients']) > 0) { + $offset += 500; + } else { + break; + } + } + + $diff_time = 10 * 24 * 60 * 60; // 10 day + $current_time = time(); + + foreach (range(0, 50) as $day10) { + $date_from = $current_time - $diff_time * ($day10 + 1); + $date_to = $current_time - $diff_time * $day10; + + $body = $client->request('GET', 'https://chatter.salebot.pro/api/325aa5519d0e65ea8c4759a3e6143584/subscribers?date_to=' . $date_to . '&date_from=' . $date_from)->getBody(); + + $result = ''; + while (!$body->eof()) { + $result .= $body->read(10000); + } + $json = json_decode($result, true); + foreach ($json as $data) { + $client_id = $data['id']; + $client_type = $data['client_type']; + + $phone = $data['variables']['phone'] ?? ''; + $is_subscribed = ($data['variables']['notSubscribed'] ?? '0') != '1'; + + if (!isset($clients[$client_id])) { + $clients[$client_id] = []; + } + + $clients[$client_id]['client_type'] = $client_type; + $clients[$client_id]['phone'] = $phone; + $clients[$client_id]['is_subscribed'] = $is_subscribed; + + $finalResult [] = $data; + } + } + + foreach ($clients as $client_id => &$client_data1) { + if (!isset($client_data1['phone'])) { + $body = $client->request('GET', 'https://chatter.salebot.pro/api/325aa5519d0e65ea8c4759a3e6143584/get_variables?client_id=' . $client_id)->getBody(); + $result = ''; + while (!$body->eof()) { + $result .= $body->read(10000); + } + $json = json_decode($result, true); + if (isset($json['phone'])) { + $client_data1['phone'] = $json['phone']; + } + } + } + + foreach ($clients as $client_id => $client_data) { + $messagerUser = MessagerUser::find()->where(['client_id' => $client_id])->one(); + if (!$messagerUser) { + $messagerUser = new MessagerUser; + $messagerUser->client_id = $client_id; + } + + if (isset($client_data['client_type'])) { + $messagerUser->client_type = $client_data['client_type']; + } + + if (isset($client_data['platform_id'])) { + $messagerUser->platform_id = intval($client_data['platform_id']) ?? 0; + } + + $phone = ClientHelper::phoneClear($client_data['phone'] ?? ''); + $messagerUser->phone = ClientHelper::phoneVerify($phone) ? $phone : ''; + + if (isset($client_data['is_subscribed'])) { + $messagerUser->is_subscribed = $client_data['is_subscribed'] ? 1 : 0; + } + $messagerUser->save(); + if ($messagerUser->getErrors()) { + + LogService::apiErrorLog(json_encode(["error_id" => 1, "error" => $messagerUser->getErrors()], JSON_UNESCAPED_UNICODE)); + + var_dump($messagerUser->getErrors()); + die; + } + } + + var_dump($finalResult); + } + + public function actionRefreshUsersDatabase() { + $txt = file_get_contents(__DIR__ . "/refresh_clients.txt"); + $data = []; + $phones = []; + $arr = preg_split("/[\r\n]+/", $txt); + foreach ($arr as $str) { + if (empty($str)) { + continue; + } + $rec = preg_split('/\s+/', $str); + $phone = $rec[0]; + $phones [] = $phone; + $data [$phone] = $rec; + } + $users = Users::find()->where(['IN', 'phone', $phones])->all(); + foreach ($users as $user) { + /* @var $user Users */ + $rec = $data[$user->phone]; + $user->source = 1; + $user->date = $user->date ?? date('Y-m-d H:i:s'); + $user->telegram_is_subscribed = $rec[1] == 1 ? 0 : 1; + $user->telegram_created_at = $rec[2] == 0 ? "2023-06-04 00:00:00" : date("Y-m-d H:i:s", $rec[2]); + $user->password = ClientHelper::generatePassword(8); + $user->keycode = "" . rand(1000, 9999); + $user->save(); + if ($user->getErrors()) { + var_dump($user->getErrors()); + } + unset($data[$user->phone]); + } + foreach ($data as $phone => $rec) { + $user = new Users; + $user->phone = "" . $phone; + $user->name = ""; + $user->name_name = ""; + $user->setka_id = '1'; + $user->phone_true = '1'; + $user->created_store = ''; + $user->sale_store = ''; + $user->date = date('Y-m-d H:i:s'); + $user->password = ClientHelper::generatePassword(8); + $user->keycode = "" . rand(1000, 9999); + $user->card = "" . (intval($phone) * 2 + 1608 + $user->setka_id); // генерируем номер карты который зависит от номера сетки + ДР Тимура + $user->info = ""; + $user->source = 2; + $user->telegram_is_subscribed = $rec[1] == 1 ? 0 : 1; + $user->telegram_created_at = $rec[2] == 0 ? "2023-06-04 00:00:00" : date("Y-m-d H:i:s", $rec[2]); + $user->save(); + if ($user->getErrors()) { + var_dump($user->getErrors()); + } + } + } +} diff --git a/erp24/helpers/File.php b/erp24/helpers/File.php index 21252a4..2582b7e 100644 --- a/erp24/helpers/File.php +++ b/erp24/helpers/File.php @@ -114,9 +114,9 @@ class File extends FileHelper } $substr = substr($filename, 0, 2); $imagePath = self::filepath($filename, 'images'); - $resizePath = "uploads/images/resize/{$substr}/{$w}_{$h}_{$quality}"; + $resizePath = "/var/www/erp/uploads/images/resize/{$substr}/{$w}_{$h}_{$quality}"; $resizedUrl = "{$resizePath}/{$filename}"; - $resizedPath = "uploads/images/resize/{$substr}/{$w}_{$h}_{$quality}"; + $resizedPath = "/var/www/erp/uploads/images/resize/{$substr}/{$w}_{$h}_{$quality}"; $resizedFile = "{$resizedPath}/{$filename}"; if (!file_exists($imagePath)) { diff --git a/erp24/yii_run b/erp24/yii_run new file mode 100644 index 0000000..3921e6d --- /dev/null +++ b/erp24/yii_run @@ -0,0 +1,6 @@ +#!/bin/bash +cd $1 +echo $(date +%Y%m%d,%T)>cron_last_run.txt +/bin/php8.1 yii $2 + +