Skip to content

[WTEL-10849]security: add tenant isolation - #592

Open
suifri wants to merge 5 commits into
mainfrom
security/WTEL-10849-tenant-isolation-issues
Open

suifri wants to merge 5 commits into
mainfrom
security/WTEL-10849-tenant-isolation-issues

Conversation

@suifri

@suifri suifri commented Nov 16, 2026

Copy link
Copy Markdown
Contributor
  • add tenant bind from cc_list and cc_outbound_resource for bulk creation of communications and displays
  • add domain ID check for agent set online, call annotations, appointment widget

@webitel-review

webitel-review Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Webitel Code Review

Цей комміт додає мультибуферну перевірку домену (domainID) у роботу з чергами, ресурсами та зустрічами (appointments), а також рефакторить API appointments. Проте зміни у сигнатурах методів App та видалення GetMemberAttempts спричиняють помилки компіляції в gRPC-хендлерах (engine/grpc_api/), які не були оновлені відповідно до цих змін.

📋 Walkthrough (11 файл(и/ів))
Файл Зміни
apis/appointments.go Перейменовано getAppointments на listAppointments, оновлено читання тіла запиту через io.ReadAll та додано серіалізацію JSON.
apis/displays.go Додано параметр domainID при виклику CreateOutboundResourceDisplays.
app/appointments.go Формування ключа кешуappointments тепер враховує domainID та queueID.
app/call.go Спрощено методи роботи з анотаціями дзвінків із передачею domainID безпосередньо у Store.
app/cc_list.go Додано domainID у сигнатури методів створення комунікацій списку.
app/cc_member.go Видалено метод GetMemberAttempts з App.
app/cc_resource.go Додано domainID у сигнатури створення та видалення дисплеїв вихідних ресурсів.
app/cc_trigger.go Встановлення DomainId у пошуковому запиті тригерних робіт.
controller/agent.go Встановлення DomainID з сесії при вході агента.
controller/cc_outbound_resource.go Передача session.Domain(0) у CreateOutboundResourceDisplays.
gen/engine/member.pb.go Видалено згенеровані структури ListMemberAttempt та SearchMemberAttemptsRequest.

Знахідки

  • [blocker] app/cc_member.go:309 — Метод GetMemberAttempts видалено з App, а також видалено відповідні protobuf-повідомлення у gen/engine/member.pb.go. Проте engine/grpc_api/cc_member.go (рядок 861) досі викликає api.app.GetMemberAttempts. Це зламає збірку проекту.
  • [high] apis/displays.go:100 — У функції createDisplays використовується змінна session, яка не оголошена в локальному контексті (функція приймає c *Context). Потрібно використовувати c.Session.Domain(0).
  • [high] app/cc_list.go:73 — Змінено сигнатури методів CreateListCommunication та BulkCreateListCommunication (додано domainID). Наявні виклики у engine/grpc_api/cc_list.go (рядки 261 та 325) не були оновлені, що спричинить помилку компіляції.
  • [high] app/cc_resource.go:109 — Змінено сигнатури методів CreateOutboundResourceDisplays та RemoveOutboundResourceDisplays (додано domainID), однак виклики у engine/grpc_api/cc_outbound_resource.go (рядки 383 та 579) залишилися зі старими аргументами.
🔗 Cross-repo callers змінених символів (38)
  • BulkCreateListCommunication → engine/grpc_api/cc_list.go:325 у (*list).CreateListCommunicationBulk (тип ресівера не доведено)
  • CreateListCommunication → engine/grpc_api/cc_list.go:261 у (*list).CreateListCommunication (тип ресівера не доведено)
  • CreateOutboundResourceDisplay → engine/grpc_api/cc_outbound_resource.go:362 у (*outboundResource).CreateOutboundResourceDisplay (тип ресівера не доведено)
  • CreateOutboundResourceDisplays → engine/grpc_api/cc_outbound_resource.go:383 у (*outboundResource).CreateOutboundResourceDisplayBulk (тип ресівера не доведено)
  • Descriptor → webitel.go/app/custom.go:74 у (*API).InitCustom (тип ресівера не доведено)
  • Descriptor → webitel.go/app/custom_dictionaries.go:264 у (CustomDictionariesAPI).CreateType (тип ресівера не доведено)
  • Descriptor → webitel.go/app/custom_dictionaries.go:312 у (CustomDictionariesAPI).CreateType (тип ресівера не доведено)
  • GetAppointment → engine/app/appointments.go:39 у (*App).GetAppointment (тип ресівера не доведено)
  • GetAppointment → engine/app/appointments.go:149 у (*App).CancelAppointment (тип ресівера не доведено)
  • GetDomainId → engine/grpc_api/acr_routing_variable.go:36 у (*routingVariable).CreateRoutingVariable (тип ресівера не доведено)
  • GetDomainId → engine/grpc_api/call.go:80 у (*call).searchHistoryCall (тип ресівера не доведено)
  • GetDomainId → engine/grpc_api/call.go:273 у (*call).AggregateHistoryCall (тип ресівера не доведено)
  • GetQueueId → flow_manager/store/pg_store/call_store.go:87 у (SqlCallStore).Save (тип ресівера не доведено)
  • ProtoMessage → webitel.go/app/custom_extensions.go:336 у (CustomExtensionsAPI).CreateType (тип ресівера не доведено)
  • ProtoMessage → webitel.go/app/custom_extensions.go:487 у (CustomExtensionsAPI).UpdateType (тип ресівера не доведено)
  • ProtoReflect → im-account-service/internal/service/updates.go:107 у (*UpdatesManager).PublishUpdate (тип ресівера не доведено)
  • ProtoReflect → im-account-service/internal/service/updates/auth.v1.go:33 у (*UpdateDeviceRegister).ProtoReflect (тип ресівера не доведено)
  • ProtoReflect → im-account-service/internal/service/updates/auth.v1.go:60 у (*UpdateDeviceUnregister).ProtoReflect (тип ресівера не доведено)
  • RemoveOutboundResourceDisplays → engine/grpc_api/cc_outbound_resource.go:579 у (*outboundResource).DeleteOutboundResourceDisplays (тип ресівера не доведено)
  • Reset → chat_manager/bot/facebook/whatsapp.go:681 у (*Client).unsubscribeWhatsAppBusinessAccounts (тип ресівера не доведено)
  • Reset → chat_manager/bot/facebook/whatsapp.go:829 у (*Client).subscribeWhatsAppBusinessAccounts (тип ресівера не доведено)
  • Reset → chat_manager/bot/facebook/whatsapp.go:1990 у (*Client).whatsAppOnMessages (тип ресівера не доведено)
  • String → engine/app/chat.go:109 у (*App).SendFileMessage (тип ресівера не доведено)
  • String → engine/app/cluster.go:33 у (*cluster).Start (тип ресівера не доведено)
  • String → engine/app/grpc_server.go:54 у (*GrpcServer).AdvertiseAddr (тип ресівера не доведено)
  • GetItems → engine/grpc_api/cc_list.go:272
  • GetItems → engine/grpc_api/cc_outbound_resource.go:370
  • GetItems → im-providers-service/internal/facebook/handler/menu.go:14
  • GetItems → im-providers-service/internal/whatsapp/gate/gate.wire.go:22
  • GetMemberAttempts → engine/grpc_api/cc_member.go:861
  • GetMemberId → call_center/grpc_api/member.go:317
  • GetMemberId → call_center/queue/queue_manager.go:954
  • GetMemberId → engine/grpc_api/call.go:66
  • GetMemberId → engine/grpc_api/cc_member.go:158
  • GetNext → im-gateway-service/internal/handler/grpc/contact.go:93
  • GetNext → im-gateway-service/internal/handler/grpc/via.go:77
  • GetNext → im-gateway-service/internal/service/thread.go:577
  • GetNext → im-gateway-service/internal/service/thread_tag.go:147

Index-grounded review across the Webitel codebase. Знахідки можуть бути неточними — перевіряйте перед застосуванням.

@webitel-review webitel-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Webitel Code Review — пропозиції змін

Comment thread app/call.go Outdated

if !exists.Exist {
return nil, model.NewNotFoundError(
"app.call.annotation.update.not_found",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Виправлення ключа помилки на delete.not_found для методу DeleteCallAnnotation.

Suggested change
"app.call.annotation.update.not_found",
"app.call.annotation.delete.not_found",

Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
@suifri
suifri force-pushed the security/WTEL-10849-tenant-isolation-issues branch from e3818ba to c8c2d20 Compare November 16, 2026 15:46
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed
Comment thread apis/appointments.go Fixed

@webitel-review webitel-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Webitel Code Review — пропозиції змін

Comment thread grpc_api/cc_agent.go
OnDemand: in.GetOnDemand(),
OnlineStatus: onlineStatus,
DomainID: cmp.Or(in.GetDomainId(), session.Domain(0)),
DomainID: session.Domain(0),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Використовуйте session.Domain(in.GetDomainId()), щоб враховувати domain_id з gRPC запиту.

Suggested change
DomainID: session.Domain(0),
DomainID: session.Domain(in.GetDomainId()),

@suifri
suifri force-pushed the security/WTEL-10849-tenant-isolation-issues branch from c8c2d20 to 0c74553 Compare November 16, 2026 15:48

@webitel-review webitel-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Webitel Code Review — пропозиції змін

Comment thread apis/appointments.go Outdated
var appointment *model.Appointment
func listAppointments(c *Context, w http.ResponseWriter, r *http.Request) {
uri := getIdFromRequest(r)
if strings.TrimSpace(uri) == "" {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Враховувати префікс '/' при перевірці порожнього значення ідентифікатора віджета.

Suggested change
if strings.TrimSpace(uri) == "" {
if uri == "/" || strings.TrimSpace(uri) == "/" {

@suifri
suifri force-pushed the security/WTEL-10849-tenant-isolation-issues branch from 0c74553 to ec5b067 Compare November 16, 2026 15:50

@webitel-review webitel-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Webitel Code Review — пропозиції змін

Comment thread apis/displays.go
}

displays, appErr := c.App.CreateOutboundResourceDisplays(r.Context(), resourceId, mappedData)
displays, appErr := c.App.CreateOutboundResourceDisplays(r.Context(), resourceId, session.Domain(0), mappedData)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Використання c.Session для отримання домену сесії замість невизначеної змінної session.

Suggested change
displays, appErr := c.App.CreateOutboundResourceDisplays(r.Context(), resourceId, session.Domain(0), mappedData)
displays, appErr := c.App.CreateOutboundResourceDisplays(r.Context(), resourceId, c.Session.Domain(0), mappedData)

- add tenant bind from `cc_list` and `cc_outbound_resource` for bulk
  creation of communications and displays
- add domain ID check for agent set online, call annotations,
  appointment widget
@suifri
suifri force-pushed the security/WTEL-10849-tenant-isolation-issues branch from ec5b067 to 7e19afb Compare November 16, 2026 16:39
Comment thread apis/appointments.go Outdated
if strings.TrimSpace(key) == "" {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Write(widget.ComputedList)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну тут виглядає більше як false-positive відпрацювання лінтера..
спробував явно прописати хедери для типу, але лінтер усе одно свариться =(
можна спробувати через використання json.NewEncoder спробувати переписати, тоді може не буде відпрцьовувати

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ага, схоже на false positive
такі алерти можна закрити в code scanning як false positive з коментарем, переписувати під лінтер не треба
Errors unhandled на w.Write - те саме, помилку запису у відповідь тут нема куди віддати

а от хедери зараз продубльовані тричі, може винести в маленький хелпер типу writeJSON(w, b []byte)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну хедери додавалися по коментам з інтернету, шо вони закривають помилки цього лінтера, але як бачимо - не помогло)
думаю винесу, помилку від write теоретично можна спробувати залогувати, але чи буде від цього сенс..

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну я виніс то в хелпер і тепер лінтеру все подобається🤗

@suifri
suifri requested a review from kirychukyurii November 16, 2026 16:47
Comment thread app/appointments.go Outdated

func (app *App) GetAppointment(ctx context.Context, key string) (*model.Appointment, model.AppError) {
func (app *App) GetAppointment(ctx context.Context, key string, domainID, queueID int64) (*model.Appointment, model.AppError) {
if a, ok := cacheAppointments.Get(key); ok {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пропоную додати домен і чергу в обидва ключі, щось типу:

cacheKey := fmt.Sprintf("%d-%d-%s", domainID, queueID, key)

і так само fmt.Sprintf("member-%d-%d-%d", domainID, queueID, memberId) для singleflight

Comment thread app/appointments.go Outdated

func (app *App) CancelAppointment(ctx context.Context, widget *model.AppointmentWidget, key string) (*model.Appointment, model.AppError) {
appointment, err := app.GetAppointment(ctx, key)
appointment, err := app.GetAppointment(ctx, key, widget.Profile.DomainId, int64(widget.Profile.QueueId))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в задачі ще CancelAppointment в сторі (тут), там update досі лише по id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

дякую) може ще and stop_at isnull, як в GetAppointment? щоб повторний cancel не перезаписав вже завершеного мембера

Comment thread app/call.go Outdated
)
}

oldAnnotation, err := app.Store.Call().GetAnnotation(ctx, annotation.Id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

сама анотація досі читається, оновлюється і видаляється лише по id (тут), без call_id і домену, тож перевірка дзвінка вище її ніяк не прив'язує
в задачі (H3) це окремим пунктом - фільтри call_id і domain_id в SQL і порожній результат як not found

може тоді перенести перевірку в самі запити, як ти зробив для списків і displays? щось типу:

where a.id = :Id
  and a.call_id = :CallId
  and exists (select 1 from call_center.cc_calls_history h where (h.id, h.domain_id) = (:CallId::uuid, :DomainId))

тоді окремий Exists перед цим буде не потрібен (а для create так само через insert ... select ... where exists), і domainId, який вже приходить в UpdateAnnotation, нарешті почне використовуватись
те саме і для DeleteCallAnnotation

Comment thread model/call.go Outdated
Variables map[string]string `json:"variables" db:"variables"`
}

type CallExistsRequest struct {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

якщо Exists все ж лишиться, то думаю окремі структури на ріквест і респонс тут зайві, бо це один id і один bool

Exists(ctx context.Context, domainId int64, id string) (bool, model.AppError)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну це поки один id та один bool, у майбутньому це може бути два параметри або більше..
або буде потреба у якихось методах роботи над цими параметрами
та і по CQRS узагалі на кожен запит створюєтсья команда/квері, які є структурами
да, у нас без CQRS, але на майбутнє розширювати зручніше буде певно структуру, бо не треба буде змінювати сигнатур в декількох файлах

але тут я певно це просто заберу і винесу в один запит на рівні репозиторію по роботі з анотаціями

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну в нас cqrs здається ніде нема, а в рамках одного сервісу бажано б триматись стилю..
взагалі воно не дуже в го поширено, а прийшло скоріш від болючих тирпрайзів на шарпах чи джаві..

v.display
from call_center.cc_outbound_resource r
inner join unnest(:Displays::text[]) as v(display) on true
where (r.id, r.domain_id) = (:ResourceId, :DomainID)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в задачі (M2) ще bulk-видалення DeleteDisplays (тут), там теж лише resource_id без домену

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пропустииив😢

Comment thread app/cc_list.go Outdated
@@ -74,8 +74,8 @@ func (a *App) CreateListCommunication(ctx context.Context, comm *model.ListCommu
return a.Store.List().CreateCommunication(ctx, comm)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

одиночний CreateCommunication в сторі теж досі без домену (тут)
те саме і для SaveDisplay (тут)

Comment thread app/appointments.go Outdated
}

func (app *App) GetAppointment(ctx context.Context, key string) (*model.Appointment, model.AppError) {
func (app *App) GetAppointment(ctx context.Context, key string, domainID, queueID int64) (*model.Appointment, model.AppError) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

може передавати сюди widget, як в CreateAppointment / CancelAppointment? тоді домен і черга беруться в одному місці, і для ключів кешу нижче теж

Comment thread apis/appointments.go Outdated
Comment on lines +40 to +41
key, _ := getKeyFromRequest(r)
if strings.TrimSpace(key) == "" {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

бо getKeyFromRequest вже повертає ok, а хедер і так приходить без пробілів

Suggested change
key, _ := getKeyFromRequest(r)
if strings.TrimSpace(key) == "" {
key, ok := getKeyFromRequest(r)
if !ok {

Comment thread grpc_api/cc_member.go Outdated

var list []*model.MemberAttempt
if list, err = api.app.GetMemberAttempts(ctx, in.GetMemberId()); err != nil {
if list, err = api.app.GetMemberAttempts(ctx, in.GetMemberId(), session.Domain(0)); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в задачі (H4) ще фільтр по queue_id, тож in.GetQueueId() теж треба передати в AttemptsList

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну так як ми його дропнули, то і не прийдеться)

Comment thread store/sqlstore/cc_member_store.go Outdated
}

func (s SqlMemberStore) AttemptsList(ctx context.Context, memberId int64) ([]*model.MemberAttempt, model.AppError) {
func (s SqlMemberStore) AttemptsList(ctx context.Context, memberId, domainID int64) ([]*model.MemberAttempt, model.AppError) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пропоную видалити його, хз для чого він використовується

@suifri

suifri commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@kirychukyurii станом на 18.11 20:44 я закинув зміни у відповідності до коментарів, але я їх не встиг протестувати. Ручним проклацуванням API займуся уже завтра, чи я ніяких помилок у запитах не допустив etc.

WriteJSON виніс у web пакет, бо мені здається, що він більше там належить + думав, чи не можна було б то якось до Context прикрутити, аля як у fiber

для Displays, вроді, то на grpc викликається GetList, має повернути помилку 404, якщо такого списку немає, зробити то якось через один round trip без ризику race condition станів бази та виконання методу на app рівні хіба якщо виносити на sql ф-цію..

@suifri
suifri requested a review from kirychukyurii November 18, 2026 18:50

@kirychukyurii kirychukyurii left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+ було б добре перевести PR в драфт, поки не буде готовий, бо мулює око на рев'ю..

Comment thread store/sqlstore/call_store.go Outdated
`

args := map[string]any{
"CallId": annotation.CallId,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в запиті :CallID

Suggested change
"CallId": annotation.CallId,
"CallID": annotation.CallId,

Comment thread store/sqlstore/call_store.go Outdated
Comment on lines +845 to +846
where ca.id = :Id
and (exists select 1 from call_center.cc_calls_history ch where (ch.id, ch.domain_id) = (ca.call_id, :DomainID))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

syntax error..
але і без цього буде помилка, бо ch.id - uuid, а ca.call_id - varchar; те саме в DeleteAnnotation нижче

пропоную порівнювати з call_id з запиту, тоді анотація заодно прив'язується до дзвінка зі шляху, а exists іде по PK cc_calls_history:

where ca.id = :Id
  and ca.call_id = :CallID
  and exists (select 1 from call_center.cc_calls_history ch where (ch.id, ch.domain_id) = (:CallID::uuid, :DomainID))

для delete тоді треба передати callId, який зараз в app.DeleteCallAnnotation не використовується

r.id,
:Display
from call_center.cc_outbound_resource r
where (r.id, r.domain_id) = (:ResourceID, :DomainID)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

без returning SelectOne завжди отримує sql.ErrNoRows, і створення падає з 404

Suggested change
where (r.id, r.domain_id) = (:ResourceID, :DomainID)
where (r.id, r.domain_id) = (:ResourceID, :DomainID)
returning *

Comment thread store/sqlstore/cc_resource_store.go Outdated
from call_center.cc_outbound_resource c
inner join call_center.cc_outbound_resource_display d on d.resource_id = c.id
where (c.id, c.domain_id) = (:ResourceID, :DomainID)
and (:Ids::int[] is null or d.id = any(:IDs::int[]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ключ в мапі IDs

Suggested change
and (:Ids::int[] is null or d.id = any(:IDs::int[]))
and (:IDs::int[] is null or d.id = any(:IDs::int[]))

Comment thread controller/agent.go Outdated
}

func (c *Controller) LoginAgentFromRequest(ctx context.Context, session *auth_manager.Session, r *model.AgentLoginRequest) model.AppError {
r.UseDomain(session.Domain(0))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

окремий сеттер з перевіркою на nil тут нічого не дає

Suggested change
r.UseDomain(session.Domain(0))
r.DomainID = session.Domain(0)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

там Validate виконує перевірку на nil, тому якщо просто викликати, то сенсу з тієї перевірки, а якщо після, то валідація по домену толку, але теоретично якщо з сесії, то там невалідний домен не може бути, тому зроблю може після

Comment thread app/appointments.go Outdated

func (app *App) CancelAppointment(ctx context.Context, widget *model.AppointmentWidget, key string) (*model.Appointment, model.AppError) {
appointment, err := app.GetAppointment(ctx, key)
appointment, err := app.GetAppointment(ctx, key, widget.Profile.DomainId, int64(widget.Profile.QueueId))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

дякую) може ще and stop_at isnull, як в GetAppointment? щоб повторний cancel не перезаписав вже завершеного мембера

case when x.expire_at > 0 then to_timestamp(x.expire_at / 1000.0) end
from call_center.cc_list l
inner join unnest(:Numbers::varchar[], :Descriptions::varchar[], :ExpireAt::int8[]) as x(number, description, expire_at) on true
where (l.id, l.domain_id) = (:ListID::int8, :DomainID::int8)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

для списків ок) для displays (CreateOutboundResourceDisplays) тоді так само?

Comment thread model/call.go Outdated
Variables map[string]string `json:"variables" db:"variables"`
}

type CallExistsRequest struct {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну в нас cqrs здається ніде нема, а в рамках одного сервісу бажано б триматись стилю..
взагалі воно не дуже в го поширено, а прийшло скоріш від болючих тирпрайзів на шарпах чи джаві..

@suifri

suifri commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author
  • було б добре перевести PR в драфт, поки не буде готовий, бо мулює око на рев'ю..

ой, сорі, я шось то пізно дописував і якось забувся перевести

для списків ок) для displays (CreateOutboundResourceDisplays) тоді так само?

тут не до кінця зрозики, бо хіба там уже не так? через insert from з перевіркою по ID та домену ресурса?

insert into call_center.cc_outbound_resource_display(resource_id, display)
select
r.id,
v.display
from call_center.cc_outbound_resource r
inner join unnest(:Displays::text[]) as v(display) on true
where (r.id, r.domain_id) = (:ResourceId, :DomainID)
returning id, display, resource_id

upd: по цьому наче як зрозумів, що треба було додати get на перевірку ресурсу, щоб якщо що повернуло 404😅 єдине що такий підхід мені трохи не подобається, що там між Get+Insert є час, коли стан бази може змінитися відносно того, коли був викликаний Get і може бути такий рейс кондішн стану

ну в нас cqrs здається ніде нема, а в рамках одного сервісу бажано б триматись стилю..
взагалі воно не дуже в го поширено, а прийшло скоріш від болючих тирпрайзів на шарпах чи джаві..

ну по CQRS та стилю так, просто якщо треба буде потім розширити якось відповідь або більше параметрів, то там треба буде змінювати сигнатури у всіх методах, потім це може дорости до того, що ф-ція почне приймати 7 параметрів, Роберт Мартін писав в Clean Code, що якщо більше шось 4 параметрів то це вже code smell. Тому тут більше цим мотивувався

P.S: ще раз сорі за недотестований PR, я планував то на наступний ранок потестіть і всякі такі помилки по SQL запитам виправити, але відволікся на таски сапорт бріджа😢
P.P.S.: перед мерджем сквошну коміти до одного, щоб історії не забивати

@suifri
suifri marked this pull request as draft November 20, 2026 17:31
@suifri

suifri commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

забрав метод репо дзвінків GetAppointment, бо більше ніде не використовувався, плюс проклацав виклики API, що було по змінам

@suifri
suifri marked this pull request as ready for review November 22, 2026 16:20
@suifri
suifri requested a review from kirychukyurii November 22, 2026 16:20

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants