add payment text
Some checks failed
CI/CD / Vet, test, build (push) Has been cancelled
CI/CD / Docker image (push) Has been cancelled
CI/CD / Deploy binary to server (push) Has been cancelled

This commit is contained in:
2026-09-30 16:26:38 +05:00
parent 7e403dab13
commit ebedeba009
19 changed files with 1387 additions and 23 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

View File

@@ -601,6 +601,11 @@ CREATE TABLE IF NOT EXISTS visa_master_order_payments (
gateway_status character varying(32) NOT NULL DEFAULT 'pending',
gateway_reference character varying(255),
gateway_response jsonb,
-- orderNumber sent to GBÜS register.do and shown on its hosted payment
-- page ("Номер заказа"): ddMMyyHHmmss in Ashgabat time, e.g.
-- 290926133808 for 29.09.2026 13:38:08. GBÜS rejects a repeated
-- orderNumber per merchant, hence the unique index below.
order_number character varying(32),
created_by bigint,
created_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
@@ -615,6 +620,8 @@ CREATE TABLE IF NOT EXISTS visa_master_order_payments (
CREATE INDEX IF NOT EXISTS visa_master_order_payments_order_id_idx ON visa_master_order_payments (order_id);
CREATE INDEX IF NOT EXISTS visa_master_order_payments_user_id_idx ON visa_master_order_payments (user_id);
CREATE UNIQUE INDEX IF NOT EXISTS visa_master_order_payments_order_number_idx
ON visa_master_order_payments (order_number);
-- Every individual step taken while processing a payout (validated, rate
-- fetched, gateway request sent, gateway response received, order marked

View File

@@ -1,2 +0,0 @@
DROP INDEX IF EXISTS visa_master_order_payments_order_number_idx;
ALTER TABLE visa_master_order_payments DROP COLUMN IF EXISTS order_number;

View File

@@ -1,13 +0,0 @@
-- order_number is the orderNumber sent to GBÜS register.do and shown on its
-- hosted payment page ("Номер заказа"): ddMMyyHHmmss in Ashgabat time, e.g.
-- 290926133808 for 29.09.2026 13:38:08. GBÜS rejects a repeated orderNumber
-- per merchant, hence the unique index. Rows made before this column keep
-- the vmo-<order>-<payment> number they were actually registered with.
ALTER TABLE visa_master_order_payments ADD COLUMN IF NOT EXISTS order_number character varying(32);
UPDATE visa_master_order_payments
SET order_number = 'vmo-' || order_id || '-' || id
WHERE order_number IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS visa_master_order_payments_order_number_idx
ON visa_master_order_payments (order_number);

View File

@@ -0,0 +1 @@
DROP TABLE IF EXISTS payment_texts;

View File

@@ -0,0 +1,23 @@
-- Admin-editable texts shown to clients around a visa/master/sber payout
-- (e.g. the warning before paying). Clients look a text up by its fixed
-- code, so codes are seeded here and never created/deleted from the admin
-- UI - only name/text/is_active are editable. text is {"tm","ru","en"}.
CREATE TABLE IF NOT EXISTS payment_texts (
id bigserial PRIMARY KEY,
code character varying(64) NOT NULL,
name character varying(255) NOT NULL,
text jsonb NOT NULL DEFAULT '{"tm":"","ru":"","en":""}'::jsonb,
is_active boolean NOT NULL DEFAULT true,
updated_by bigint,
updated_at TIMESTAMP DEFAULT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') NOT NULL,
CONSTRAINT payment_texts_code_key UNIQUE (code),
CONSTRAINT payment_texts_updated_by_fkey
FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL
);
INSERT INTO payment_texts (code, name, text) VALUES
('payment_warning_text', 'Visa/Master töleg duýduryş',
'{"tm":"Dogry töleg aýyny saýlamagyňyzy haýyş edýäris","ru":"","en":""}'::jsonb),
('sber_payment_warning', 'Sber töleg duýduryş',
'{"tm":"Sber töleg duýduryş","ru":"","en":""}'::jsonb)
ON CONFLICT (code) DO NOTHING;

View File

@@ -18,6 +18,8 @@ TRUNCATE TABLE
activity_logs,
backups,
currencies,
visa_master_payment_logs,
visa_master_order_payments,
visa_master_payment_orders,
loan_paid_off_letters,
loans,
@@ -242,9 +244,13 @@ INSERT INTO provinces (name, region, active) VALUES
-- ---------------------------------------------------------------------------
INSERT INTO branches (
unique_code, name, address, region, province_id, phone_numbers,
billing_username, billing_password, active
billing_username, billing_password,
billing_visa_master_username, billing_visa_master_password,
billing_sber_username, billing_sber_password, active
)
SELECT v.unique_code, v.name::json, v.address::json, v.region, p.id, '+993 61 92 92 48', v.billing_username, 'billing_pass', v.active
SELECT v.unique_code, v.name::json, v.address::json, v.region, p.id, '+993 61 92 92 48', v.billing_username, 'billing_pass',
replace(v.billing_username, 'billing_', 'vm_'), 'vm_pass',
replace(v.billing_username, 'billing_', 'sber_'), 'sber_pass', v.active
FROM (VALUES
('AGB-01', '{"en":"Ashgabat Central Branch","ru":"Центральный филиал Ашхабад","tm":"Aşgabat Merkezi şahamça"}', '{"en":"Archabil Ave 1","ru":"пр. Арчабиль 1","tm":"Arçabil şaýoly 1"}', 'AG', 'Aşgabat', 'billing_agb', true),
('AGB-02', '{"en":"Ashgabat Kopetdag Branch","ru":"Филиал Копетдаг","tm":"Köpetdag şahamçasy"}', '{"en":"Turkmenbashy Ave 45","ru":"пр. Туркменбаши 45","tm":"Türkmenbaşy şaýoly 45"}', 'AG', 'Aşgabat', 'billing_agb2', true),
@@ -594,7 +600,7 @@ INSERT INTO loan_paid_off_letters (
);
-- ---------------------------------------------------------------------------
-- Visa / Master payment orders (student transfers)
-- Visa / Master payment orders (type = student)
-- documents JSON keys match the admin upload slots (student + sender).
-- ---------------------------------------------------------------------------
INSERT INTO visa_master_payment_orders (
@@ -604,7 +610,7 @@ INSERT INTO visa_master_payment_orders (
status, notes,
sender_full_name, sender_passport_serie, sender_passport_number, sender_deposit_account,
reciever_full_name, reciever_passport_serie, reciever_passport_number, reciever_deposit_account,
paid
paid, amount_usd
) VALUES
(
'VMP-2026-0001', 'student', 'Serdar', 'Myradow', '+993 61 92 92 48', 'serdar@bank.tm',
@@ -630,7 +636,7 @@ INSERT INTO visa_master_payment_orders (
'pending', 'Garaşylýar',
'Myradow Serdar Orazowiç', 'I-AG', '123456', '23202984200012345678',
'Orazowa Gulnar Myradowna', 'I-AG', '654321', NULL,
false
false, NULL
),
(
'VMP-2026-0002', 'student', 'Kerim', 'Atayew', '+993 61 92 92 48', NULL,
@@ -656,8 +662,22 @@ INSERT INTO visa_master_payment_orders (
'approved', NULL,
'Atayew Kerim Begliýewiç', 'I-AG', '101010', '23202984200010101011',
'Gurbanowa Leyla Saparowna', 'I-AG', '303030', NULL,
true
),
true, 150.00
);
-- ---------------------------------------------------------------------------
-- Sber payment orders (type = sber). Ids 3–8; aşakdaky töleg/loglar
-- order_id 4, 5, 6-a salgylanýar.
-- ---------------------------------------------------------------------------
INSERT INTO visa_master_payment_orders (
unique_id, type, passport_name, passport_surname, phone, email,
region, branch_id, user_id, address,
sender_datas, payment_reciever, documents,
status, notes,
sender_full_name, sender_passport_serie, sender_passport_number, sender_deposit_account,
reciever_full_name, reciever_passport_serie, reciever_passport_number, reciever_deposit_account,
paid, amount_usd
) VALUES
(
'VMP-2026-0003', 'sber', 'Batyr', 'Saparow', '+993 61 92 92 48', NULL,
'AG', 1, 5, 'Aşgabat, Bitarap Türkmenistan 12',
@@ -682,9 +702,176 @@ INSERT INTO visa_master_payment_orders (
'pending', 'Sber tölegi garaşylýar',
'Saparow Batyr Annaýewiç', 'I-AG', '202020', '23202984200020202022',
'Saparowa Aýna Batyrowna', 'I-AG', '404040', NULL,
false
false, 200.00
),
(
'VMP-2026-0004', 'sber', 'Aýna', 'Orazowa', '+993 61 92 92 48', 'gulnar@bank.tm',
'AG', 1, 6, 'Aşgabat, Andalyp 21',
'{"fullName":"Orazowa Gulnar Myradowna","passportSerie":"I-AG","passportNumber":"654321","depositAccount":"23202984200065432100"}'::json,
'[{"fullName":"Orazowa Aýna Serdarowna","passportSerie":"I-AG","passportNumber":"505050"}]'::json,
'{
"student_visa_card_details":["sber-card-4.pdf"],
"student_enrollment_certificate":["enrollment-4.pdf"],
"student_ticket_copy":[],
"student_internal_passport":["student-internal-4.pdf"],
"student_foreign_passport":["student-foreign-4.pdf"],
"student_visa_page":["student-visa-page-4.pdf"],
"student_stamp_page":[],
"student_enrollment_clarification":[],
"sender_internal_passport":["sender-internal-4.pdf"],
"sender_foreign_passport":[],
"sender_stamp_page":[],
"kinship_documents":["kinship-4.pdf"],
"first_passport_series_info":[],
"police_passport_series_info":[]
}'::json,
'approved', 'Sber tölegi geçirildi',
'Orazowa Gulnar Myradowna', 'I-AG', '654321', '23202984200065432100',
'Orazowa Aýna Serdarowna', 'I-AG', '505050', NULL,
true, 250.00
),
(
'VMP-2026-0005', 'sber', 'Merdan', 'Hojaýew', '+993 61 92 92 48', 'dovran@bank.tm',
'AG', 2, 7, 'Aşgabat, Garaşsyzlyk 55',
'{"fullName":"Hojaýew Döwran Amanowiç","passportSerie":"I-AG","passportNumber":"606060","depositAccount":"23202984200060606066"}'::json,
'[{"fullName":"Hojaýew Merdan Döwranowiç","passportSerie":"I-AG","passportNumber":"707070"}]'::json,
'{
"student_visa_card_details":["sber-card-5.pdf"],
"student_enrollment_certificate":["enrollment-5.pdf"],
"student_ticket_copy":[],
"student_internal_passport":["student-internal-5.pdf"],
"student_foreign_passport":["student-foreign-5.pdf"],
"student_visa_page":["student-visa-page-5.pdf"],
"student_stamp_page":[],
"student_enrollment_clarification":[],
"sender_internal_passport":["sender-internal-5.pdf"],
"sender_foreign_passport":[],
"sender_stamp_page":[],
"kinship_documents":["kinship-5.pdf"],
"first_passport_series_info":[],
"police_passport_series_info":[]
}'::json,
'approved', 'Töleg şowsuz, gaýtadan synanyşyň',
'Hojaýew Döwran Amanowiç', 'I-AG', '606060', '23202984200060606066',
'Hojaýew Merdan Döwranowiç', 'I-AG', '707070', NULL,
false, 200.00
),
(
'VMP-2026-0006', 'sber', 'Leýli', 'Nurýewa', '+993 61 92 92 48', 'maya@bank.tm',
'AG', 1, 8, 'Aşgabat, Oguzhan 3',
'{"fullName":"Nurýewa Maýa Batyrowna","passportSerie":"I-AG","passportNumber":"808080","depositAccount":"23202984200080808088"}'::json,
'[{"fullName":"Nurýewa Leýli Myratowna","passportSerie":"I-AG","passportNumber":"909090"}]'::json,
'{
"student_visa_card_details":["sber-card-6.pdf"],
"student_enrollment_certificate":["enrollment-6.pdf"],
"student_ticket_copy":[],
"student_internal_passport":["student-internal-6.pdf"],
"student_foreign_passport":["student-foreign-6.pdf"],
"student_visa_page":["student-visa-page-6.pdf"],
"student_stamp_page":[],
"student_enrollment_clarification":[],
"sender_internal_passport":["sender-internal-6.pdf"],
"sender_foreign_passport":[],
"sender_stamp_page":[],
"kinship_documents":["kinship-6.pdf"],
"first_passport_series_info":[],
"police_passport_series_info":[]
}'::json,
'approved', 'GBÜS tassyklamasy garaşylýar',
'Nurýewa Maýa Batyrowna', 'I-AG', '808080', '23202984200080808088',
'Nurýewa Leýli Myratowna', 'I-AG', '909090', NULL,
false, 150.00
),
(
'VMP-2026-0007', 'sber', 'Rahman', 'Gurbanow', '+993 61 92 92 48', 'leyla@bank.tm',
'AH', 3, 10, 'Ak bugdaý, Täze ýol 4',
'{"fullName":"Gurbanowa Leyla Saparowna","passportSerie":"I-AH","passportNumber":"303030","depositAccount":"23202984200030303033"}'::json,
'[{"fullName":"Gurbanow Rahman Kakajanowiç","passportSerie":"I-AH","passportNumber":"111222"}]'::json,
'{
"student_visa_card_details":["sber-card-7.pdf"],
"student_enrollment_certificate":["enrollment-7.pdf"],
"student_ticket_copy":[],
"student_internal_passport":["student-internal-7.pdf"],
"student_foreign_passport":["student-foreign-7.pdf"],
"student_visa_page":["student-visa-page-7.pdf"],
"student_stamp_page":[],
"student_enrollment_clarification":[],
"sender_internal_passport":["sender-internal-7.pdf"],
"sender_foreign_passport":[],
"sender_stamp_page":[],
"kinship_documents":["kinship-7.pdf"],
"first_passport_series_info":[],
"police_passport_series_info":[]
}'::json,
'rejected', 'Okuw güwänamasy ýok',
'Gurbanowa Leyla Saparowna', 'I-AH', '303030', '23202984200030303033',
'Gurbanow Rahman Kakajanowiç', 'I-AH', '111222', NULL,
false, NULL
),
(
'VMP-2026-0008', 'sber', 'Myrat', 'Atayew', '+993 61 92 92 48', 'kerim@bank.tm',
'MR', 7, 9, 'Mary, Magtymguly 18',
'{"fullName":"Atayew Kerim Begliýewiç","passportSerie":"I-MR","passportNumber":"101010","depositAccount":"23202984200010101011"}'::json,
'[{"fullName":"Atayew Myrat Kerimowiç","passportSerie":"I-MR","passportNumber":"121212"}]'::json,
'{
"student_visa_card_details":["sber-card-8.pdf"],
"student_enrollment_certificate":["enrollment-8.pdf"],
"student_ticket_copy":[],
"student_internal_passport":["student-internal-8.pdf"],
"student_foreign_passport":["student-foreign-8.pdf"],
"student_visa_page":["student-visa-page-8.pdf"],
"student_stamp_page":[],
"student_enrollment_clarification":[],
"sender_internal_passport":["sender-internal-8.pdf"],
"sender_foreign_passport":[],
"sender_stamp_page":[],
"kinship_documents":["kinship-8.pdf"],
"first_passport_series_info":[],
"police_passport_series_info":[]
}'::json,
'pending', 'Sber: resminamalar barlanýar',
'Atayew Kerim Begliýewiç', 'I-MR', '101010', '23202984200010101011',
'Atayew Myrat Kerimowiç', 'I-MR', '121212', NULL,
false, NULL
);
-- ---------------------------------------------------------------------------
-- Sber payout attempts (visa_master_order_payments) & step logs.
-- Kurs: USD→TMT 3.5175, RUB→TMT 0.047504; sber_bank_fee_tmt = 100,
-- tveb_fee_usd = 18 (= 63.32 TMT). Sber üçin gbus_fee_tmt NULL.
-- Order ids: 4 = paid (2 aý), 5 = failed, 6 = pending (GBÜS garaşylýar).
-- ---------------------------------------------------------------------------
INSERT INTO visa_master_order_payments (
order_id, user_id, payment_period, exchange_rate_usd, exchange_rate_rub, amount_tmt,
bank_fee_tmt, gbus_fee_tmt, tveb_fee_usd, tveb_fee_tmt, total_amount_tmt,
gateway_status, gateway_reference, gateway_response, created_by, order_number, created_at, updated_at
) VALUES
(4, 6, '2026-08-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
'paid', 'a1b2c3d4-0004-4001-8001-000000000001', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
3, '150826101512', '2026-08-15 05:15:12', '2026-08-15 05:17:40'),
(4, 6, '2026-09-01', 3.5175, 0.047504, 879.38, 100, NULL, 18, 63.32, 1042.70,
'paid', 'a1b2c3d4-0004-4001-8001-000000000002', '{"orderStatus":2,"actionCode":0,"actionCodeDescription":"Request processed successfully"}'::jsonb,
3, '120926112030', '2026-09-12 06:20:30', '2026-09-12 06:22:05'),
(5, 7, '2026-09-01', 3.5175, 0.047504, 700.00, 100, NULL, 18, 63.32, 863.32,
'failed', 'a1b2c3d4-0005-4001-8001-000000000003', '{"orderStatus":6,"actionCode":-2007,"actionCodeDescription":"Decline. Payment time limit"}'::jsonb,
3, '250926143011', '2026-09-25 09:30:11', '2026-09-25 09:50:11'),
(6, 8, '2026-09-01', 3.5175, 0.047504, 527.63, 100, NULL, 18, 63.32, 690.95,
'pending', 'a1b2c3d4-0006-4001-8001-000000000004', '{"errorCode":"0","orderId":"a1b2c3d4-0006-4001-8001-000000000004"}'::jsonb,
3, '300926154500', '2026-09-30 10:45:00', '2026-09-30 10:45:01');
INSERT INTO visa_master_payment_logs (order_id, step, detail, created_by, created_at) VALUES
(4, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":879.38,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-12 06:20:28'),
(4, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":1042.70}'::jsonb, 3, '2026-09-12 06:20:29'),
(4, 'callback_received', '{"gatewayStatus":"pending"}'::jsonb, NULL, '2026-09-12 06:22:04'),
(4, 'payment_finalized', '{"paid":true,"gatewayStatus":"paid"}'::jsonb, NULL, '2026-09-12 06:22:05'),
(5, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":700.00,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-25 09:30:09'),
(5, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":863.32}'::jsonb, 3, '2026-09-25 09:30:10'),
(5, 'status_check_response', '{"success":true,"paid":false,"orderStatus":6,"actionCode":-2007}'::jsonb, 3, '2026-09-25 09:50:10'),
(5, 'payment_finalized', '{"paid":false,"gatewayStatus":"failed"}'::jsonb, 3, '2026-09-25 09:50:11'),
(6, 'validated', '{"orderType":"sber","maxAmountUsd":250,"amountTmt":527.63,"exchangeRateUsd":3.5175}'::jsonb, 3, '2026-09-30 10:44:59'),
(6, 'fees_calculated', '{"bankFeeTmt":100,"gbusFeeTmt":null,"tvebFeeUsd":18,"tvebFeeTmt":63.32,"exchangeRateRub":0.047504,"totalAmountTmt":690.95}'::jsonb, 3, '2026-09-30 10:45:00');
-- ---------------------------------------------------------------------------
-- Currency rates (Walýuta kursy)
-- ---------------------------------------------------------------------------
@@ -720,6 +907,14 @@ INSERT INTO payment_settings (id, bank_fee_tmt, gbus_fee_tmt, sber_bank_fee_tmt,
VALUES (1, 100, 15, 100, 18)
ON CONFLICT (id) DO NOTHING;
-- payment_texts hem şeýle (users FK); klient kodlary gaýtadan goý.
INSERT INTO payment_texts (code, name, text) VALUES
('payment_warning_text', 'Visa/Master töleg duýduryş',
'{"tm":"Dogry töleg aýyny saýlamagyňyzy haýyş edýäris","ru":"","en":""}'::jsonb),
('sber_payment_warning', 'Sber töleg duýduryş',
'{"tm":"","ru":"","en":""}'::jsonb)
ON CONFLICT (code) DO NOTHING;
COMMIT;
-- Quick counts
@@ -742,6 +937,8 @@ UNION ALL SELECT 'loan_orders', count(*) FROM loan_orders
UNION ALL SELECT 'loans', count(*) FROM loans
UNION ALL SELECT 'loan_paid_off_letters', count(*) FROM loan_paid_off_letters
UNION ALL SELECT 'visa_master_payment_orders', count(*) FROM visa_master_payment_orders
UNION ALL SELECT 'visa_master_order_payments', count(*) FROM visa_master_order_payments
UNION ALL SELECT 'visa_master_payment_logs', count(*) FROM visa_master_payment_logs
UNION ALL SELECT 'registration_verifications', count(*) FROM registration_verifications
UNION ALL SELECT 'activity_logs', count(*) FROM activity_logs
UNION ALL SELECT 'backups', count(*) FROM backups

View File

@@ -5118,6 +5118,203 @@ const docTemplate = `{
}
}
},
"/payment-texts": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns the admin-editable, localized texts (warnings, hints) shown to clients on visa/master/sber payout screens. Clients only get active ones, with empty languages filled with a default text.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "List payment texts",
"parameters": [
{
"type": "string",
"description": "Filter by code, name or text",
"name": "search",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.ListPaymentTextDTO"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/payment-texts/{code}": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns one payment text by its fixed code (e.g. payment_warning_text, sber_payment_warning). For clients, empty languages are filled with a default text, a deleted known code returns its default, and inactive texts are 404.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Get a payment text by code",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
},
"put": {
"security": [
{
"BearerAuth": []
}
],
"description": "Updates the name, localized text and active flag of an existing payment text. The code itself cannot be changed.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Update a payment text",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
},
{
"description": "Payment text payload",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/paymenttexts.UpdatePaymentTextDTO"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
},
"delete": {
"security": [
{
"BearerAuth": []
}
],
"description": "Super admin only. Deletes a payment text by code; clients then get the built-in default text for known codes.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Delete a payment text",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/appresult.AppSuccess"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/permissions": {
"get": {
"security": [
@@ -9357,6 +9554,67 @@ const docTemplate = `{
}
}
},
"paymenttexts.ListPaymentTextDTO": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"items": {
"type": "array",
"items": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
}
}
},
"paymenttexts.PaymentTextDTO": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"id": {
"type": "integer"
},
"isActive": {
"type": "boolean"
},
"name": {
"type": "string"
},
"text": {
"$ref": "#/definitions/shared.LocalizedText"
},
"updatedAt": {
"type": "string"
},
"updatedById": {
"type": "integer"
},
"updatedByName": {
"type": "string"
}
}
},
"paymenttexts.UpdatePaymentTextDTO": {
"type": "object",
"required": [
"isActive",
"name"
],
"properties": {
"isActive": {
"type": "boolean"
},
"name": {
"type": "string"
},
"text": {
"$ref": "#/definitions/shared.LocalizedText"
}
}
},
"perm.Code": {
"type": "string",
"enum": [

View File

@@ -5112,6 +5112,203 @@
}
}
},
"/payment-texts": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns the admin-editable, localized texts (warnings, hints) shown to clients on visa/master/sber payout screens. Clients only get active ones, with empty languages filled with a default text.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "List payment texts",
"parameters": [
{
"type": "string",
"description": "Filter by code, name or text",
"name": "search",
"in": "query"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.ListPaymentTextDTO"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/payment-texts/{code}": {
"get": {
"security": [
{
"BearerAuth": []
}
],
"description": "Returns one payment text by its fixed code (e.g. payment_warning_text, sber_payment_warning). For clients, empty languages are filled with a default text, a deleted known code returns its default, and inactive texts are 404.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Get a payment text by code",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
},
"put": {
"security": [
{
"BearerAuth": []
}
],
"description": "Updates the name, localized text and active flag of an existing payment text. The code itself cannot be changed.",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Update a payment text",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
},
{
"description": "Payment text payload",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/paymenttexts.UpdatePaymentTextDTO"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
},
"400": {
"description": "Bad Request",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
},
"delete": {
"security": [
{
"BearerAuth": []
}
],
"description": "Super admin only. Deletes a payment text by code; clients then get the built-in default text for known codes.",
"produces": [
"application/json"
],
"tags": [
"payment-texts"
],
"summary": "Delete a payment text",
"parameters": [
{
"type": "string",
"description": "Text code",
"name": "code",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/appresult.AppSuccess"
}
},
"403": {
"description": "Forbidden",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"404": {
"description": "Not Found",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/appresult.AppError"
}
}
}
}
},
"/permissions": {
"get": {
"security": [
@@ -9351,6 +9548,67 @@
}
}
},
"paymenttexts.ListPaymentTextDTO": {
"type": "object",
"properties": {
"count": {
"type": "integer"
},
"items": {
"type": "array",
"items": {
"$ref": "#/definitions/paymenttexts.PaymentTextDTO"
}
}
}
},
"paymenttexts.PaymentTextDTO": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"id": {
"type": "integer"
},
"isActive": {
"type": "boolean"
},
"name": {
"type": "string"
},
"text": {
"$ref": "#/definitions/shared.LocalizedText"
},
"updatedAt": {
"type": "string"
},
"updatedById": {
"type": "integer"
},
"updatedByName": {
"type": "string"
}
}
},
"paymenttexts.UpdatePaymentTextDTO": {
"type": "object",
"required": [
"isActive",
"name"
],
"properties": {
"isActive": {
"type": "boolean"
},
"name": {
"type": "string"
},
"text": {
"$ref": "#/definitions/shared.LocalizedText"
}
}
},
"perm.Code": {
"type": "string",
"enum": [

View File

@@ -1402,6 +1402,46 @@ definitions:
- sberBankFeeTmt
- tvebFeeUsd
type: object
paymenttexts.ListPaymentTextDTO:
properties:
count:
type: integer
items:
items:
$ref: '#/definitions/paymenttexts.PaymentTextDTO'
type: array
type: object
paymenttexts.PaymentTextDTO:
properties:
code:
type: string
id:
type: integer
isActive:
type: boolean
name:
type: string
text:
$ref: '#/definitions/shared.LocalizedText'
updatedAt:
type: string
updatedById:
type: integer
updatedByName:
type: string
type: object
paymenttexts.UpdatePaymentTextDTO:
properties:
isActive:
type: boolean
name:
type: string
text:
$ref: '#/definitions/shared.LocalizedText'
required:
- isActive
- name
type: object
perm.Code:
enum:
- dashboard
@@ -5149,6 +5189,137 @@ paths:
summary: Update payment settings
tags:
- payment-settings
/payment-texts:
get:
description: Returns the admin-editable, localized texts (warnings, hints) shown
to clients on visa/master/sber payout screens. Clients only get active ones,
with empty languages filled with a default text.
parameters:
- description: Filter by code, name or text
in: query
name: search
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/paymenttexts.ListPaymentTextDTO'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: List payment texts
tags:
- payment-texts
/payment-texts/{code}:
delete:
description: Super admin only. Deletes a payment text by code; clients then
get the built-in default text for known codes.
parameters:
- description: Text code
in: path
name: code
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/appresult.AppSuccess'
"403":
description: Forbidden
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Delete a payment text
tags:
- payment-texts
get:
description: Returns one payment text by its fixed code (e.g. payment_warning_text,
sber_payment_warning). For clients, empty languages are filled with a default
text, a deleted known code returns its default, and inactive texts are 404.
parameters:
- description: Text code
in: path
name: code
required: true
type: string
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/paymenttexts.PaymentTextDTO'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Get a payment text by code
tags:
- payment-texts
put:
consumes:
- application/json
description: Updates the name, localized text and active flag of an existing
payment text. The code itself cannot be changed.
parameters:
- description: Text code
in: path
name: code
required: true
type: string
- description: Payment text payload
in: body
name: body
required: true
schema:
$ref: '#/definitions/paymenttexts.UpdatePaymentTextDTO'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/paymenttexts.PaymentTextDTO'
"400":
description: Bad Request
schema:
$ref: '#/definitions/appresult.AppError'
"404":
description: Not Found
schema:
$ref: '#/definitions/appresult.AppError'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/appresult.AppError'
security:
- BearerAuth: []
summary: Update a payment text
tags:
- payment-texts
/permissions:
get:
description: 'Returns the permission catalog: one code per module, in display

View File

@@ -29,6 +29,7 @@ var swaggerTagOrder = []struct {
{Name: "file-upload", Description: "File upload"},
{Name: "backups", Description: "Database SQL backups"},
{Name: "currencies", Description: "Currency exchange rates"},
{Name: "payment-texts", Description: "Payment warning texts (Visa/Master, Sber)"},
{Name: "dashboard", Description: "Admin dashboard overview"},
}

View File

@@ -53,6 +53,11 @@ func IsOwnScope(c *gin.Context) bool {
return p != nil && p.Scope == ScopeOwn
}
func IsSuper(c *gin.Context) bool {
p := PrincipalFrom(c)
return p != nil && p.IsSuper
}
func HasAllScope(c *gin.Context) bool {
p := PrincipalFrom(c)
return p != nil && p.Scope == ScopeAll

View File

@@ -0,0 +1,114 @@
package db
import (
"context"
"encoding/json"
"strconv"
"strings"
"online-back/internal/payment/paymenttexts"
"online-back/internal/shared"
"online-back/pkg/client/postgresql"
"online-back/pkg/logging"
)
type repository struct {
client postgresql.Client
logger *logging.Logger
}
func NewRepository(client postgresql.Client, logger *logging.Logger) paymenttexts.Repository {
return &repository{client: client, logger: logger}
}
const textColumnsSQL = `t.id, t.code, t.name, t.text, t.is_active, t.updated_by, ` + shared.UserDisplaySQL + `, t.updated_at`
func (r *repository) List(ctx context.Context, filter paymenttexts.ListFilter) (paymenttexts.ListPaymentTextDTO, error) {
var conditions []string
var args []interface{}
if filter.ActiveOnly {
conditions = append(conditions, "t.is_active")
}
if filter.Search != "" {
args = append(args, shared.LikePattern(filter.Search))
n := strconv.Itoa(len(args))
conditions = append(conditions, "(t.code ILIKE $"+n+" OR t.name ILIKE $"+n+" OR t.text::text ILIKE $"+n+")")
}
where := ""
if len(conditions) > 0 {
where = " WHERE " + strings.Join(conditions, " AND ")
}
rows, err := r.client.Query(ctx,
`SELECT `+textColumnsSQL+` FROM payment_texts t LEFT JOIN users u ON u.id = t.updated_by`+where+` ORDER BY t.id ASC`,
args...,
)
if err != nil {
return paymenttexts.ListPaymentTextDTO{}, err
}
defer rows.Close()
items := []paymenttexts.PaymentTextDTO{}
for rows.Next() {
item, err := scanText(rows)
if err != nil {
return paymenttexts.ListPaymentTextDTO{}, err
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
return paymenttexts.ListPaymentTextDTO{}, err
}
return paymenttexts.ListPaymentTextDTO{Count: len(items), Items: items}, nil
}
func (r *repository) GetByCode(ctx context.Context, code string) (paymenttexts.PaymentTextDTO, error) {
return scanText(r.client.QueryRow(ctx,
`SELECT `+textColumnsSQL+` FROM payment_texts t LEFT JOIN users u ON u.id = t.updated_by WHERE t.code = $1`,
code,
))
}
func (r *repository) Update(ctx context.Context, code string, dto paymenttexts.UpdatePaymentTextDTO) (paymenttexts.PaymentTextDTO, error) {
text, err := json.Marshal(dto.Text)
if err != nil {
return paymenttexts.PaymentTextDTO{}, err
}
query := `
WITH t AS (
UPDATE payment_texts SET
name = $2, text = $3, is_active = $4, updated_by = $5,
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
WHERE code = $1
RETURNING *
)
SELECT ` + textColumnsSQL + ` FROM t LEFT JOIN users u ON u.id = t.updated_by`
return scanText(r.client.QueryRow(ctx, query, code, dto.Name, text, *dto.IsActive, dto.UpdatedBy))
}
func (r *repository) Delete(ctx context.Context, code string) (bool, error) {
tag, err := r.client.Exec(ctx, `DELETE FROM payment_texts WHERE code = $1`, code)
if err != nil {
return false, err
}
return tag.RowsAffected() > 0, nil
}
func scanText(row interface {
Scan(dest ...interface{}) error
}) (paymenttexts.PaymentTextDTO, error) {
var item paymenttexts.PaymentTextDTO
var text []byte
if err := row.Scan(
&item.Id, &item.Code, &item.Name, &text, &item.IsActive, &item.UpdatedById, &item.UpdatedByName, &item.UpdatedAt,
); err != nil {
return paymenttexts.PaymentTextDTO{}, err
}
if err := shared.UnmarshalLocalized(text, &item.Text); err != nil {
return paymenttexts.PaymentTextDTO{}, err
}
return item, nil
}

View File

@@ -0,0 +1,67 @@
package paymenttexts
import (
"strings"
"online-back/internal/shared"
)
// defaultTexts is what clients get when a known code's row is missing
// (deleted) or a language is left empty in the admin UI, so the payout
// screens never show a blank warning.
var defaultTexts = map[string]shared.LocalizedText{
"payment_warning_text": {
Tm: "Dogry töleg aýyny saýlamagyňyzy haýyş edýäris",
Ru: "Пожалуйста, убедитесь, что выбран правильный месяц оплаты",
En: "Please make sure you select the correct payment month",
},
"sber_payment_warning": {
Tm: "Sber arkaly töleg geçirmezden öň maglumatlaryňyzyň dogrudygyny barlaň",
Ru: "Перед оплатой через Сбер проверьте правильность ваших данных",
En: "Please check that your details are correct before paying via Sber",
},
}
// genericText covers unknown codes whose text is entirely empty.
var genericText = shared.LocalizedText{
Tm: "Töleg geçirmezden öň maglumatlaryňyzyň dogrudygyny barlaň",
Ru: "Перед оплатой проверьте правильность ваших данных",
En: "Please check that your details are correct before paying",
}
// defaultItem stands in for a known code whose row does not exist.
func defaultItem(code string) (PaymentTextDTO, bool) {
text, ok := defaultTexts[code]
if !ok {
return PaymentTextDTO{}, false
}
return PaymentTextDTO{Code: code, Name: code, Text: text, IsActive: true}, true
}
// withFallback fills every empty language: first from the code's default,
// then from another language the admin did fill in, then from genericText.
func withFallback(item PaymentTextDTO) PaymentTextDTO {
def, known := defaultTexts[item.Code]
if !known {
def = shared.LocalizedText{}
}
filled := firstNonEmpty(item.Text.Tm, item.Text.Ru, item.Text.En)
pick := func(own, fromDefault, generic string) string {
return firstNonEmpty(own, fromDefault, filled, generic)
}
item.Text = shared.LocalizedText{
Tm: pick(item.Text.Tm, def.Tm, genericText.Tm),
Ru: pick(item.Text.Ru, def.Ru, genericText.Ru),
En: pick(item.Text.En, def.En, genericText.En),
}
return item
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}

View File

@@ -0,0 +1,43 @@
package paymenttexts
import (
"testing"
"online-back/internal/shared"
)
func TestWithFallback(t *testing.T) {
cases := []struct {
name string
in PaymentTextDTO
want shared.LocalizedText
}{
{
name: "filled text is kept",
in: PaymentTextDTO{Code: "payment_warning_text", Text: shared.LocalizedText{Tm: "a", Ru: "b", En: "c"}},
want: shared.LocalizedText{Tm: "a", Ru: "b", En: "c"},
},
{
name: "known code: empty languages take the default",
in: PaymentTextDTO{Code: "payment_warning_text", Text: shared.LocalizedText{Tm: "a", Ru: " "}},
want: shared.LocalizedText{Tm: "a", Ru: defaultTexts["payment_warning_text"].Ru, En: defaultTexts["payment_warning_text"].En},
},
{
name: "unknown code: empty languages copy a filled one",
in: PaymentTextDTO{Code: "other", Text: shared.LocalizedText{Ru: "b"}},
want: shared.LocalizedText{Tm: "b", Ru: "b", En: "b"},
},
{
name: "unknown code, all empty: generic text",
in: PaymentTextDTO{Code: "other"},
want: genericText,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := withFallback(tc.in).Text; got != tc.want {
t.Fatalf("got %+v, want %+v", got, tc.want)
}
})
}
}

View File

@@ -0,0 +1,39 @@
// Package paymenttexts holds the admin-editable, localized texts (warnings,
// hints) shown to clients around a visa/master/sber payout. Rows are keyed by
// a fixed code the client apps depend on, so the admin API can only edit
// existing rows - codes are added by migration.
package paymenttexts
import (
"time"
"online-back/internal/shared"
)
type PaymentTextDTO struct {
Id int64 `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Text shared.LocalizedText `json:"text"`
IsActive bool `json:"isActive"`
UpdatedById *int64 `json:"updatedById,omitempty"`
UpdatedByName string `json:"updatedByName,omitempty"`
UpdatedAt time.Time `json:"updatedAt"`
}
type ListPaymentTextDTO struct {
Count int `json:"count"`
Items []PaymentTextDTO `json:"items"`
}
type UpdatePaymentTextDTO struct {
Name string `json:"name" binding:"required"`
Text shared.LocalizedText `json:"text"`
IsActive *bool `json:"isActive" binding:"required"`
UpdatedBy *int64 `json:"-"`
}
type ListFilter struct {
Search string
ActiveOnly bool
}

View File

@@ -0,0 +1,182 @@
package paymenttexts
import (
"errors"
"net/http"
"strings"
"online-back/internal/appresult"
"online-back/internal/handlers"
"online-back/internal/identity/rbac"
"online-back/internal/identity/rbac/perm"
"online-back/internal/shared"
"online-back/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4"
)
const baseURL = "/payment-texts"
type handler struct {
logger *logging.Logger
repository Repository
}
func NewHandler(logger *logging.Logger, repository Repository) handlers.Handler {
return &handler{logger: logger, repository: repository}
}
// Catalog: clients read the texts too (the payout screens show them);
// editing needs payment-settings. Codes are added by migration because the
// client apps look them up by code; only a super admin may delete one, and
// clients then get its built-in default (see defaults.go).
func (h *handler) Register(router *gin.RouterGroup) {
group := rbac.Group(router, baseURL, rbac.Catalog(perm.PaymentSettings))
group.GET("", h.list)
group.GET("/:code", h.getByCode)
group.PUT("/:code", h.update)
group.DELETE("/:code", h.delete)
}
// list godoc
// @Summary List payment texts
// @Description Returns the admin-editable, localized texts (warnings, hints) shown to clients on visa/master/sber payout screens. Clients only get active ones, with empty languages filled with a default text.
// @Tags payment-texts
// @Produce json
// @Security BearerAuth
// @Param search query string false "Filter by code, name or text"
// @Success 200 {object} ListPaymentTextDTO
// @Failure 500 {object} appresult.AppError
// @Router /payment-texts [get]
func (h *handler) list(c *gin.Context) {
filter := ListFilter{
Search: shared.QueryValue(c, "search", "q"),
ActiveOnly: rbac.IsOwnScope(c),
}
result, err := h.repository.List(c.Request.Context(), filter)
if err != nil {
h.logger.Errorf("list payment texts failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if filter.ActiveOnly {
for i := range result.Items {
result.Items[i] = withFallback(result.Items[i])
}
}
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
}
// getByCode godoc
// @Summary Get a payment text by code
// @Description Returns one payment text by its fixed code (e.g. payment_warning_text, sber_payment_warning). For clients, empty languages are filled with a default text, a deleted known code returns its default, and inactive texts are 404.
// @Tags payment-texts
// @Produce json
// @Security BearerAuth
// @Param code path string true "Text code"
// @Success 200 {object} PaymentTextDTO
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-texts/{code} [get]
func (h *handler) getByCode(c *gin.Context) {
code := strings.TrimSpace(c.Param("code"))
client := rbac.IsOwnScope(c)
item, err := h.repository.GetByCode(c.Request.Context(), code)
if errors.Is(err, pgx.ErrNoRows) {
if def, ok := defaultItem(code); ok && client {
c.JSON(http.StatusOK, appresult.SuccessWithData(def))
return
}
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("get payment text failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if client {
if !item.IsActive {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
item = withFallback(item)
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// update godoc
// @Summary Update a payment text
// @Description Updates the name, localized text and active flag of an existing payment text. The code itself cannot be changed.
// @Tags payment-texts
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param code path string true "Text code"
// @Param body body UpdatePaymentTextDTO true "Payment text payload"
// @Success 200 {object} PaymentTextDTO
// @Failure 400 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-texts/{code} [put]
func (h *handler) update(c *gin.Context) {
var dto UpdatePaymentTextDTO
if err := c.ShouldBindJSON(&dto); err != nil || strings.TrimSpace(dto.Name) == "" {
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
return
}
dto.Name = strings.TrimSpace(dto.Name)
if id, ok := rbac.CurrentUserID(c); ok {
dto.UpdatedBy = &id
}
item, err := h.repository.Update(c.Request.Context(), strings.TrimSpace(c.Param("code")), dto)
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
if err != nil {
h.logger.Errorf("update payment text failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
}
// delete godoc
// @Summary Delete a payment text
// @Description Super admin only. Deletes a payment text by code; clients then get the built-in default text for known codes.
// @Tags payment-texts
// @Produce json
// @Security BearerAuth
// @Param code path string true "Text code"
// @Success 200 {object} appresult.AppSuccess
// @Failure 403 {object} appresult.AppError
// @Failure 404 {object} appresult.AppError
// @Failure 500 {object} appresult.AppError
// @Router /payment-texts/{code} [delete]
func (h *handler) delete(c *gin.Context) {
if !rbac.IsSuper(c) {
c.JSON(http.StatusForbidden, appresult.ErrForbidden)
return
}
deleted, err := h.repository.Delete(c.Request.Context(), strings.TrimSpace(c.Param("code")))
if err != nil {
h.logger.Errorf("delete payment text failed: %v", err)
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
return
}
if !deleted {
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
return
}
c.JSON(http.StatusOK, appresult.SuccessWithData("payment text removed"))
}

View File

@@ -0,0 +1,10 @@
package paymenttexts
import "context"
type Repository interface {
List(ctx context.Context, filter ListFilter) (ListPaymentTextDTO, error)
GetByCode(ctx context.Context, code string) (PaymentTextDTO, error)
Update(ctx context.Context, code string, dto UpdatePaymentTextDTO) (PaymentTextDTO, error)
Delete(ctx context.Context, code string) (bool, error)
}

View File

@@ -11,6 +11,8 @@ import (
paymenthistorydb "online-back/internal/payment/paymenthistory/db"
"online-back/internal/payment/paymentsettings"
paymentsettingsdb "online-back/internal/payment/paymentsettings/db"
"online-back/internal/payment/paymenttexts"
paymenttextsdb "online-back/internal/payment/paymenttexts/db"
"online-back/internal/payment/visamasterpay"
visamasterpaydb "online-back/internal/payment/visamasterpay/db"
"online-back/pkg/client/postgresql"
@@ -31,6 +33,7 @@ func Handlers(client postgresql.Client, logger *logging.Logger, currencyRepo cur
settingsRepo := paymentsettingsdb.NewRepository(client, logger)
return []handlers.Handler{
paymentsettings.NewHandler(logger, settingsRepo),
paymenttexts.NewHandler(logger, paymenttextsdb.NewRepository(client, logger)),
visamasterpay.NewHandler(logger, visamasterpaydb.NewRepository(client, logger, currencyRepo, settingsRepo, gateway, publicBaseURL)),
paymenthistory.NewHandler(logger, paymenthistorydb.NewRepository(client, logger, publicBaseURL)),
}