diff --git a/clients/smtp.go b/clients/smtp.go index 2b2f802..8c59537 100644 --- a/clients/smtp.go +++ b/clients/smtp.go @@ -13,8 +13,6 @@ type Deps struct { SmtpHost string SmtpPort string SmtpSender string - Username string - Password string ApiKey string FiberClient *fiber.Client } @@ -24,8 +22,6 @@ type SmtpClient struct { smtpHost string smtpPort string smtpSender string - username string - password string apiKey string fiberClient *fiber.Client } @@ -39,8 +35,6 @@ func NewSmtpClient(deps Deps) *SmtpClient { smtpHost: deps.SmtpHost, smtpPort: deps.SmtpPort, smtpSender: deps.SmtpSender, - username: deps.Username, - password: deps.Password, apiKey: deps.ApiKey, fiberClient: deps.FiberClient, } diff --git a/dal/dal.go b/dal/dal.go index 106e537..1b0de35 100644 --- a/dal/dal.go +++ b/dal/dal.go @@ -17,6 +17,7 @@ import ( "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/quiz" "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/result" "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/statistics" + "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/tg" "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/repository/workers" "time" ) @@ -34,6 +35,7 @@ type DAL struct { WorkerRepo *workers.WorkerRepository StatisticsRepo *statistics.StatisticsRepository WorkerAnsRepo *answer.WorkerAnswerRepository + TgRepo *tg.TgRepo } func New(ctx context.Context, cred string, minioClient *minio.Client) (*DAL, error) { @@ -100,6 +102,11 @@ func New(ctx context.Context, cred string, minioClient *minio.Client) (*DAL, err Pool: pool, }) + tgRepo := tg.NewTgRepo(tg.Deps{ + Queries: queries, + Pool: pool, + }) + return &DAL{ conn: pool, queries: queries, @@ -111,6 +118,7 @@ func New(ctx context.Context, cred string, minioClient *minio.Client) (*DAL, err WorkerRepo: workerRepo, StatisticsRepo: statisticsRepo, WorkerAnsRepo: workerAnsRepo, + TgRepo: tgRepo, }, nil } diff --git a/dal/db_query/queries.sql b/dal/db_query/queries.sql index 1406e9a..f0a49e5 100644 --- a/dal/db_query/queries.sql +++ b/dal/db_query/queries.sql @@ -20,7 +20,7 @@ INSERT INTO quiz (accountid, qid ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) - RETURNING id, created_at, updated_at, qid; +RETURNING id, created_at, updated_at, qid; -- name: InsertQuestion :one INSERT INTO question ( @@ -35,7 +35,7 @@ INSERT INTO question ( updated_at ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) - RETURNING id, created_at, updated_at; +RETURNING id, created_at, updated_at; -- name: DeleteQuestion :one UPDATE question SET deleted=true WHERE id=$1 RETURNING question.*; @@ -51,7 +51,7 @@ INSERT INTO question( SELECT $1, title, description, questiontype, required, page, content, version, parent_ids FROM question WHERE question.id=$2 - RETURNING question.id, quiz_id, created_at, updated_at; +RETURNING question.id, quiz_id, created_at, updated_at; -- name: DuplicateQuestion :one INSERT INTO question( @@ -61,7 +61,7 @@ INSERT INTO question( SELECT quiz_id, title, description, questiontype, required, page, content, version, parent_ids FROM question WHERE question.id=$1 - RETURNING question.id, quiz_id, created_at, updated_at; +RETURNING question.id, quiz_id, created_at, updated_at; -- name: MoveToHistory :one INSERT INTO question( @@ -71,7 +71,7 @@ INSERT INTO question( SELECT quiz_id, title, description, questiontype, required, page, content, version, parent_ids, true as deleted FROM question WHERE question.id=$1 - RETURNING question.id, quiz_id, parent_ids; +RETURNING question.id, quiz_id, parent_ids; -- name: MoveToHistoryQuiz :one INSERT INTO quiz(deleted, @@ -81,7 +81,7 @@ INSERT INTO quiz(deleted, SELECT true as deleted, accountid, archived,fingerprinting,repeatable,note_prevented,mail_notifications,unique_answers,name,description,config, status,limit_answers,due_to,time_of_passing,pausable,version,version_comment,parent_ids,questions_count,answers_count,average_time_passing, super, group_id FROM quiz WHERE quiz.id=$1 AND quiz.accountid=$2 - RETURNING quiz.id, qid, parent_ids; +RETURNING quiz.id, qid, parent_ids; -- name: CopyQuiz :one INSERT INTO quiz( @@ -91,7 +91,7 @@ INSERT INTO quiz( SELECT accountid, archived,fingerprinting,repeatable,note_prevented,mail_notifications,unique_answers,name,description,config, status,limit_answers,due_to,time_of_passing,pausable,version,version_comment,parent_ids,questions_count, super, group_id FROM quiz WHERE quiz.id=$1 AND quiz.accountId=$2 - RETURNING id, qid,created_at, updated_at; +RETURNING id, qid,created_at, updated_at; -- name: CopyQuizQuestions :exec INSERT INTO question( @@ -134,7 +134,6 @@ SELECT p.amount, p.created_at, a.id, - a.email, qz.config FROM privileges AS p @@ -144,7 +143,7 @@ WHERE qz.id = $1; -- name: CreateAccount :one -INSERT INTO account (id, user_id, email, created_at, deleted) VALUES ($1, $2, $3, $4, $5) RETURNING *;; +INSERT INTO account (id, user_id, created_at, deleted) VALUES ($1, $2, $3, $4) RETURNING *; -- name: DeletePrivilegeByAccID :exec DELETE FROM privileges WHERE account_id = $1; @@ -233,11 +232,11 @@ SET answers_count = COALESCE(aa.unique_true_answers_count, 0), average_time_passing = COALESCE(sta.average_session_time, 0), sessions_count = COALESCE(sta.sess,0) - FROM +FROM (SELECT * FROM quiz WHERE deleted = FALSE AND archived = FALSE) q_sub -LEFT JOIN answer_aggregates aa ON q_sub.id = aa.quiz_id - LEFT JOIN question_aggregates qa ON q_sub.id = qa.quiz_id - LEFT JOIN session_times_aggregates sta ON q_sub.id = sta.quiz_id + LEFT JOIN answer_aggregates aa ON q_sub.id = aa.quiz_id + LEFT JOIN question_aggregates qa ON q_sub.id = qa.quiz_id + LEFT JOIN session_times_aggregates sta ON q_sub.id = sta.quiz_id WHERE q.id = q_sub.id; @@ -248,7 +247,6 @@ UPDATE privileges SET amount = $1 WHERE id = $2; SELECT a.id, a.user_id, - a.email, a.created_at, COALESCE(p.ID,0), coalesce(p.privilegeid,''), @@ -409,13 +407,13 @@ WITH TimeBucket AS ( SELECT date_trunc('hour', timestamp_bucket)::TIMESTAMP AS time_interval_start, COALESCE(LEAD( - date_trunc('hour', timestamp_bucket)::TIMESTAMP - ) OVER (ORDER BY timestamp_bucket), NOW()) AS time_interval_end + date_trunc('hour', timestamp_bucket)::TIMESTAMP + ) OVER (ORDER BY timestamp_bucket), NOW()) AS time_interval_end FROM - generate_series(TO_TIMESTAMP($1), TO_TIMESTAMP($2), CASE - WHEN EXTRACT(epoch FROM TO_TIMESTAMP($2)) - EXTRACT(epoch FROM TO_TIMESTAMP($1)) > 172800 THEN '1 day'::interval - ELSE '1 hour'::interval - END) AS timestamp_bucket + generate_series(TO_TIMESTAMP($1), TO_TIMESTAMP($2), CASE + WHEN EXTRACT(epoch FROM TO_TIMESTAMP($2)) - EXTRACT(epoch FROM TO_TIMESTAMP($1)) > 172800 THEN '1 day'::interval + ELSE '1 hour'::interval + END) AS timestamp_bucket ), OpenStats AS ( SELECT @@ -496,7 +494,7 @@ SELECT CASE WHEN COALESCE(os.open_count, 0) > 0 THEN COALESCE(rs.true_result_count, 0)::float / COALESCE(os.open_count, 0)::float ELSE 0 - END::float AS conversion, + END::float AS conversion, COALESCE(at.avg_time, 0) AS avg_time FROM TimeBucket tb @@ -513,10 +511,10 @@ FROM -- name: QuestionsStatistics :many WITH Funnel AS ( SELECT - COUNT(DISTINCT a.session) FILTER (WHERE a.start = FALSE) AS count_start_false, - COUNT(DISTINCT a.session) FILTER (WHERE a.start = TRUE) AS count_start_true, - COUNT(DISTINCT CASE WHEN a.result = FALSE AND qid_true_result IS NOT NULL THEN a.session END) AS count_f_result_with_t_question, - COUNT(DISTINCT a.session) FILTER (WHERE a.result = TRUE) AS count_t_result + COUNT(DISTINCT a.session) FILTER (WHERE a.start = FALSE) AS count_start_false, + COUNT(DISTINCT a.session) FILTER (WHERE a.start = TRUE) AS count_start_true, + COUNT(DISTINCT CASE WHEN a.result = FALSE AND qid_true_result IS NOT NULL THEN a.session END) AS count_f_result_with_t_question, + COUNT(DISTINCT a.session) FILTER (WHERE a.result = TRUE) AS count_t_result FROM answer a LEFT JOIN ( @@ -531,23 +529,23 @@ WITH Funnel AS ( AND a.created_at <= TO_TIMESTAMP($3) ), Results AS ( - SELECT - COALESCE(q.title, '') AS question_title, - COUNT(*) AS total_answers, - CAST(COUNT(*) * 100.0 / NULLIF(SUM(COUNT(*)) FILTER (WHERE a.result = TRUE) OVER (PARTITION BY a.quiz_id), 0) AS FLOAT8) AS percentage - FROM - question q - JOIN answer a ON q.id = a.question_id - WHERE - a.quiz_id = $1 - AND a.created_at >= TO_TIMESTAMP($2) - AND a.created_at <= TO_TIMESTAMP($3) - AND a.result = TRUE - GROUP BY - q.title, a.quiz_id, a.result - HAVING - COUNT(*) >= 1 - ), + SELECT + COALESCE(q.title, '') AS question_title, + COUNT(*) AS total_answers, + CAST(COUNT(*) * 100.0 / NULLIF(SUM(COUNT(*)) FILTER (WHERE a.result = TRUE) OVER (PARTITION BY a.quiz_id), 0) AS FLOAT8) AS percentage + FROM + question q + JOIN answer a ON q.id = a.question_id + WHERE + a.quiz_id = $1 + AND a.created_at >= TO_TIMESTAMP($2) + AND a.created_at <= TO_TIMESTAMP($3) + AND a.result = TRUE + GROUP BY + q.title, a.quiz_id, a.result + HAVING + COUNT(*) >= 1 + ), LastContent AS ( SELECT a.question_id, @@ -563,35 +561,35 @@ WITH Funnel AS ( answer WHERE quiz_id = $1 - AND start != true + AND start != true AND created_at >= TO_TIMESTAMP($2) AND created_at <= TO_TIMESTAMP($3) GROUP BY - question_id, session + question_id, session ) AS last_created_at_one_session ON a.session = last_created_at_one_session.session AND a.question_id = last_created_at_one_session.question_id AND a.created_at = last_created_at_one_session.last_created_at ), Questions AS ( - SELECT - q.title AS question_title, - q.page AS question_page, - lc.last_answer_content AS answer_content, - CAST( - COUNT(CASE WHEN a.result = FALSE THEN 1 END) * 100.0 / NULLIF(SUM(COUNT(CASE WHEN a.result = FALSE THEN 1 END)) OVER (PARTITION BY q.id), 0) AS FLOAT8 - ) AS percentage - FROM - question q - JOIN LastContent lc ON q.id = lc.question_id - JOIN answer a ON q.id = a.question_id - WHERE - a.quiz_id = $1 - AND a.start != true - AND a.created_at >= TO_TIMESTAMP($2) - AND a.created_at <= TO_TIMESTAMP($3) - GROUP BY - q.id, q.title, lc.last_answer_content - HAVING - COUNT(*) >= 1 -) + SELECT + q.title AS question_title, + q.page AS question_page, + lc.last_answer_content AS answer_content, + CAST( + COUNT(CASE WHEN a.result = FALSE THEN 1 END) * 100.0 / NULLIF(SUM(COUNT(CASE WHEN a.result = FALSE THEN 1 END)) OVER (PARTITION BY q.id), 0) AS FLOAT8 + ) AS percentage + FROM + question q + JOIN LastContent lc ON q.id = lc.question_id + JOIN answer a ON q.id = a.question_id + WHERE + a.quiz_id = $1 + AND a.start != true + AND a.created_at >= TO_TIMESTAMP($2) + AND a.created_at <= TO_TIMESTAMP($3) + GROUP BY + q.id, q.title, lc.last_answer_content + HAVING + COUNT(*) >= 1 + ) SELECT Funnel.count_start_false, Funnel.count_start_true, @@ -605,34 +603,34 @@ SELECT COALESCE(Questions.percentage, 0) AS questions_percentage FROM Funnel - LEFT JOIN Results ON true - LEFT JOIN Questions ON Questions.percentage >= 1; + LEFT JOIN Results ON true + LEFT JOIN Questions ON Questions.percentage >= 1; -- name: QuizCopyQid :one - INSERT INTO quiz ( - accountid, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, - status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id - ) - SELECT - $2, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, - status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id - FROM - quiz as q - WHERE - q.qid = $1 - RETURNING (select id from quiz where qid = $1),id, qid; - +INSERT INTO quiz ( + accountid, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, + status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id +) +SELECT + $2, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, + status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id +FROM + quiz as q +WHERE + q.qid = $1 +RETURNING (select id from quiz where qid = $1),id, qid; + -- name: CopyQuestionQuizID :exec INSERT INTO question ( quiz_id, title, description, questiontype, required, page, content, version, parent_ids, created_at, updated_at ) -SELECT +SELECT $2, title, description, questiontype, required, page, content, version, parent_ids, created_at, updated_at -FROM +FROM question -WHERE +WHERE question.quiz_id = $1 AND deleted = false; -- name: GetQidOwner :one @@ -658,7 +656,7 @@ SELECT (SELECT registration_count FROM Registrations) AS registrations, (SELECT quiz_count FROM Quizes) AS quizes, (SELECT result_count FROM Results) AS results; - + -- name: GetListStartQuiz :many SELECT id FROM quiz WHERE accountid = $1 AND status = 'start'; @@ -710,19 +708,19 @@ UPDATE accountsAmo SET Name = $2, Subdomain = $3, Country = $4, DriveURL = $5 WH WITH companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE accountsAmo.AmoID = $1 RETURNING AccountID ), -userDel AS ( -UPDATE usersAmo SET Deleted = true WHERE AmoID = $1 -) + userDel AS ( + UPDATE usersAmo SET Deleted = true WHERE AmoID = $1 + ) DELETE FROM tokens WHERE AccountID IN (SELECT AccountID FROM companyDel); -- name: SoftDeleteAccount :exec WITH amoCompany AS ( SELECT AmoID FROM accountsAmo WHERE accountsAmo.AccountID = $1 AND deleted = false ),usersDel AS ( - UPDATE usersAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) - ), - companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) - ) + UPDATE usersAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) +), + companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) + ) DELETE FROM tokens WHERE tokens.AccountID = $1; -- name: GetCurrentCompany :one @@ -812,7 +810,7 @@ FROM json_array_elements($1::json) AS update_data WHERE f.amoID = (update_data ->> 'AmoID')::INT AND f.accountID = (update_data ->> 'AccountID')::INT AND f.Entity = (update_data ->> 'Entity')::entitytype; - + -- name: CheckTags :many WITH user_data AS ( SELECT AmoID FROM accountsAmo WHERE accountsAmo.AccountID = $1 AND accountsAmo.Deleted = false @@ -837,7 +835,7 @@ WITH user_data AS ( ) SELECT nt.*,ud.AmoID FROM new_tags nt - JOIN user_data ud ON true + JOIN user_data ud ON true WHERE NOT EXISTS ( SELECT * FROM inserted_tags ins @@ -855,14 +853,14 @@ WITH new_pipelines AS ( FROM json_array_elements($1::json) AS pipeline ), inserted_pipelines AS( INSERT INTO pipelines (amoID, accountID, name, isArchive, createdAt) - SELECT np.amoID, - np.accountID, - np.name, - np.isArchive, - np.createdAt - FROM new_pipelines np - ON CONFLICT (amoID, accountID) DO NOTHING - RETURNING * + SELECT np.amoID, + np.accountID, + np.name, + np.isArchive, + np.createdAt + FROM new_pipelines np + ON CONFLICT (amoID, accountID) DO NOTHING + RETURNING * ) SELECT np.* FROM new_pipelines np @@ -877,29 +875,29 @@ WITH user_data AS ( SELECT AmoID FROM accountsAmo WHERE accountsAmo.AccountID = $1 AND accountsAmo.Deleted = false ), new_fields AS ( SELECT (field->>'AmoID')::INT AS amoID, - COALESCE(field->>'Code', '')::varchar(255) AS code, - COALESCE(field->>'Name', '')::varchar(512) AS name, - CAST(field->>'Entity' AS entitytype) AS Entity, - COALESCE(field->>'Type', '')::fieldtype AS type, - CURRENT_TIMESTAMP AS createdAt + COALESCE(field->>'Code', '')::varchar(255) AS code, + COALESCE(field->>'Name', '')::varchar(512) AS name, + CAST(field->>'Entity' AS entitytype) AS Entity, + COALESCE(field->>'Type', '')::fieldtype AS type, + CURRENT_TIMESTAMP AS createdAt FROM json_array_elements($2::json) AS field ), inserted_fields AS( INSERT INTO fields (amoID, code, accountID, name, Entity, type, createdAt) - SELECT nf.amoID, - nf.code, - ud.AmoID, - nf.name, - nf.Entity, - nf.type, - nf.createdAt - FROM new_fields nf - JOIN user_data ud ON true - ON CONFLICT (amoID, accountID, entity) DO NOTHING - RETURNING * + SELECT nf.amoID, + nf.code, + ud.AmoID, + nf.name, + nf.Entity, + nf.type, + nf.createdAt + FROM new_fields nf + JOIN user_data ud ON true + ON CONFLICT (amoID, accountID, entity) DO NOTHING + RETURNING * ) SELECT nf.*,ud.AmoID FROM new_fields nf - JOIN user_data ud ON true + JOIN user_data ud ON true WHERE NOT EXISTS ( SELECT * FROM inserted_fields ins @@ -918,15 +916,15 @@ WITH new_steps AS ( FROM json_array_elements($1::json) AS step ), inserted_steps AS ( INSERT INTO steps (amoID, pipelineID, accountID, name, color, createdAt) - SELECT ns.amoID, - ns.pipelineID, - ns.accountID, - ns.name, - ns.color, - ns.createdAt - FROM new_steps ns - ON CONFLICT (amoID, accountID, PipelineID) DO NOTHING - RETURNING * + SELECT ns.amoID, + ns.pipelineID, + ns.accountID, + ns.name, + ns.color, + ns.createdAt + FROM new_steps ns + ON CONFLICT (amoID, accountID, PipelineID) DO NOTHING + RETURNING * ) SELECT ns.* FROM new_steps ns @@ -946,7 +944,7 @@ SELECT * FROM rules WHERE QuizID = $1 AND Deleted = false; INSERT INTO rules (AccountID, QuizID, PerformerID, PipelineID, StepID, FieldsRule,TagsToAdd) SELECT u.AmoID AS AccountID,$1 AS QuizID,$2 AS PerformerID,$3 AS PipelineID, $4 AS StepID,$5 AS FieldsRule,$6 AS TagsToAdd FROM accountsamo u WHERE u.AccountID = $7 AND u.Deleted = false - RETURNING id; +RETURNING id; -- name: ChangeQuizSettings :one UPDATE rules @@ -971,11 +969,11 @@ VALUES ($1, $2, $3, $4, $5, $6); -- name: GettingAmoUsersTrueResults :many SELECT a.quiz_id,a.id,a.result,a.question_id,a.content,a.session, - COALESCE((SELECT a2.utm - FROM answer a2 - WHERE a2.start = true AND a2.session = a.session - LIMIT 1), '{}'::jsonb) AS utm -,t.accesstoken,r.accountid,r.fieldsrule,r.tagstoadd,r.performerid,r.stepid,r.pipelineid,(SELECT u.name FROM usersAmo u WHERE u.AmoUserID = r.performerid AND u.deleted = false) AS performer_name,u.subdomain,u.accountid,u.driveurl + COALESCE((SELECT a2.utm + FROM answer a2 + WHERE a2.start = true AND a2.session = a.session + LIMIT 1), '{}'::jsonb) AS utm + ,t.accesstoken,r.accountid,r.fieldsrule,r.tagstoadd,r.performerid,r.stepid,r.pipelineid,(SELECT u.name FROM usersAmo u WHERE u.AmoUserID = r.performerid AND u.deleted = false) AS performer_name,u.subdomain,u.accountid,u.driveurl FROM answer a INNER JOIN quiz q ON a.quiz_id = q.id LEFT JOIN amoCRMStatuses s ON a.id = s.AnswerID @@ -1057,3 +1055,31 @@ INSERT INTO amoContact (AccountID, AmoID, Field) VALUES ($1, $2, $3) RETURNING A -- name: UpdateAmoContact :exec UPDATE amoContact SET Field = $1,AmoID=$3 WHERE ID = $2; + +-- name: CreateLeadTarget :one +INSERT INTO leadtarget (accountID,type,quizID,target,InviteLink) VALUES ($1,$2,$3,$4,$5) RETURNING *; + +-- name: DeleteLeadTarget :exec +UPDATE leadtarget SET deleted = true WHERE id = $1; + +-- name: UpdateLeadTarget :one +UPDATE leadtarget SET target = $1,InviteLink = $2 WHERE id = $3 AND deleted=false RETURNING *; + +-- name: GetLeadTarget :many +SELECT * FROM leadtarget WHERE accountID = $1 AND quizID = $2 AND deleted=false; + +-- name: CreateTgAccount :one +INSERT INTO tgAccounts (ApiID, ApiHash, PhoneNumber,Password, Status) +VALUES ($1, $2, $3, $4, $5) RETURNING id; + +-- name: GetAllTgAccounts :many +SELECT * FROM tgAccounts WHERE Deleted = false; + +-- name: UpdateStatusTg :exec +UPDATE tgAccounts SET Status = $1 WHERE id = $2; + +-- name: SoftDeleteTgAccount :exec +UPDATE tgAccounts SET Deleted = true WHERE id = $1; + +-- name: SearchIDByAppIDanAppHash :one +SELECT * FROM tgAccounts WHERE ApiID = $1 and ApiHash=$2 and Deleted = false; \ No newline at end of file diff --git a/dal/schema/000017_init.down.sql b/dal/schema/000017_init.down.sql new file mode 100644 index 0000000..1fe8abb --- /dev/null +++ b/dal/schema/000017_init.down.sql @@ -0,0 +1,10 @@ +ALTER TABLE account ADD column email varchar(50) NOT NULL default ''; + +DO $$ + BEGIN + IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leadtargettype') THEN + DROP TYPE LeadTargetType; + END IF; + END $$; + +DROP TABLE IF EXISTS leadtarget; \ No newline at end of file diff --git a/dal/schema/000017_init.up.sql b/dal/schema/000017_init.up.sql new file mode 100644 index 0000000..8da2b34 --- /dev/null +++ b/dal/schema/000017_init.up.sql @@ -0,0 +1,19 @@ +AlTER TABLE account DROP column email; + +DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'leadtargettype') THEN + CREATE TYPE LeadTargetType AS ENUM ('mail', 'telegram', 'whatsapp'); + END IF; + END $$; + +CREATE TABLE IF NOT EXISTS leadtarget( + ID BIGSERIAL UNIQUE NOT NULL PRIMARY KEY, + AccountID varchar(30) NOT NULL, + Type LeadTargetType NOT NULL, + QuizID integer NOT NULL DEFAULT 0, + Target text NOT NULL, + InviteLink text NOT NULL DEFAULT '', + Deleted boolean NOT NULL DEFAULT false, + CreatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +); diff --git a/dal/schema/000018_init.down.sql b/dal/schema/000018_init.down.sql new file mode 100644 index 0000000..749dbb0 --- /dev/null +++ b/dal/schema/000018_init.down.sql @@ -0,0 +1,10 @@ +DROP TABLE IF EXISTS tgAccounts; + +DO $$ + BEGIN + IF EXISTS (SELECT 1 FROM pg_type WHERE typname = 'tgAccountStatus') THEN + DROP TYPE TgAccountStatus; + END IF; + END $$; + +DROP INDEX IF EXISTS idx_apiid_apihash; \ No newline at end of file diff --git a/dal/schema/000018_init.up.sql b/dal/schema/000018_init.up.sql new file mode 100644 index 0000000..e165366 --- /dev/null +++ b/dal/schema/000018_init.up.sql @@ -0,0 +1,19 @@ +DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'tgAccountStatus') THEN + CREATE TYPE TgAccountStatus AS ENUM ('active', 'inactive', 'ban'); + END IF; + END $$; + +CREATE TABLE IF NOT EXISTS tgAccounts ( + id bigserial primary key , + ApiID integer not null, + ApiHash text not null , + PhoneNumber text not null , + Password text not null , + Status TgAccountStatus not null, + Deleted bool not null default false, + CreatedAt timestamp not null default current_timestamp +); + +CREATE UNIQUE INDEX idx_apiid_apihash ON tgAccounts (ApiID, ApiHash) WHERE Deleted = false; diff --git a/dal/schema/000019_init.down.sql b/dal/schema/000019_init.down.sql new file mode 100644 index 0000000..e76faa2 --- /dev/null +++ b/dal/schema/000019_init.down.sql @@ -0,0 +1,11 @@ +ALTER TABLE account +ALTER COLUMN user_id DROP NOT NULL, +ALTER COLUMN created_at DROP NOT NULL, +ALTER COLUMN deleted DROP NOT NULL; + +ALTER TABLE privileges +ALTER COLUMN privilegeID DROP NOT NULL, +ALTER COLUMN account_id DROP NOT NULL, +ALTER COLUMN privilege_name DROP NOT NULL, +ALTER COLUMN amount DROP NOT NULL, +ALTER COLUMN created_at DROP NOT NULL; \ No newline at end of file diff --git a/dal/schema/000019_init.up.sql b/dal/schema/000019_init.up.sql new file mode 100644 index 0000000..ac84b67 --- /dev/null +++ b/dal/schema/000019_init.up.sql @@ -0,0 +1,11 @@ +ALTER TABLE account +ALTER COLUMN user_id SET NOT NULL, +ALTER COLUMN created_at SET NOT NULL, +ALTER COLUMN deleted SET NOT NULL; + +ALTER TABLE privileges +ALTER COLUMN privilegeID SET NOT NULL, +ALTER COLUMN account_id SET NOT NULL, +ALTER COLUMN privilege_name SET NOT NULL, +ALTER COLUMN amount SET NOT NULL, +ALTER COLUMN created_at SET NOT NULL; \ No newline at end of file diff --git a/dal/sqlcgen/models.go b/dal/sqlcgen/models.go index 90a4ade..c9fbf05 100644 --- a/dal/sqlcgen/models.go +++ b/dal/sqlcgen/models.go @@ -13,11 +13,10 @@ import ( ) type Account struct { - ID uuid.UUID `db:"id" json:"id"` - UserID sql.NullString `db:"user_id" json:"user_id"` - Email sql.NullString `db:"email" json:"email"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - Deleted sql.NullBool `db:"deleted" json:"deleted"` + ID uuid.UUID `db:"id" json:"id"` + UserID string `db:"user_id" json:"user_id"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + Deleted bool `db:"deleted" json:"deleted"` } type Accountsamo struct { @@ -81,6 +80,17 @@ type Field struct { Createdat sql.NullTime `db:"createdat" json:"createdat"` } +type Leadtarget struct { + ID int64 `db:"id" json:"id"` + Accountid string `db:"accountid" json:"accountid"` + Type interface{} `db:"type" json:"type"` + Quizid int32 `db:"quizid" json:"quizid"` + Target string `db:"target" json:"target"` + Invitelink string `db:"invitelink" json:"invitelink"` + Deleted bool `db:"deleted" json:"deleted"` + Createdat time.Time `db:"createdat" json:"createdat"` +} + type Pipeline struct { ID int64 `db:"id" json:"id"` Amoid int32 `db:"amoid" json:"amoid"` @@ -92,12 +102,12 @@ type Pipeline struct { } type Privilege struct { - ID int32 `db:"id" json:"id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - AccountID uuid.NullUUID `db:"account_id" json:"account_id"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` + ID int32 `db:"id" json:"id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + AccountID uuid.UUID `db:"account_id" json:"account_id"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` } type Question struct { @@ -183,6 +193,17 @@ type Tag struct { Createdat sql.NullTime `db:"createdat" json:"createdat"` } +type Tgaccount struct { + ID int64 `db:"id" json:"id"` + Apiid int32 `db:"apiid" json:"apiid"` + Apihash string `db:"apihash" json:"apihash"` + Phonenumber string `db:"phonenumber" json:"phonenumber"` + Password string `db:"password" json:"password"` + Status interface{} `db:"status" json:"status"` + Deleted bool `db:"deleted" json:"deleted"` + Createdat time.Time `db:"createdat" json:"createdat"` +} + type Token struct { Accountid string `db:"accountid" json:"accountid"` Refreshtoken string `db:"refreshtoken" json:"refreshtoken"` diff --git a/dal/sqlcgen/queries.sql.go b/dal/sqlcgen/queries.sql.go index cadc777..1cbf320 100644 --- a/dal/sqlcgen/queries.sql.go +++ b/dal/sqlcgen/queries.sql.go @@ -25,22 +25,15 @@ type AccountPaginationParams struct { Offset int32 `db:"offset" json:"offset"` } -type AccountPaginationRow struct { - ID uuid.UUID `db:"id" json:"id"` - UserID sql.NullString `db:"user_id" json:"user_id"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - Deleted sql.NullBool `db:"deleted" json:"deleted"` -} - -func (q *Queries) AccountPagination(ctx context.Context, arg AccountPaginationParams) ([]AccountPaginationRow, error) { +func (q *Queries) AccountPagination(ctx context.Context, arg AccountPaginationParams) ([]Account, error) { rows, err := q.db.QueryContext(ctx, accountPagination, arg.Limit, arg.Offset) if err != nil { return nil, err } defer rows.Close() - var items []AccountPaginationRow + var items []Account for rows.Next() { - var i AccountPaginationRow + var i Account if err := rows.Scan( &i.ID, &i.UserID, @@ -180,9 +173,9 @@ WHERE privilege_name = $2 ` type CheckAndAddDefaultParams struct { - Amount sql.NullInt32 `db:"amount" json:"amount"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount_2 sql.NullInt32 `db:"amount_2" json:"amount_2"` + Amount int32 `db:"amount" json:"amount"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount_2 int32 `db:"amount_2" json:"amount_2"` } func (q *Queries) CheckAndAddDefault(ctx context.Context, arg CheckAndAddDefaultParams) error { @@ -213,29 +206,29 @@ WITH user_data AS ( SELECT AmoID FROM accountsAmo WHERE accountsAmo.AccountID = $1 AND accountsAmo.Deleted = false ), new_fields AS ( SELECT (field->>'AmoID')::INT AS amoID, - COALESCE(field->>'Code', '')::varchar(255) AS code, - COALESCE(field->>'Name', '')::varchar(512) AS name, - CAST(field->>'Entity' AS entitytype) AS Entity, - COALESCE(field->>'Type', '')::fieldtype AS type, - CURRENT_TIMESTAMP AS createdAt + COALESCE(field->>'Code', '')::varchar(255) AS code, + COALESCE(field->>'Name', '')::varchar(512) AS name, + CAST(field->>'Entity' AS entitytype) AS Entity, + COALESCE(field->>'Type', '')::fieldtype AS type, + CURRENT_TIMESTAMP AS createdAt FROM json_array_elements($2::json) AS field ), inserted_fields AS( INSERT INTO fields (amoID, code, accountID, name, Entity, type, createdAt) - SELECT nf.amoID, - nf.code, - ud.AmoID, - nf.name, - nf.Entity, - nf.type, - nf.createdAt - FROM new_fields nf - JOIN user_data ud ON true - ON CONFLICT (amoID, accountID, entity) DO NOTHING - RETURNING id, amoid, code, accountid, name, entity, type, deleted, createdat + SELECT nf.amoID, + nf.code, + ud.AmoID, + nf.name, + nf.Entity, + nf.type, + nf.createdAt + FROM new_fields nf + JOIN user_data ud ON true + ON CONFLICT (amoID, accountID, entity) DO NOTHING + RETURNING id, amoid, code, accountid, name, entity, type, deleted, createdat ) SELECT nf.amoid, nf.code, nf.name, nf.entity, nf.type, nf.createdat,ud.AmoID FROM new_fields nf - JOIN user_data ud ON true + JOIN user_data ud ON true WHERE NOT EXISTS ( SELECT id, ins.amoid, code, accountid, name, entity, type, deleted, createdat, ud.amoid FROM inserted_fields ins @@ -300,14 +293,14 @@ WITH new_pipelines AS ( FROM json_array_elements($1::json) AS pipeline ), inserted_pipelines AS( INSERT INTO pipelines (amoID, accountID, name, isArchive, createdAt) - SELECT np.amoID, - np.accountID, - np.name, - np.isArchive, - np.createdAt - FROM new_pipelines np - ON CONFLICT (amoID, accountID) DO NOTHING - RETURNING id, amoid, accountid, name, isarchive, deleted, createdat + SELECT np.amoID, + np.accountID, + np.name, + np.isArchive, + np.createdAt + FROM new_pipelines np + ON CONFLICT (amoID, accountID) DO NOTHING + RETURNING id, amoid, accountid, name, isarchive, deleted, createdat ) SELECT np.amoid, np.accountid, np.name, np.isarchive, np.createdat FROM new_pipelines np @@ -412,15 +405,15 @@ WITH new_steps AS ( FROM json_array_elements($1::json) AS step ), inserted_steps AS ( INSERT INTO steps (amoID, pipelineID, accountID, name, color, createdAt) - SELECT ns.amoID, - ns.pipelineID, - ns.accountID, - ns.name, - ns.color, - ns.createdAt - FROM new_steps ns - ON CONFLICT (amoID, accountID, PipelineID) DO NOTHING - RETURNING id, amoid, pipelineid, accountid, name, color, deleted, createdat + SELECT ns.amoID, + ns.pipelineID, + ns.accountID, + ns.name, + ns.color, + ns.createdAt + FROM new_steps ns + ON CONFLICT (amoID, accountID, PipelineID) DO NOTHING + RETURNING id, amoid, pipelineid, accountid, name, color, deleted, createdat ) SELECT ns.amoid, ns.pipelineid, ns.accountid, ns.name, ns.color, ns.createdat FROM new_steps ns @@ -494,7 +487,7 @@ WITH user_data AS ( ) SELECT nt.amoid, nt.entity, nt.name, nt.color,ud.AmoID FROM new_tags nt - JOIN user_data ud ON true + JOIN user_data ud ON true WHERE NOT EXISTS ( SELECT id, ins.amoid, accountid, entity, name, color, deleted, createdat, ud.amoid FROM inserted_tags ins @@ -553,7 +546,7 @@ INSERT INTO question( SELECT $1, title, description, questiontype, required, page, content, version, parent_ids FROM question WHERE question.id=$2 - RETURNING question.id, quiz_id, created_at, updated_at +RETURNING question.id, quiz_id, created_at, updated_at ` type CopyQuestionParams struct { @@ -585,12 +578,12 @@ INSERT INTO question ( quiz_id, title, description, questiontype, required, page, content, version, parent_ids, created_at, updated_at ) -SELECT +SELECT $2, title, description, questiontype, required, page, content, version, parent_ids, created_at, updated_at -FROM +FROM question -WHERE +WHERE question.quiz_id = $1 AND deleted = false ` @@ -612,7 +605,7 @@ INSERT INTO quiz( SELECT accountid, archived,fingerprinting,repeatable,note_prevented,mail_notifications,unique_answers,name,description,config, status,limit_answers,due_to,time_of_passing,pausable,version,version_comment,parent_ids,questions_count, super, group_id FROM quiz WHERE quiz.id=$1 AND quiz.accountId=$2 - RETURNING id, qid,created_at, updated_at +RETURNING id, qid,created_at, updated_at ` type CopyQuizParams struct { @@ -658,22 +651,20 @@ func (q *Queries) CopyQuizQuestions(ctx context.Context, arg CopyQuizQuestionsPa } const createAccount = `-- name: CreateAccount :one -INSERT INTO account (id, user_id, email, created_at, deleted) VALUES ($1, $2, $3, $4, $5) RETURNING id, user_id, email, created_at, deleted +INSERT INTO account (id, user_id, created_at, deleted) VALUES ($1, $2, $3, $4) RETURNING id, user_id, created_at, deleted ` type CreateAccountParams struct { - ID uuid.UUID `db:"id" json:"id"` - UserID sql.NullString `db:"user_id" json:"user_id"` - Email sql.NullString `db:"email" json:"email"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - Deleted sql.NullBool `db:"deleted" json:"deleted"` + ID uuid.UUID `db:"id" json:"id"` + UserID string `db:"user_id" json:"user_id"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + Deleted bool `db:"deleted" json:"deleted"` } func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (Account, error) { row := q.db.QueryRowContext(ctx, createAccount, arg.ID, arg.UserID, - arg.Email, arg.CreatedAt, arg.Deleted, ) @@ -681,7 +672,6 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A err := row.Scan( &i.ID, &i.UserID, - &i.Email, &i.CreatedAt, &i.Deleted, ) @@ -716,6 +706,66 @@ func (q *Queries) CreateAmoAccount(ctx context.Context, arg CreateAmoAccountPara return err } +const createLeadTarget = `-- name: CreateLeadTarget :one +INSERT INTO leadtarget (accountID,type,quizID,target,InviteLink) VALUES ($1,$2,$3,$4,$5) RETURNING id, accountid, type, quizid, target, invitelink, deleted, createdat +` + +type CreateLeadTargetParams struct { + Accountid string `db:"accountid" json:"accountid"` + Type interface{} `db:"type" json:"type"` + Quizid int32 `db:"quizid" json:"quizid"` + Target string `db:"target" json:"target"` + Invitelink string `db:"invitelink" json:"invitelink"` +} + +func (q *Queries) CreateLeadTarget(ctx context.Context, arg CreateLeadTargetParams) (Leadtarget, error) { + row := q.db.QueryRowContext(ctx, createLeadTarget, + arg.Accountid, + arg.Type, + arg.Quizid, + arg.Target, + arg.Invitelink, + ) + var i Leadtarget + err := row.Scan( + &i.ID, + &i.Accountid, + &i.Type, + &i.Quizid, + &i.Target, + &i.Invitelink, + &i.Deleted, + &i.Createdat, + ) + return i, err +} + +const createTgAccount = `-- name: CreateTgAccount :one +INSERT INTO tgAccounts (ApiID, ApiHash, PhoneNumber,Password, Status) +VALUES ($1, $2, $3, $4, $5) RETURNING id +` + +type CreateTgAccountParams struct { + Apiid int32 `db:"apiid" json:"apiid"` + Apihash string `db:"apihash" json:"apihash"` + Phonenumber string `db:"phonenumber" json:"phonenumber"` + Password string `db:"password" json:"password"` + Status interface{} `db:"status" json:"status"` +} + +func (q *Queries) CreateTgAccount(ctx context.Context, arg CreateTgAccountParams) (int64, error) { + row := q.db.QueryRowContext(ctx, createTgAccount, + arg.Apiid, + arg.Apihash, + arg.Phonenumber, + arg.Password, + arg.Status, + ) + var id int64 + err := row.Scan(&id) + return id, err +} + const createWebHook = `-- name: CreateWebHook :exec INSERT INTO tokens (AccountID, RefreshToken, AccessToken, AuthCode, Expiration, CreatedAt) VALUES ($1, $2, $3, $4, $5, $6) @@ -749,8 +799,8 @@ RETURNING p.id, p.privilegeID, p.account_id, p.privilege_name, p.amount, p.creat ` type DecrementManualParams struct { - UserID sql.NullString `db:"user_id" json:"user_id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` + UserID string `db:"user_id" json:"user_id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` } func (q *Queries) DecrementManual(ctx context.Context, arg DecrementManualParams) (Privilege, error) { @@ -785,6 +835,15 @@ func (q *Queries) DeleteFields(ctx context.Context, dollar_1 []int64) error { return err } +const deleteLeadTarget = `-- name: DeleteLeadTarget :exec +UPDATE leadtarget SET deleted = true WHERE id = $1 +` + +func (q *Queries) DeleteLeadTarget(ctx context.Context, id int64) error { + _, err := q.db.ExecContext(ctx, deleteLeadTarget, id) + return err +} + const deletePipelines = `-- name: DeletePipelines :exec UPDATE pipelines SET Deleted = true WHERE ID = ANY($1::bigint[]) ` @@ -798,7 +857,7 @@ const deletePrivilegeByAccID = `-- name: DeletePrivilegeByAccID :exec DELETE FROM privileges WHERE account_id = $1 ` -func (q *Queries) DeletePrivilegeByAccID(ctx context.Context, accountID uuid.NullUUID) error { +func (q *Queries) DeletePrivilegeByAccID(ctx context.Context, accountID uuid.UUID) error { _, err := q.db.ExecContext(ctx, deletePrivilegeByAccID, accountID) return err } @@ -1031,7 +1090,7 @@ INSERT INTO question( SELECT quiz_id, title, description, questiontype, required, page, content, version, parent_ids FROM question WHERE question.id=$1 - RETURNING question.id, quiz_id, created_at, updated_at +RETURNING question.id, quiz_id, created_at, updated_at ` type DuplicateQuestionRow struct { @@ -1058,13 +1117,13 @@ WITH TimeBucket AS ( SELECT date_trunc('hour', timestamp_bucket)::TIMESTAMP AS time_interval_start, COALESCE(LEAD( - date_trunc('hour', timestamp_bucket)::TIMESTAMP - ) OVER (ORDER BY timestamp_bucket), NOW()) AS time_interval_end + date_trunc('hour', timestamp_bucket)::TIMESTAMP + ) OVER (ORDER BY timestamp_bucket), NOW()) AS time_interval_end FROM - generate_series(TO_TIMESTAMP($1), TO_TIMESTAMP($2), CASE - WHEN EXTRACT(epoch FROM TO_TIMESTAMP($2)) - EXTRACT(epoch FROM TO_TIMESTAMP($1)) > 172800 THEN '1 day'::interval - ELSE '1 hour'::interval - END) AS timestamp_bucket + generate_series(TO_TIMESTAMP($1), TO_TIMESTAMP($2), CASE + WHEN EXTRACT(epoch FROM TO_TIMESTAMP($2)) - EXTRACT(epoch FROM TO_TIMESTAMP($1)) > 172800 THEN '1 day'::interval + ELSE '1 hour'::interval + END) AS timestamp_bucket ), OpenStats AS ( SELECT @@ -1145,7 +1204,7 @@ SELECT CASE WHEN COALESCE(os.open_count, 0) > 0 THEN COALESCE(rs.true_result_count, 0)::float / COALESCE(os.open_count, 0)::float ELSE 0 - END::float AS conversion, + END::float AS conversion, COALESCE(at.avg_time, 0) AS avg_time FROM TimeBucket tb @@ -1207,7 +1266,6 @@ const getAccAndPrivilegeByEmail = `-- name: GetAccAndPrivilegeByEmail :one SELECT a.id, a.user_id, - a.email, a.created_at, COALESCE(p.ID,0), coalesce(p.privilegeid,''), @@ -1221,23 +1279,21 @@ WHERE ` type GetAccAndPrivilegeByEmailRow struct { - ID uuid.UUID `db:"id" json:"id"` - UserID sql.NullString `db:"user_id" json:"user_id"` - Email sql.NullString `db:"email" json:"email"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - ID_2 int32 `db:"id_2" json:"id_2"` - Privilegeid string `db:"privilegeid" json:"privilegeid"` - Amount int32 `db:"amount" json:"amount"` - CreatedAt_2 sql.NullTime `db:"created_at_2" json:"created_at_2"` + ID uuid.UUID `db:"id" json:"id"` + UserID string `db:"user_id" json:"user_id"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + ID_2 int32 `db:"id_2" json:"id_2"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt_2 time.Time `db:"created_at_2" json:"created_at_2"` } -func (q *Queries) GetAccAndPrivilegeByEmail(ctx context.Context, userID sql.NullString) (GetAccAndPrivilegeByEmailRow, error) { +func (q *Queries) GetAccAndPrivilegeByEmail(ctx context.Context, userID string) (GetAccAndPrivilegeByEmailRow, error) { row := q.db.QueryRowContext(ctx, getAccAndPrivilegeByEmail, userID) var i GetAccAndPrivilegeByEmailRow err := row.Scan( &i.ID, &i.UserID, - &i.Email, &i.CreatedAt, &i.ID_2, &i.Privilegeid, @@ -1259,18 +1315,18 @@ WHERE a.user_id = $1 ` type GetAccountWithPrivilegesRow struct { - ID uuid.UUID `db:"id" json:"id"` - UserID sql.NullString `db:"user_id" json:"user_id"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - Deleted sql.NullBool `db:"deleted" json:"deleted"` - PrivilegeID int32 `db:"privilege_id" json:"privilege_id"` - Privilegeid string `db:"privilegeid" json:"privilegeid"` - PrivilegeName string `db:"privilege_name" json:"privilege_name"` - Amount int32 `db:"amount" json:"amount"` - PrivilegeCreatedAt sql.NullTime `db:"privilege_created_at" json:"privilege_created_at"` + ID uuid.UUID `db:"id" json:"id"` + UserID string `db:"user_id" json:"user_id"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + Deleted bool `db:"deleted" json:"deleted"` + PrivilegeID int32 `db:"privilege_id" json:"privilege_id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + PrivilegeCreatedAt time.Time `db:"privilege_created_at" json:"privilege_created_at"` } -func (q *Queries) GetAccountWithPrivileges(ctx context.Context, userID sql.NullString) ([]GetAccountWithPrivilegesRow, error) { +func (q *Queries) GetAccountWithPrivileges(ctx context.Context, userID string) ([]GetAccountWithPrivilegesRow, error) { rows, err := q.db.QueryContext(ctx, getAccountWithPrivileges, userID) if err != nil { return nil, err @@ -1394,6 +1450,42 @@ func (q *Queries) GetAllCompanyUsers(ctx context.Context, amoid int32) ([]Usersa return items, nil } +const getAllTgAccounts = `-- name: GetAllTgAccounts :many +SELECT id, apiid, apihash, phonenumber, password, status, deleted, createdat FROM tgAccounts WHERE Deleted = false +` + +func (q *Queries) GetAllTgAccounts(ctx context.Context) ([]Tgaccount, error) { + rows, err := q.db.QueryContext(ctx, getAllTgAccounts) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Tgaccount + for rows.Next() { + var i Tgaccount + if err := rows.Scan( + &i.ID, + &i.Apiid, + &i.Apihash, + &i.Phonenumber, + &i.Password, + &i.Status, + &i.Deleted, + &i.Createdat, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const getAllTokens = `-- name: GetAllTokens :many SELECT accountid, refreshtoken, accesstoken, authcode, expiration, createdat FROM tokens ` @@ -1498,15 +1590,15 @@ WHERE p.amount = 0 ` type GetExpiredCountPrivilegeRow struct { - ID int32 `db:"id" json:"id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - UserID sql.NullString `db:"user_id" json:"user_id"` + ID int32 `db:"id" json:"id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + UserID string `db:"user_id" json:"user_id"` } -func (q *Queries) GetExpiredCountPrivilege(ctx context.Context, privilegeid sql.NullString) ([]GetExpiredCountPrivilegeRow, error) { +func (q *Queries) GetExpiredCountPrivilege(ctx context.Context, privilegeid string) ([]GetExpiredCountPrivilegeRow, error) { rows, err := q.db.QueryContext(ctx, getExpiredCountPrivilege, privilegeid) if err != nil { return nil, err @@ -1545,15 +1637,15 @@ WHERE p.created_at + p.amount * interval '1 day' < NOW() ` type GetExpiredDayPrivilegeRow struct { - ID int32 `db:"id" json:"id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - UserID sql.NullString `db:"user_id" json:"user_id"` + ID int32 `db:"id" json:"id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + UserID string `db:"user_id" json:"user_id"` } -func (q *Queries) GetExpiredDayPrivilege(ctx context.Context, privilegeid sql.NullString) ([]GetExpiredDayPrivilegeRow, error) { +func (q *Queries) GetExpiredDayPrivilege(ctx context.Context, privilegeid string) ([]GetExpiredDayPrivilegeRow, error) { rows, err := q.db.QueryContext(ctx, getExpiredDayPrivilege, privilegeid) if err != nil { return nil, err @@ -1667,6 +1759,47 @@ func (q *Queries) GetFieldsWithPagination(ctx context.Context, arg GetFieldsWith return items, nil } +const getLeadTarget = `-- name: GetLeadTarget :many +SELECT id, accountid, type, quizid, target, invitelink, deleted, createdat FROM leadtarget WHERE accountID = $1 AND quizID = $2 AND deleted=false +` + +type GetLeadTargetParams struct { + Accountid string `db:"accountid" json:"accountid"` + Quizid int32 `db:"quizid" json:"quizid"` +} + +func (q *Queries) GetLeadTarget(ctx context.Context, arg GetLeadTargetParams) ([]Leadtarget, error) { + rows, err := q.db.QueryContext(ctx, getLeadTarget, arg.Accountid, arg.Quizid) + if err != nil { + return nil, err + } + defer rows.Close() + var items []Leadtarget + for rows.Next() { + var i Leadtarget + if err := rows.Scan( + &i.ID, + &i.Accountid, + &i.Type, + &i.Quizid, + &i.Target, + &i.Invitelink, + &i.Deleted, + &i.Createdat, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const getListCreatedQuizzes = `-- name: GetListCreatedQuizzes :many SELECT id FROM quiz @@ -1787,14 +1920,14 @@ SELECT id,privilegeID,privilege_name,amount, created_at FROM privileges WHERE ac ` type GetPrivilegesByAccountIDRow struct { - ID int32 `db:"id" json:"id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` + ID int32 `db:"id" json:"id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` } -func (q *Queries) GetPrivilegesByAccountID(ctx context.Context, accountID uuid.NullUUID) ([]GetPrivilegesByAccountIDRow, error) { +func (q *Queries) GetPrivilegesByAccountID(ctx context.Context, accountID uuid.UUID) ([]GetPrivilegesByAccountIDRow, error) { rows, err := q.db.QueryContext(ctx, getPrivilegesByAccountID, accountID) if err != nil { return nil, err @@ -1828,14 +1961,14 @@ SELECT p.id,p.privilegeID,p.privilege_name,p.amount, p.created_at FROM privilege ` type GetPrivilegesByAccountIDWCRow struct { - ID int32 `db:"id" json:"id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` + ID int32 `db:"id" json:"id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` } -func (q *Queries) GetPrivilegesByAccountIDWC(ctx context.Context, userID sql.NullString) ([]GetPrivilegesByAccountIDWCRow, error) { +func (q *Queries) GetPrivilegesByAccountIDWC(ctx context.Context, userID string) ([]GetPrivilegesByAccountIDWCRow, error) { rows, err := q.db.QueryContext(ctx, getPrivilegesByAccountIDWC, userID) if err != nil { return nil, err @@ -1871,7 +2004,6 @@ SELECT p.amount, p.created_at, a.id, - a.email, qz.config FROM privileges AS p @@ -1882,12 +2014,11 @@ WHERE ` type GetPrivilegesQuizAccountRow struct { - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` ID uuid.UUID `db:"id" json:"id"` - Email sql.NullString `db:"email" json:"email"` Config sql.NullString `db:"config" json:"config"` } @@ -1906,7 +2037,6 @@ func (q *Queries) GetPrivilegesQuizAccount(ctx context.Context, id int64) ([]Get &i.Amount, &i.CreatedAt, &i.ID, - &i.Email, &i.Config, ); err != nil { return nil, err @@ -2773,11 +2903,11 @@ func (q *Queries) GetUsersWithPagination(ctx context.Context, arg GetUsersWithPa const gettingAmoUsersTrueResults = `-- name: GettingAmoUsersTrueResults :many SELECT a.quiz_id,a.id,a.result,a.question_id,a.content,a.session, - COALESCE((SELECT a2.utm - FROM answer a2 - WHERE a2.start = true AND a2.session = a.session - LIMIT 1), '{}'::jsonb) AS utm -,t.accesstoken,r.accountid,r.fieldsrule,r.tagstoadd,r.performerid,r.stepid,r.pipelineid,(SELECT u.name FROM usersAmo u WHERE u.AmoUserID = r.performerid AND u.deleted = false) AS performer_name,u.subdomain,u.accountid,u.driveurl + COALESCE((SELECT a2.utm + FROM answer a2 + WHERE a2.start = true AND a2.session = a.session + LIMIT 1), '{}'::jsonb) AS utm + ,t.accesstoken,r.accountid,r.fieldsrule,r.tagstoadd,r.performerid,r.stepid,r.pipelineid,(SELECT u.name FROM usersAmo u WHERE u.AmoUserID = r.performerid AND u.deleted = false) AS performer_name,u.subdomain,u.accountid,u.driveurl FROM answer a INNER JOIN quiz q ON a.quiz_id = q.id LEFT JOIN amoCRMStatuses s ON a.id = s.AnswerID @@ -2955,11 +3085,11 @@ INSERT INTO privileges (privilegeID, account_id, privilege_name, amount, created ` type InsertPrivilegeParams struct { - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` - AccountID uuid.NullUUID `db:"account_id" json:"account_id"` - PrivilegeName sql.NullString `db:"privilege_name" json:"privilege_name"` - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` + AccountID uuid.UUID `db:"account_id" json:"account_id"` + PrivilegeName string `db:"privilege_name" json:"privilege_name"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` } func (q *Queries) InsertPrivilege(ctx context.Context, arg InsertPrivilegeParams) error { @@ -2986,7 +3116,7 @@ INSERT INTO question ( updated_at ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) - RETURNING id, created_at, updated_at +RETURNING id, created_at, updated_at ` type InsertQuestionParams struct { @@ -3046,7 +3176,7 @@ INSERT INTO quiz (accountid, qid ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19) - RETURNING id, created_at, updated_at, qid +RETURNING id, created_at, updated_at, qid ` type InsertQuizParams struct { @@ -3118,7 +3248,7 @@ INSERT INTO question( SELECT quiz_id, title, description, questiontype, required, page, content, version, parent_ids, true as deleted FROM question WHERE question.id=$1 - RETURNING question.id, quiz_id, parent_ids +RETURNING question.id, quiz_id, parent_ids ` type MoveToHistoryRow struct { @@ -3142,7 +3272,7 @@ INSERT INTO quiz(deleted, SELECT true as deleted, accountid, archived,fingerprinting,repeatable,note_prevented,mail_notifications,unique_answers,name,description,config, status,limit_answers,due_to,time_of_passing,pausable,version,version_comment,parent_ids,questions_count,answers_count,average_time_passing, super, group_id FROM quiz WHERE quiz.id=$1 AND quiz.accountid=$2 - RETURNING quiz.id, qid, parent_ids +RETURNING quiz.id, qid, parent_ids ` type MoveToHistoryQuizParams struct { @@ -3166,10 +3296,10 @@ func (q *Queries) MoveToHistoryQuiz(ctx context.Context, arg MoveToHistoryQuizPa const questionsStatistics = `-- name: QuestionsStatistics :many WITH Funnel AS ( SELECT - COUNT(DISTINCT a.session) FILTER (WHERE a.start = FALSE) AS count_start_false, - COUNT(DISTINCT a.session) FILTER (WHERE a.start = TRUE) AS count_start_true, - COUNT(DISTINCT CASE WHEN a.result = FALSE AND qid_true_result IS NOT NULL THEN a.session END) AS count_f_result_with_t_question, - COUNT(DISTINCT a.session) FILTER (WHERE a.result = TRUE) AS count_t_result + COUNT(DISTINCT a.session) FILTER (WHERE a.start = FALSE) AS count_start_false, + COUNT(DISTINCT a.session) FILTER (WHERE a.start = TRUE) AS count_start_true, + COUNT(DISTINCT CASE WHEN a.result = FALSE AND qid_true_result IS NOT NULL THEN a.session END) AS count_f_result_with_t_question, + COUNT(DISTINCT a.session) FILTER (WHERE a.result = TRUE) AS count_t_result FROM answer a LEFT JOIN ( @@ -3184,23 +3314,23 @@ WITH Funnel AS ( AND a.created_at <= TO_TIMESTAMP($3) ), Results AS ( - SELECT - COALESCE(q.title, '') AS question_title, - COUNT(*) AS total_answers, - CAST(COUNT(*) * 100.0 / NULLIF(SUM(COUNT(*)) FILTER (WHERE a.result = TRUE) OVER (PARTITION BY a.quiz_id), 0) AS FLOAT8) AS percentage - FROM - question q - JOIN answer a ON q.id = a.question_id - WHERE - a.quiz_id = $1 - AND a.created_at >= TO_TIMESTAMP($2) - AND a.created_at <= TO_TIMESTAMP($3) - AND a.result = TRUE - GROUP BY - q.title, a.quiz_id, a.result - HAVING - COUNT(*) >= 1 - ), + SELECT + COALESCE(q.title, '') AS question_title, + COUNT(*) AS total_answers, + CAST(COUNT(*) * 100.0 / NULLIF(SUM(COUNT(*)) FILTER (WHERE a.result = TRUE) OVER (PARTITION BY a.quiz_id), 0) AS FLOAT8) AS percentage + FROM + question q + JOIN answer a ON q.id = a.question_id + WHERE + a.quiz_id = $1 + AND a.created_at >= TO_TIMESTAMP($2) + AND a.created_at <= TO_TIMESTAMP($3) + AND a.result = TRUE + GROUP BY + q.title, a.quiz_id, a.result + HAVING + COUNT(*) >= 1 + ), LastContent AS ( SELECT a.question_id, @@ -3216,35 +3346,35 @@ WITH Funnel AS ( answer WHERE quiz_id = $1 - AND start != true + AND start != true AND created_at >= TO_TIMESTAMP($2) AND created_at <= TO_TIMESTAMP($3) GROUP BY - question_id, session + question_id, session ) AS last_created_at_one_session ON a.session = last_created_at_one_session.session AND a.question_id = last_created_at_one_session.question_id AND a.created_at = last_created_at_one_session.last_created_at ), Questions AS ( - SELECT - q.title AS question_title, - q.page AS question_page, - lc.last_answer_content AS answer_content, - CAST( - COUNT(CASE WHEN a.result = FALSE THEN 1 END) * 100.0 / NULLIF(SUM(COUNT(CASE WHEN a.result = FALSE THEN 1 END)) OVER (PARTITION BY q.id), 0) AS FLOAT8 - ) AS percentage - FROM - question q - JOIN LastContent lc ON q.id = lc.question_id - JOIN answer a ON q.id = a.question_id - WHERE - a.quiz_id = $1 - AND a.start != true - AND a.created_at >= TO_TIMESTAMP($2) - AND a.created_at <= TO_TIMESTAMP($3) - GROUP BY - q.id, q.title, lc.last_answer_content - HAVING - COUNT(*) >= 1 -) + SELECT + q.title AS question_title, + q.page AS question_page, + lc.last_answer_content AS answer_content, + CAST( + COUNT(CASE WHEN a.result = FALSE THEN 1 END) * 100.0 / NULLIF(SUM(COUNT(CASE WHEN a.result = FALSE THEN 1 END)) OVER (PARTITION BY q.id), 0) AS FLOAT8 + ) AS percentage + FROM + question q + JOIN LastContent lc ON q.id = lc.question_id + JOIN answer a ON q.id = a.question_id + WHERE + a.quiz_id = $1 + AND a.start != true + AND a.created_at >= TO_TIMESTAMP($2) + AND a.created_at <= TO_TIMESTAMP($3) + GROUP BY + q.id, q.title, lc.last_answer_content + HAVING + COUNT(*) >= 1 + ) SELECT Funnel.count_start_false, Funnel.count_start_true, @@ -3258,8 +3388,8 @@ SELECT COALESCE(Questions.percentage, 0) AS questions_percentage FROM Funnel - LEFT JOIN Results ON true - LEFT JOIN Questions ON Questions.percentage >= 1 + LEFT JOIN Results ON true + LEFT JOIN Questions ON Questions.percentage >= 1 ` type QuestionsStatisticsParams struct { @@ -3316,18 +3446,18 @@ func (q *Queries) QuestionsStatistics(ctx context.Context, arg QuestionsStatisti } const quizCopyQid = `-- name: QuizCopyQid :one - INSERT INTO quiz ( - accountid, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, - status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id - ) - SELECT - $2, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, - status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id - FROM - quiz as q - WHERE - q.qid = $1 - RETURNING (select id from quiz where qid = $1),id, qid +INSERT INTO quiz ( + accountid, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, + status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id +) +SELECT + $2, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, name, description, config, + status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, questions_count, answers_count, average_time_passing, super, group_id +FROM + quiz as q +WHERE + q.qid = $1 +RETURNING (select id from quiz where qid = $1),id, qid ` type QuizCopyQidParams struct { @@ -3348,11 +3478,36 @@ func (q *Queries) QuizCopyQid(ctx context.Context, arg QuizCopyQidParams) (QuizC return i, err } +const searchIDByAppIDanAppHash = `-- name: SearchIDByAppIDanAppHash :one +SELECT id, apiid, apihash, phonenumber, password, status, deleted, createdat FROM tgAccounts WHERE ApiID = $1 and ApiHash=$2 and Deleted = false +` + +type SearchIDByAppIDanAppHashParams struct { + Apiid int32 `db:"apiid" json:"apiid"` + Apihash string `db:"apihash" json:"apihash"` +} + +func (q *Queries) SearchIDByAppIDanAppHash(ctx context.Context, arg SearchIDByAppIDanAppHashParams) (Tgaccount, error) { + row := q.db.QueryRowContext(ctx, searchIDByAppIDanAppHash, arg.Apiid, arg.Apihash) + var i Tgaccount + err := row.Scan( + &i.ID, + &i.Apiid, + &i.Apihash, + &i.Phonenumber, + &i.Password, + &i.Status, + &i.Deleted, + &i.Createdat, + ) + return i, err +} + const setQuizSettings = `-- name: SetQuizSettings :one INSERT INTO rules (AccountID, QuizID, PerformerID, PipelineID, StepID, FieldsRule,TagsToAdd) SELECT u.AmoID AS AccountID,$1 AS QuizID,$2 AS PerformerID,$3 AS PipelineID, $4 AS StepID,$5 AS FieldsRule,$6 AS TagsToAdd FROM accountsamo u WHERE u.AccountID = $7 AND u.Deleted = false - RETURNING id +RETURNING id ` type SetQuizSettingsParams struct { @@ -3409,10 +3564,10 @@ const softDeleteAccount = `-- name: SoftDeleteAccount :exec WITH amoCompany AS ( SELECT AmoID FROM accountsAmo WHERE accountsAmo.AccountID = $1 AND deleted = false ),usersDel AS ( - UPDATE usersAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) - ), - companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) - ) + UPDATE usersAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) +), + companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE AmoID = (SELECT AmoID FROM amoCompany) + ) DELETE FROM tokens WHERE tokens.AccountID = $1 ` @@ -3430,6 +3585,15 @@ func (q *Queries) SoftDeleteResultByID(ctx context.Context, id int64) error { return err } +const softDeleteTgAccount = `-- name: SoftDeleteTgAccount :exec +UPDATE tgAccounts SET Deleted = true WHERE id = $1 +` + +func (q *Queries) SoftDeleteTgAccount(ctx context.Context, id int64) error { + _, err := q.db.ExecContext(ctx, softDeleteTgAccount, id) + return err +} + const templateCopy = `-- name: TemplateCopy :one WITH copied_quiz AS ( INSERT INTO quiz (accountid, name,fingerprinting,repeatable,note_prevented,mail_notifications,unique_answers,super,group_id, description, config, status,limit_answers,due_to,time_of_passing,pausable,version,version_comment, parent_ids) @@ -3554,6 +3718,32 @@ func (q *Queries) UpdateFields(ctx context.Context, dollar_1 json.RawMessage) er return err } +const updateLeadTarget = `-- name: UpdateLeadTarget :one +UPDATE leadtarget SET target = $1,InviteLink = $2 WHERE id = $3 AND deleted=false RETURNING id, accountid, type, quizid, target, invitelink, deleted, createdat +` + +type UpdateLeadTargetParams struct { + Target string `db:"target" json:"target"` + Invitelink string `db:"invitelink" json:"invitelink"` + ID int64 `db:"id" json:"id"` +} + +func (q *Queries) UpdateLeadTarget(ctx context.Context, arg UpdateLeadTargetParams) (Leadtarget, error) { + row := q.db.QueryRowContext(ctx, updateLeadTarget, arg.Target, arg.Invitelink, arg.ID) + var i Leadtarget + err := row.Scan( + &i.ID, + &i.Accountid, + &i.Type, + &i.Quizid, + &i.Target, + &i.Invitelink, + &i.Deleted, + &i.Createdat, + ) + return i, err +} + const updatePipelines = `-- name: UpdatePipelines :exec UPDATE pipelines AS p SET name = (update_data ->> 'Name')::varchar(512), @@ -3573,10 +3763,10 @@ UPDATE privileges SET amount = $1, created_at = $2 WHERE account_id = $3 AND pri ` type UpdatePrivilegeParams struct { - Amount sql.NullInt32 `db:"amount" json:"amount"` - CreatedAt sql.NullTime `db:"created_at" json:"created_at"` - AccountID uuid.NullUUID `db:"account_id" json:"account_id"` - Privilegeid sql.NullString `db:"privilegeid" json:"privilegeid"` + Amount int32 `db:"amount" json:"amount"` + CreatedAt time.Time `db:"created_at" json:"created_at"` + AccountID uuid.UUID `db:"account_id" json:"account_id"` + Privilegeid string `db:"privilegeid" json:"privilegeid"` } func (q *Queries) UpdatePrivilege(ctx context.Context, arg UpdatePrivilegeParams) error { @@ -3594,8 +3784,8 @@ UPDATE privileges SET amount = $1 WHERE id = $2 ` type UpdatePrivilegeAmountParams struct { - Amount sql.NullInt32 `db:"amount" json:"amount"` - ID int32 `db:"id" json:"id"` + Amount int32 `db:"amount" json:"amount"` + ID int32 `db:"id" json:"id"` } func (q *Queries) UpdatePrivilegeAmount(ctx context.Context, arg UpdatePrivilegeAmountParams) error { @@ -3603,6 +3793,20 @@ func (q *Queries) UpdatePrivilegeAmount(ctx context.Context, arg UpdatePrivilege return err } +const updateStatusTg = `-- name: UpdateStatusTg :exec +UPDATE tgAccounts SET Status = $1 WHERE id = $2 +` + +type UpdateStatusTgParams struct { + Status interface{} `db:"status" json:"status"` + ID int64 `db:"id" json:"id"` +} + +func (q *Queries) UpdateStatusTg(ctx context.Context, arg UpdateStatusTgParams) error { + _, err := q.db.ExecContext(ctx, updateStatusTg, arg.Status, arg.ID) + return err +} + const updateSteps = `-- name: UpdateSteps :exec UPDATE steps AS s SET name = (update_data ->> 'Name')::varchar(512), @@ -3653,9 +3857,9 @@ const webhookDelete = `-- name: WebhookDelete :exec WITH companyDel AS ( UPDATE accountsAmo SET Deleted = true WHERE accountsAmo.AmoID = $1 RETURNING AccountID ), -userDel AS ( -UPDATE usersAmo SET Deleted = true WHERE AmoID = $1 -) + userDel AS ( + UPDATE usersAmo SET Deleted = true WHERE AmoID = $1 + ) DELETE FROM tokens WHERE AccountID IN (SELECT AccountID FROM companyDel) ` @@ -3739,11 +3943,11 @@ SET answers_count = COALESCE(aa.unique_true_answers_count, 0), average_time_passing = COALESCE(sta.average_session_time, 0), sessions_count = COALESCE(sta.sess,0) - FROM +FROM (SELECT id, qid, accountid, deleted, archived, fingerprinting, repeatable, note_prevented, mail_notifications, unique_answers, super, group_id, name, description, config, status, limit_answers, due_to, time_of_passing, pausable, version, version_comment, parent_ids, created_at, updated_at, questions_count, answers_count, average_time_passing, sessions_count FROM quiz WHERE deleted = FALSE AND archived = FALSE) q_sub -LEFT JOIN answer_aggregates aa ON q_sub.id = aa.quiz_id - LEFT JOIN question_aggregates qa ON q_sub.id = qa.quiz_id - LEFT JOIN session_times_aggregates sta ON q_sub.id = sta.quiz_id + LEFT JOIN answer_aggregates aa ON q_sub.id = aa.quiz_id + LEFT JOIN question_aggregates qa ON q_sub.id = qa.quiz_id + LEFT JOIN session_times_aggregates sta ON q_sub.id = sta.quiz_id WHERE q.id = q_sub.id ` diff --git a/go.mod b/go.mod index 41af95d..f5c6edf 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module penahub.gitlab.yandexcloud.net/backend/quiz/common.git go 1.21.4 require ( + github.com/ClickHouse/clickhouse-go v1.5.4 github.com/gofiber/fiber/v2 v2.52.0 github.com/golang-jwt/jwt/v5 v5.2.0 github.com/golang/protobuf v1.5.3 @@ -18,7 +19,6 @@ require ( ) require ( - github.com/ClickHouse/clickhouse-go v1.5.4 // indirect github.com/andybalholm/brotli v1.0.5 // indirect github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 // indirect github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/go.sum b/go.sum index 5bcd421..d047566 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,7 @@ github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/ github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/bkaradzic/go-lz4 v1.0.0 h1:RXc4wYsyz985CkXXeX04y4VnZFGG8Rd43pRaHsOXAKk= github.com/bkaradzic/go-lz4 v1.0.0/go.mod h1:0YdlkowM3VswSROI7qDxhRvJ3sLhlFrRRwjwegp5jy4= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= @@ -61,6 +62,7 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= diff --git a/model/model.go b/model/model.go index 3882503..5db3a91 100644 --- a/model/model.go +++ b/model/model.go @@ -282,7 +282,6 @@ type ExpiredPrivileges struct { type Account struct { ID string `json:"id"` UserID string `json:"user_id"` - Email string `json:"email"` CreatedAt time.Time `json:"created_at"` Deleted bool `json:"deleted"` Privileges map[string]ShortPrivilege `json:"privileges"` @@ -308,3 +307,28 @@ type AnswerExport struct { } type UTMSavingMap map[string]string + +type LeadTarget struct { + ID int64 `json:"id"` + AccountID string `json:"accountID"` + Type LeadTargetType `json:"type"` + QuizID int32 `json:"quizID"` + Target string `json:"target"` + InviteLink string `json:"inviteLink"` // например указывается для типа телеграмма для созданного канала + Deleted bool `json:"deleted"` + CreatedAt time.Time `json:"createdAt"` +} + +type LeadTargetType string + +const ( + LeadTargetEmail LeadTargetType = "mail" + LeadTargetTg LeadTargetType = "telegram" + LeadTargetWhatsapp LeadTargetType = "whatsapp" +) + +var ValidLeadTargetTypes = map[string]bool{ + "mail": true, + "telegram": true, + "whatsapp": true, +} diff --git a/model/tg.go b/model/tg.go new file mode 100644 index 0000000..0db8bbe --- /dev/null +++ b/model/tg.go @@ -0,0 +1,28 @@ +package model + +import "time" + +type TgAccount struct { + ID int64 + ApiID int32 + ApiHash string + PhoneNumber string + Password string + Status TgAccountStatus + Deleted bool + CreatedAt time.Time +} + +type TgAccountStatus string + +const ( + ActiveTg TgAccountStatus = "active" + InactiveTg TgAccountStatus = "inactive" + BanTg TgAccountStatus = "ban" +) + +type TgRedisTask struct { + Name string + QuizID int32 + AccountID string +} diff --git a/repository/account/account.go b/repository/account/account.go index 1cb97b6..9f10fb9 100644 --- a/repository/account/account.go +++ b/repository/account/account.go @@ -30,9 +30,7 @@ func NewAccountRepository(deps Deps) *AccountRepository { // test + func (r *AccountRepository) GetAccountByID(ctx context.Context, userID string) (model.Account, error) { - userIDSql := sql.NullString{String: userID, Valid: userID != ""} - - accountRows, err := r.queries.GetAccountWithPrivileges(ctx, userIDSql) + accountRows, err := r.queries.GetAccountWithPrivileges(ctx, userID) if err != nil { return model.Account{}, err } @@ -43,9 +41,9 @@ func (r *AccountRepository) GetAccountByID(ctx context.Context, userID string) ( for _, row := range accountRows { if account.ID == "" { account.ID = row.ID.String() - account.UserID = row.UserID.String - account.CreatedAt = row.CreatedAt.Time - account.Deleted = row.Deleted.Bool + account.UserID = row.UserID + account.CreatedAt = row.CreatedAt + account.Deleted = row.Deleted } if row.PrivilegeID != 0 { @@ -54,7 +52,7 @@ func (r *AccountRepository) GetAccountByID(ctx context.Context, userID string) ( PrivilegeID: row.Privilegeid, PrivilegeName: row.PrivilegeName, Amount: uint64(row.Amount), - CreatedAt: row.PrivilegeCreatedAt.Time, + CreatedAt: row.PrivilegeCreatedAt, } privileges[privilege.PrivilegeID] = privilege } @@ -70,9 +68,8 @@ func (r *AccountRepository) GetAccountByID(ctx context.Context, userID string) ( // test + func (r *AccountRepository) GetPrivilegesByAccountID(ctx context.Context, userID string) ([]model.ShortPrivilege, error) { - userIDSql := sql.NullString{String: userID, Valid: userID != ""} - privilegeRows, err := r.queries.GetPrivilegesByAccountIDWC(ctx, userIDSql) + privilegeRows, err := r.queries.GetPrivilegesByAccountIDWC(ctx, userID) if err != nil { return nil, err } @@ -82,10 +79,10 @@ func (r *AccountRepository) GetPrivilegesByAccountID(ctx context.Context, userID for _, row := range privilegeRows { privilege := model.ShortPrivilege{ ID: fmt.Sprintf("%d", row.ID), - PrivilegeID: row.Privilegeid.String, - PrivilegeName: row.PrivilegeName.String, - Amount: uint64(row.Amount.Int32), - CreatedAt: row.CreatedAt.Time, + PrivilegeID: row.Privilegeid, + PrivilegeName: row.PrivilegeName, + Amount: uint64(row.Amount), + CreatedAt: row.CreatedAt, } privileges = append(privileges, privilege) } @@ -98,10 +95,9 @@ func (r *AccountRepository) CreateAccount(ctx context.Context, data *model.Accou data.ID = uuid.NewString() row, err := r.queries.CreateAccount(ctx, sqlcgen.CreateAccountParams{ ID: uuid.MustParse(data.ID), - UserID: sql.NullString{String: data.UserID, Valid: data.UserID != ""}, - Email: sql.NullString{String: data.Email, Valid: data.Email != ""}, - CreatedAt: sql.NullTime{Time: data.CreatedAt, Valid: !data.CreatedAt.IsZero()}, - Deleted: sql.NullBool{Bool: data.Deleted, Valid: true}, + UserID: data.UserID, + CreatedAt: data.CreatedAt, + Deleted: data.Deleted, }) if err != nil { return model.Account{}, fmt.Errorf("failed to create account: %w", err) @@ -109,17 +105,16 @@ func (r *AccountRepository) CreateAccount(ctx context.Context, data *model.Accou createdAccount := model.Account{ ID: row.ID.String(), - UserID: row.UserID.String, - Email: row.Email.String, + UserID: row.UserID, } for _, privilege := range data.Privileges { err := r.queries.InsertPrivilege(ctx, sqlcgen.InsertPrivilegeParams{ - Privilegeid: sql.NullString{String: privilege.PrivilegeID, Valid: privilege.PrivilegeID != ""}, - AccountID: uuid.NullUUID{UUID: uuid.MustParse(data.ID), Valid: true}, - PrivilegeName: sql.NullString{String: privilege.PrivilegeName, Valid: privilege.PrivilegeName != ""}, - Amount: sql.NullInt32{Int32: int32(privilege.Amount), Valid: true}, - CreatedAt: sql.NullTime{Time: privilege.CreatedAt, Valid: !privilege.CreatedAt.IsZero()}, + Privilegeid: privilege.PrivilegeID, + AccountID: uuid.MustParse(data.ID), + PrivilegeName: privilege.PrivilegeName, + Amount: int32(privilege.Amount), + CreatedAt: privilege.CreatedAt, }) if err != nil { @@ -142,7 +137,7 @@ func (r *AccountRepository) DeleteAccount(ctx context.Context, accountID string) return err } - err = r.queries.DeletePrivilegeByAccID(ctx, uuid.NullUUID{UUID: uuid.MustParse(accountID), Valid: true}) + err = r.queries.DeletePrivilegeByAccID(ctx, uuid.MustParse(accountID)) if err != nil { tx.Rollback() return err @@ -166,9 +161,9 @@ func (r *AccountRepository) GetAccounts(ctx context.Context, limit uint64, offse for _, row := range rows { account := model.Account{ ID: row.ID.String(), - UserID: row.UserID.String, - CreatedAt: row.CreatedAt.Time, - Deleted: row.Deleted.Bool, + UserID: row.UserID, + CreatedAt: row.CreatedAt, + Deleted: row.Deleted, } accounts = append(accounts, account) @@ -180,10 +175,10 @@ func (r *AccountRepository) GetAccounts(ctx context.Context, limit uint64, offse // test + func (r *AccountRepository) UpdatePrivilege(ctx context.Context, privilege *model.ShortPrivilege, accountID string) error { err := r.queries.UpdatePrivilege(ctx, sqlcgen.UpdatePrivilegeParams{ - Amount: sql.NullInt32{Int32: int32(privilege.Amount), Valid: true}, - CreatedAt: sql.NullTime{Time: privilege.CreatedAt, Valid: !privilege.CreatedAt.IsZero()}, - AccountID: uuid.NullUUID{UUID: uuid.MustParse(accountID), Valid: true}, - Privilegeid: sql.NullString{String: privilege.PrivilegeID, Valid: privilege.PrivilegeID != ""}, + Amount: int32(privilege.Amount), + CreatedAt: privilege.CreatedAt, + AccountID: uuid.MustParse(accountID), + Privilegeid: privilege.PrivilegeID, }) if err != nil { @@ -196,11 +191,11 @@ func (r *AccountRepository) UpdatePrivilege(ctx context.Context, privilege *mode // test + func (r *AccountRepository) InsertPrivilege(ctx context.Context, privilege *model.ShortPrivilege, accountID string) error { err := r.queries.InsertPrivilege(ctx, sqlcgen.InsertPrivilegeParams{ - Amount: sql.NullInt32{Int32: int32(privilege.Amount), Valid: true}, - CreatedAt: sql.NullTime{Time: privilege.CreatedAt, Valid: !privilege.CreatedAt.IsZero()}, - AccountID: uuid.NullUUID{UUID: uuid.MustParse(accountID), Valid: true}, - Privilegeid: sql.NullString{String: privilege.PrivilegeID, Valid: privilege.PrivilegeID != ""}, - PrivilegeName: sql.NullString{String: privilege.PrivilegeName, Valid: privilege.PrivilegeName != ""}, + Amount: int32(privilege.Amount), + CreatedAt: privilege.CreatedAt, + AccountID: uuid.MustParse(accountID), + Privilegeid: privilege.PrivilegeID, + PrivilegeName: privilege.PrivilegeName, }) if err != nil { @@ -212,7 +207,7 @@ func (r *AccountRepository) InsertPrivilege(ctx context.Context, privilege *mode // test + func (r *AccountRepository) GetExpired(ctx context.Context, privilegeID string) ([]model.ExpiredPrivileges, error) { - rows, err := r.queries.GetExpiredDayPrivilege(ctx, sql.NullString{String: privilegeID, Valid: privilegeID != ""}) + rows, err := r.queries.GetExpiredDayPrivilege(ctx, privilegeID) if err != nil { return nil, err } @@ -222,13 +217,13 @@ func (r *AccountRepository) GetExpired(ctx context.Context, privilegeID string) for _, row := range rows { privilege := model.ShortPrivilege{ ID: fmt.Sprintf("%d", row.ID), - PrivilegeID: row.Privilegeid.String, - PrivilegeName: row.PrivilegeName.String, - Amount: uint64(row.Amount.Int32), - CreatedAt: row.CreatedAt.Time, + PrivilegeID: row.Privilegeid, + PrivilegeName: row.PrivilegeName, + Amount: uint64(row.Amount), + CreatedAt: row.CreatedAt, } expiredRecords = append(expiredRecords, model.ExpiredPrivileges{ - UserID: row.UserID.String, + UserID: row.UserID, Privilege: privilege, }) @@ -238,7 +233,7 @@ func (r *AccountRepository) GetExpired(ctx context.Context, privilegeID string) } func (r *AccountRepository) GetExpiredCount(ctx context.Context, privilegeID string) ([]model.ExpiredPrivileges, error) { - rows, err := r.queries.GetExpiredCountPrivilege(ctx, sql.NullString{String: privilegeID, Valid: privilegeID != ""}) + rows, err := r.queries.GetExpiredCountPrivilege(ctx, privilegeID) if err != nil { return nil, err } @@ -248,13 +243,13 @@ func (r *AccountRepository) GetExpiredCount(ctx context.Context, privilegeID str for _, row := range rows { privilege := model.ShortPrivilege{ ID: fmt.Sprintf("%d", row.ID), - PrivilegeID: row.Privilegeid.String, - PrivilegeName: row.PrivilegeName.String, - Amount: uint64(row.Amount.Int32), - CreatedAt: row.CreatedAt.Time, + PrivilegeID: row.Privilegeid, + PrivilegeName: row.PrivilegeName, + Amount: uint64(row.Amount), + CreatedAt: row.CreatedAt, } expiredRecords = append(expiredRecords, model.ExpiredPrivileges{ - UserID: row.UserID.String, + UserID: row.UserID, Privilege: privilege, }) @@ -265,9 +260,9 @@ func (r *AccountRepository) GetExpiredCount(ctx context.Context, privilegeID str func (r *AccountRepository) CheckAndAddDefault(ctx context.Context, amount uint64, privilegeID string, zeroAmount uint64) error { err := r.queries.CheckAndAddDefault(ctx, sqlcgen.CheckAndAddDefaultParams{ - Amount: sql.NullInt32{Int32: int32(amount), Valid: true}, - PrivilegeName: sql.NullString{String: privilegeID, Valid: privilegeID != ""}, - Amount_2: sql.NullInt32{Int32: int32(zeroAmount), Valid: true}, + Amount: int32(amount), + PrivilegeName: privilegeID, + Amount_2: int32(zeroAmount), }) if err != nil { @@ -295,7 +290,7 @@ func (r *AccountRepository) UpdatePrivilegeAmount(ctx context.Context, ID string } err = r.queries.UpdatePrivilegeAmount(ctx, sqlcgen.UpdatePrivilegeAmountParams{ - Amount: sql.NullInt32{Int32: int32(newAmount), Valid: true}, + Amount: int32(newAmount), ID: int32(intID), }) @@ -311,22 +306,21 @@ func (r *AccountRepository) GetAccAndPrivilegeByEmail(ctx context.Context, email var account model.Account var privileges []model.ShortPrivilege - row, err := r.queries.GetAccAndPrivilegeByEmail(ctx, sql.NullString{String: email, Valid: true}) + row, err := r.queries.GetAccAndPrivilegeByEmail(ctx, email) if err != nil { return account, privileges, err } account.ID = row.ID.String() - account.UserID = row.UserID.String - account.Email = row.Email.String - account.CreatedAt = row.CreatedAt.Time + account.UserID = row.UserID + account.CreatedAt = row.CreatedAt if row.ID_2 != 0 { privilege := model.ShortPrivilege{ ID: fmt.Sprint(row.ID_2), PrivilegeID: row.Privilegeid, Amount: uint64(row.Amount), - CreatedAt: row.CreatedAt_2.Time, + CreatedAt: row.CreatedAt_2, } privileges = append(privileges, privilege) } @@ -352,8 +346,8 @@ func (r *AccountRepository) GetQidOwner(ctx context.Context, qId string) (string func (r *AccountRepository) ManualDone(ctx context.Context, userID string) error { _, err := r.queries.DecrementManual(ctx, sqlcgen.DecrementManualParams{ - UserID: sql.NullString{String: userID, Valid: true}, - Privilegeid: sql.NullString{String: "quizManual", Valid: true}, + UserID: userID, + Privilegeid: "quizManual", }) if err != nil { @@ -365,3 +359,100 @@ func (r *AccountRepository) ManualDone(ctx context.Context, userID string) error return nil } + +func (r *AccountRepository) PostLeadTarget(ctx context.Context, req model.LeadTarget) (model.LeadTarget, error) { + row, err := r.queries.CreateLeadTarget(ctx, sqlcgen.CreateLeadTargetParams{ + Accountid: req.AccountID, + Type: req.Type, + Quizid: req.QuizID, + Target: req.Target, + Invitelink: req.InviteLink, + }) + if err != nil { + return model.LeadTarget{}, err + } + + var targetType model.LeadTargetType + v := string(row.Type.([]byte)) + targetType = model.LeadTargetType(v) + + return model.LeadTarget{ + ID: row.ID, + AccountID: row.Accountid, + Type: targetType, + QuizID: row.Quizid, + Target: row.Target, + Deleted: row.Deleted, + CreatedAt: row.Createdat, + InviteLink: row.Invitelink, + }, nil +} + +func (r *AccountRepository) DeleteLeadTarget(ctx context.Context, id int64) error { + err := r.queries.DeleteLeadTarget(ctx, id) + if err != nil { + return err + } + return nil +} + +func (r *AccountRepository) GetLeadTarget(ctx context.Context, accountID string, quizID int32) ([]model.LeadTarget, error) { + rows, err := r.queries.GetLeadTarget(ctx, sqlcgen.GetLeadTargetParams{ + Accountid: accountID, + Quizid: quizID, + }) + if err != nil { + if err == sql.ErrNoRows { + return []model.LeadTarget{}, pj_errors.ErrNotFound + } + return []model.LeadTarget{}, err + } + var leadTargets []model.LeadTarget + for _, row := range rows { + var targetType model.LeadTargetType + v := string(row.Type.([]byte)) + targetType = model.LeadTargetType(v) + + leadTargets = append(leadTargets, model.LeadTarget{ + ID: row.ID, + AccountID: row.Accountid, + Type: targetType, + QuizID: row.Quizid, + Target: row.Target, + Deleted: row.Deleted, + CreatedAt: row.Createdat, + InviteLink: row.Invitelink, + }) + } + + return leadTargets, nil +} + +func (r *AccountRepository) UpdateLeadTarget(ctx context.Context, req model.LeadTarget) (model.LeadTarget, error) { + row, err := r.queries.UpdateLeadTarget(ctx, sqlcgen.UpdateLeadTargetParams{ + Invitelink: req.InviteLink, + Target: req.Target, + ID: req.ID, + }) + if err != nil { + if err == sql.ErrNoRows { + return model.LeadTarget{}, pj_errors.ErrNotFound + } + return model.LeadTarget{}, err + } + + var targetType model.LeadTargetType + v := string(row.Type.([]byte)) + targetType = model.LeadTargetType(v) + + return model.LeadTarget{ + ID: row.ID, + AccountID: row.Accountid, + Type: targetType, + QuizID: row.Quizid, + Target: row.Target, + Deleted: row.Deleted, + CreatedAt: row.Createdat, + InviteLink: row.Invitelink, + }, nil +} diff --git a/repository/tg/tg.go b/repository/tg/tg.go new file mode 100644 index 0000000..4675079 --- /dev/null +++ b/repository/tg/tg.go @@ -0,0 +1,111 @@ +package tg + +import ( + "context" + "database/sql" + "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal/sqlcgen" + "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model" + "penahub.gitlab.yandexcloud.net/backend/quiz/common.git/pj_errors" +) + +type TgRepo struct { + queries *sqlcgen.Queries + pool *sql.DB +} + +type Deps struct { + Queries *sqlcgen.Queries + Pool *sql.DB +} + +func NewTgRepo(deps Deps) *TgRepo { + return &TgRepo{ + queries: deps.Queries, + pool: deps.Pool, + } +} + +func (r *TgRepo) CreateTgAccount(ctx context.Context, data model.TgAccount) (int64, error) { + id, err := r.queries.CreateTgAccount(ctx, sqlcgen.CreateTgAccountParams{ + Apiid: data.ApiID, + Apihash: data.ApiHash, + Phonenumber: data.PhoneNumber, + Status: data.Status, + Password: data.Password, + }) + if err != nil { + return 0, err + } + return id, err +} + +func (r *TgRepo) GetAllTgAccounts(ctx context.Context) ([]model.TgAccount, error) { + rows, err := r.queries.GetAllTgAccounts(ctx) + if err != nil { + if err == sql.ErrNoRows { + return nil, pj_errors.ErrNotFound + } + return nil, err + } + var result []model.TgAccount + for _, row := range rows { + var status model.TgAccountStatus + s := string(row.Status.([]byte)) + status = model.TgAccountStatus(s) + result = append(result, model.TgAccount{ + ID: row.ID, + ApiID: row.Apiid, + ApiHash: row.Apihash, + PhoneNumber: row.Phonenumber, + Status: status, + Deleted: row.Deleted, + CreatedAt: row.Createdat, + Password: row.Password, + }) + } + + return result, nil +} + +func (r *TgRepo) UpdateStatusTg(ctx context.Context, id int64, status model.TgAccountStatus) error { + err := r.queries.UpdateStatusTg(ctx, sqlcgen.UpdateStatusTgParams{ + Status: status, + ID: id, + }) + if err != nil { + return err + } + return nil +} + +func (r *TgRepo) SoftDeleteTgAccount(ctx context.Context, id int64) error { + err := r.queries.SoftDeleteTgAccount(ctx, id) + if err != nil { + return err + } + return nil +} + +func (r *TgRepo) SearchIDByAppIDanAppHash(ctx context.Context, appID int32, appHash string) (*model.TgAccount, error) { + row, err := r.queries.SearchIDByAppIDanAppHash(ctx, sqlcgen.SearchIDByAppIDanAppHashParams{ + Apiid: appID, + Apihash: appHash, + }) + if err != nil { + return nil, err + } + var status model.TgAccountStatus + s := string(row.Status.([]byte)) + status = model.TgAccountStatus(s) + + return &model.TgAccount{ + ID: row.ID, + ApiID: row.Apiid, + ApiHash: row.Apihash, + PhoneNumber: row.Phonenumber, + Status: status, + Deleted: row.Deleted, + CreatedAt: row.Createdat, + Password: row.Password, + }, nil +} diff --git a/sqlc.yaml b/sqlc.yaml index 07bb059..a23277c 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -34,6 +34,12 @@ packages: - "./dal/schema/000014_init.down.sql" - "./dal/schema/000016_init.up.sql" - "./dal/schema/000016_init.down.sql" + - "./dal/schema/000017_init.up.sql" + - "./dal/schema/000017_init.down.sql" + - "./dal/schema/000018_init.up.sql" + - "./dal/schema/000018_init.down.sql" + - "./dal/schema/000019_init.up.sql" + - "./dal/schema/000019_init.down.sql" engine: "postgresql" emit_json_tags: true emit_db_tags: true