nidus-sync/platform/contact.go

77 lines
2.3 KiB
Go
Raw Normal View History

2026-05-15 20:10:14 +00:00
package platform
import (
"context"
"fmt"
"time"
2026-05-15 20:10:14 +00:00
"github.com/Gleipnir-Technology/nidus-sync/db"
modelcomms "github.com/Gleipnir-Technology/nidus-sync/db/gen/nidus-sync/comms/model"
2026-05-15 20:10:14 +00:00
querycomms "github.com/Gleipnir-Technology/nidus-sync/db/query/comms"
"github.com/Gleipnir-Technology/nidus-sync/platform/types"
)
func ContactsForOrganization(ctx context.Context, org_id int32) (results []types.Contact, err error) {
txn := db.PGInstance.PGXPool
rows, err := querycomms.ContactsFromOrganizationID(ctx, txn, int64(org_id))
if err != nil {
return results, fmt.Errorf("contacts from organization id: %w", err)
}
contact_ids := make([]int64, len(rows))
for i, row := range rows {
contact_ids[i] = int64(row.ID)
}
contact_emails_by_contact_id, err := querycomms.ContactEmailByContactIDs(ctx, txn, contact_ids)
if err != nil {
return results, fmt.Errorf("by contact ids: %w", err)
}
contact_phones_by_contact_id, err := querycomms.ContactPhoneByContactIDs(ctx, txn, contact_ids)
if err != nil {
return results, fmt.Errorf("by contact ids: %w", err)
}
results = make([]types.Contact, 0)
for _, row := range rows {
2026-05-18 15:22:24 +00:00
// Exclude the magic Nidus contact
if row.ID == 1 {
continue
}
2026-05-15 20:10:14 +00:00
contact_emails := contact_emails_by_contact_id[int64(row.ID)]
emails := make([]string, len(contact_emails))
for i, e := range contact_emails {
emails[i] = e.Address
}
contact_phones := contact_phones_by_contact_id[int64(row.ID)]
phones := make([]types.Phone, len(contact_phones))
for i, p := range contact_phones {
phones[i] = types.Phone{
E164: p.E164,
CanSMS: p.CanSms,
}
}
if row.Name != "" || len(contact_phones) > 0 || len(contact_emails) > 0 {
results = append(results, types.Contact{
Emails: emails,
ID: row.ID,
Name: row.Name,
Phones: phones,
})
2026-05-15 20:10:14 +00:00
}
}
return results, nil
}
func ContactEmptyForOrganization(ctx context.Context, txn db.Ex, org_id int32) (modelcomms.Contact, error) {
contact, err := querycomms.ContactEmptyForOrganization(ctx, txn, int64(org_id))
if err != nil {
return modelcomms.Contact{}, fmt.Errorf("querycomms: %w", err)
}
if contact != nil {
return *contact, nil
}
return querycomms.ContactInsert(ctx, txn, modelcomms.Contact{
Created: time.Now(),
Name: "",
OrganizationID: org_id,
})
}