-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/
#vagrant folder
/.vagrant
+/cron_last_run.txt
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use yii\console\Controller;
+use yii\helpers\ArrayHelper;
+use yii_app\records\Admin;
+use yii_app\records\AdminStores;
+use yii_app\records\ExportImportTable;
+
+class AdminController extends Controller {
+ public function actionUpdateStores() {
+ $admins = Admin::find()
+ ->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
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use Yii;
+use yii\console\Controller;
+
+use yii_app\records\CompanyFunctions;
+use yii_app\records\Task;
+use yii_app\records\TaskAlertLevel;
+use yii_app\records\TaskAlertLevelData;
+use yii_app\records\TaskAlertLog;
+use yii_app\records\TaskStatus;
+use yii_app\records\TaskTemplates;
+use yii_app\records\TaskTriggerTimeConditions;
+use yii_app\services\TaskService;
+
+class AlertsController extends Controller
+{
+ public function actionIndex()
+ {
+ $tasks = Task::find()->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);
+ }
+ }
+}
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use yii_app\records\AlertReceiverType;
+use yii_app\records\CommunicationType;
+use yii_app\records\Messager;
+use yii_app\records\Task;
+use yii_app\services\TelegramService;
+
+class AlertsJob extends \yii\base\BaseObject implements \yii\queue\JobInterface
+{
+ public $taskAlertLevelData;
+ public $task;
+
+ private function createTask() {
+ $task = new Task();
+ $task->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
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use Yii;
+use yii\base\Exception;
+use yii\console\Controller;
+use yii\helpers\ArrayHelper;
+use yii_app\helpers\HtmlHelper;
+use yii_app\records\Admin;
+use yii_app\records\AdminGroup;
+use yii_app\records\AdminPayroll;
+use yii_app\records\CityStore;
+use yii_app\records\EmployeePosition;
+use yii_app\records\ScriptLauncherLog;
+use yii_app\services\AdminPayrollMonthInfoService;
+use yii_app\services\CabinetService;
+use yii_app\services\ExportImportService;
+use yii_app\services\InfoLogService;
+use yii_app\services\LogService;
+use yii_app\services\RatingService;
+
+class AssignmentController extends Controller
+{
+ /**
+ * @throws Exception
+ * @throws \Exception
+ */
+ public function actionInit() {
+ $info = [];
+ $text = '';
+ $errors = [];
+ $decodeString = '-';
+ $uploadArrayInfo = [];
+
+ $val = Yii::$app->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';
+ }
+}
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use Yii;
+use yii\base\Exception;
+use yii\console\Controller;
+use yii\helpers\ArrayHelper;
+use yii_app\helpers\ClientHelper;
+use yii_app\records\Sales;
+use yii_app\records\Users;
+use yii_app\records\UsersBonus;
+use yii_app\records\UsersEvents;
+
+class BonusController extends Controller
+{
+ const DAYS_BEFORE = 2;
+ const DAYS_AFTER = 1;
+
+ public function actionBalanceCorrection() {
+ $plusQuery = UsersBonus::find()->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());
+ }
+ }
+ }
+ }
+}
--- /dev/null
+<?php
+
+namespace yii_app\commands;
+
+use GuzzleHttp\Client;
+use Yii;
+use yii\base\Exception;
+use yii\console\Controller;
+use yii_app\helpers\ClientHelper;
+use yii_app\records\MessagerUser;
+use yii_app\records\Users;
+use yii_app\services\LogService;
+
+class ClientController extends Controller
+{
+ /**
+ * @throws Exception
+ * @throws \Exception
+ */
+ public function actionRetrieve() {
+ $client = new Client();
+ $offset = 0;
+ $finalResult = [];
+ $clients = [];
+ while (true) {
+ $body = $client->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());
+ }
+ }
+ }
+}
}
$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)) {
--- /dev/null
+#!/bin/bash
+cd $1
+echo $(date +%Y%m%d,%T)>cron_last_run.txt
+/bin/php8.1 yii $2
+
+