mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 08:05:45 +00:00
1668 lines
65 KiB
Go
1668 lines
65 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/mail"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/warmbly/warmbly/internal/models"
|
|
)
|
|
|
|
// OrganizationRepository defines the interface for organization data access
|
|
type OrganizationRepository interface {
|
|
ProvisionTesterWorkspace(ctx context.Context, orgID, ownerID, adminID uuid.UUID, reason string, until time.Time) error
|
|
SeedTesterWorkspace(ctx context.Context, orgID, adminID uuid.UUID, ip, userAgent string) (*models.TesterSampleData, error)
|
|
// Organization CRUD
|
|
Create(ctx context.Context, org *models.Organization) error
|
|
GetByID(ctx context.Context, id uuid.UUID) (*models.Organization, error)
|
|
GetBySlug(ctx context.Context, slug string) (*models.Organization, error)
|
|
Update(ctx context.Context, org *models.Organization) error
|
|
UpdateAvatar(ctx context.Context, orgID uuid.UUID, avatarURL *string) error
|
|
Delete(ctx context.Context, id uuid.UUID) error
|
|
|
|
// User's organizations
|
|
GetUserOrganizations(ctx context.Context, userID uuid.UUID) ([]models.OrganizationMember, error)
|
|
GetUserDefaultOrganization(ctx context.Context, userID uuid.UUID) (*models.Organization, error)
|
|
|
|
// Member management
|
|
GetMembers(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationMember, error)
|
|
GetMember(ctx context.Context, orgID, userID uuid.UUID) (*models.OrganizationMember, error)
|
|
GetMemberByID(ctx context.Context, memberID uuid.UUID) (*models.OrganizationMember, error)
|
|
AddMember(ctx context.Context, member *models.OrganizationMember) error
|
|
UpdateMember(ctx context.Context, member *models.OrganizationMember) error
|
|
|
|
// Custom forms domain (implemented in pg_organization_forms_domain.go)
|
|
GetFormsDomain(ctx context.Context, orgID uuid.UUID) (domain string, verified bool, err error)
|
|
SetFormsDomain(ctx context.Context, orgID uuid.UUID, domain string) error
|
|
SetFormsDomainVerified(ctx context.Context, orgID uuid.UUID, verified bool, at *time.Time) error
|
|
FormsDomainHeldElsewhere(ctx context.Context, orgID uuid.UUID, domain string) (bool, error)
|
|
// ListFormsDomains returns every org with a custom forms domain set, for
|
|
// the periodic re-verification sweep.
|
|
ListFormsDomains(ctx context.Context) ([]OrgFormsDomain, error)
|
|
|
|
// Custom roles (implemented in pg_organization_roles.go)
|
|
ListRoles(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationRole, error)
|
|
GetRoleByID(ctx context.Context, orgID, roleID uuid.UUID) (*models.OrganizationRole, error)
|
|
CountRoles(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
CreateRole(ctx context.Context, role *models.OrganizationRole) error
|
|
UpdateRole(ctx context.Context, role *models.OrganizationRole) error
|
|
DeleteRole(ctx context.Context, orgID, roleID uuid.UUID) error
|
|
|
|
// Multi-role assignment (pg_member_roles.go)
|
|
AddMemberWithRoles(ctx context.Context, member *models.OrganizationMember, roleIDs []uuid.UUID) error
|
|
AcceptInvitation(ctx context.Context, invitationID uuid.UUID, member *models.OrganizationMember, roleIDs []uuid.UUID) error
|
|
HydrateInvitationRoles(ctx context.Context, invitations []models.OrganizationInvitation) error
|
|
SetMemberRoles(ctx context.Context, orgID, userID uuid.UUID, roleIDs []uuid.UUID) error
|
|
GetMemberRoles(ctx context.Context, orgID, userID uuid.UUID) ([]models.MemberRole, error)
|
|
HydrateMemberRoles(ctx context.Context, orgID uuid.UUID, members []models.OrganizationMember) error
|
|
|
|
// Resource scope: which campaigns, folders and mailboxes a restricted member reaches.
|
|
GetMemberAccess(ctx context.Context, orgID, userID uuid.UUID) (*models.MemberAccess, error)
|
|
ListMemberAccess(ctx context.Context, orgID uuid.UUID) (map[uuid.UUID]*models.MemberAccess, error)
|
|
ResolveMemberScope(ctx context.Context, orgID, userID uuid.UUID) (*models.ResourceScope, error)
|
|
CountOwnedAccessResources(ctx context.Context, orgID uuid.UUID, a *models.MemberAccess) (folders, campaigns, mailboxes int, err error)
|
|
SetMemberAccess(ctx context.Context, orgID, userID uuid.UUID, a *models.MemberAccess, grantedBy uuid.UUID) error
|
|
SuggestCampaignSenders(ctx context.Context, orgID uuid.UUID, campaignIDs, folderIDs []uuid.UUID) ([]models.SuggestedSender, error)
|
|
SetInvitationRoles(ctx context.Context, invitationID uuid.UUID, roleIDs []uuid.UUID) error
|
|
GetInvitationRoles(ctx context.Context, invitationID uuid.UUID) ([]uuid.UUID, error)
|
|
RemoveMember(ctx context.Context, orgID, userID uuid.UUID) error
|
|
GetMemberCount(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
|
|
// Invitations
|
|
CreateInvitedUser(ctx context.Context, tokenHash string, email *mail.Address, passwordHash string) (*models.User, *models.OrganizationMember, error)
|
|
CreateInvitation(ctx context.Context, inv *models.OrganizationInvitation) error
|
|
GetInvitationByToken(ctx context.Context, tokenHash string) (*models.OrganizationInvitation, error)
|
|
SetInvitationLinkToken(ctx context.Context, orgID, invitationID uuid.UUID, linkTokenHash string) (bool, error)
|
|
GetInvitationByID(ctx context.Context, id uuid.UUID) (*models.OrganizationInvitation, error)
|
|
GetInvitationByEmail(ctx context.Context, orgID uuid.UUID, email string) (*models.OrganizationInvitation, error)
|
|
GetPendingInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, error)
|
|
GetExpiredInvitations(ctx context.Context, orgID uuid.UUID, limit int) ([]models.OrganizationInvitation, error)
|
|
GetUserPendingInvitations(ctx context.Context, email string) ([]models.OrganizationInvitation, error)
|
|
DeleteInvitation(ctx context.Context, id uuid.UUID) error
|
|
DeleteExpiredInvitations(ctx context.Context) error
|
|
|
|
// Ownership transfer
|
|
TransferOwnership(ctx context.Context, orgID, currentOwnerUserID, newOwnerUserID uuid.UUID) error
|
|
|
|
// Resource counts
|
|
GetCampaignCounts(ctx context.Context, orgID uuid.UUID) (total int, active int, err error)
|
|
GetMemberCounts(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
GetEmailAccountCount(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
GetContactCount(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
GetEmailsSentTodayCount(ctx context.Context, orgID uuid.UUID) (int, error)
|
|
GetScopedOrganizationCounts(ctx context.Context, orgID uuid.UUID, scope *models.ResourceScope) (*models.OrganizationCounts, error)
|
|
|
|
// Ownership counts
|
|
GetUserOwnedOrganizationCount(ctx context.Context, userID uuid.UUID) (int, error)
|
|
|
|
// Enterprise inquiries
|
|
CreateEnterpriseInquiry(ctx context.Context, inquiry *models.EnterpriseInquiry) error
|
|
GetEnterpriseInquiry(ctx context.Context, id uuid.UUID) (*models.EnterpriseInquiry, error)
|
|
ListEnterpriseInquiries(ctx context.Context, status string, limit, offset int) ([]models.EnterpriseInquiry, error)
|
|
UpdateEnterpriseInquiryStatus(ctx context.Context, id uuid.UUID, status string, processedBy uuid.UUID) error
|
|
|
|
// Admin permissions
|
|
GetUserAdminPermissions(ctx context.Context, userID uuid.UUID) (uint32, error)
|
|
|
|
// Admin: org-wide search/listing for the admin panel
|
|
SearchOrganizationsForAdmin(ctx context.Context, search *models.AdminOrgSearch) (*models.AdminOrgsResult, error)
|
|
GetOrganizationAdminDetail(ctx context.Context, orgID uuid.UUID) (*models.AdminOrgDetail, error)
|
|
GetOrganizationMembersForAdmin(ctx context.Context, orgID uuid.UUID) ([]models.AdminOrgMember, error)
|
|
|
|
// Admin: per-org limit overrides. Read returns nil when no row
|
|
// exists (org has never been touched). Upsert always returns the
|
|
// post-write row so callers get the authoritative timestamps back.
|
|
GetOrganizationLimitOverrides(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimitOverrides, error)
|
|
UpsertOrganizationLimitOverrides(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrgOverridesRequest, grantedBy uuid.UUID) (*models.OrganizationLimitOverrides, error)
|
|
|
|
// Limit-increase requests. CreateLimitRequest enforces the partial
|
|
// unique index (one open request per (org, field)) by surfacing the
|
|
// pgx unique-violation error code. UpdateLimitRequestStatus stamps
|
|
// reviewer + timestamp atomically.
|
|
CreateLimitRequest(ctx context.Context, req *models.LimitIncreaseRequest) error
|
|
GetLimitRequest(ctx context.Context, id uuid.UUID) (*models.LimitIncreaseRequest, error)
|
|
ListLimitRequestsForOrg(ctx context.Context, orgID uuid.UUID) ([]models.LimitIncreaseRequest, error)
|
|
ListLimitRequestsForAdmin(ctx context.Context, search *models.AdminLimitRequestSearch) (*models.AdminLimitRequestsResult, error)
|
|
UpdateLimitRequestStatus(ctx context.Context, id uuid.UUID, status models.LimitRequestStatus, reviewedBy uuid.UUID, notes string) error
|
|
|
|
// Acquisition: where the workspace came from, written once at signup.
|
|
// The write is ON CONFLICT DO NOTHING because the record is a fact about
|
|
// the signup, not a mutable setting: a later visit through a different
|
|
// campaign must not rewrite where the account actually came from.
|
|
RecordOrganizationAcquisition(ctx context.Context, acq *models.OrgAcquisition) error
|
|
GetOrganizationAcquisition(ctx context.Context, orgID uuid.UUID) (*models.OrgAcquisition, error)
|
|
}
|
|
|
|
type organizationRepository struct {
|
|
db *pgxpool.Pool
|
|
}
|
|
|
|
// NewOrganizationRepository creates a new organization repository
|
|
func NewOrganizationRepository(db *pgxpool.Pool) OrganizationRepository {
|
|
return &organizationRepository{db: db}
|
|
}
|
|
|
|
// Create creates a new organization
|
|
func (r *organizationRepository) Create(ctx context.Context, org *models.Organization) error {
|
|
query := `
|
|
INSERT INTO organizations (id, name, slug, owner_user_id, created_at, updated_at, timezone)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
`
|
|
now := time.Now()
|
|
if _, err := r.db.Exec(ctx, query,
|
|
org.ID, org.Name, org.Slug, org.OwnerUserID, now, now, org.Timezone,
|
|
); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Seed the org's default CRM task types so the tasks UI is usable from day
|
|
// one. Best-effort: a failure here shouldn't block org creation.
|
|
if err := SeedDefaultTaskTypes(ctx, r.db, org.ID); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetByID retrieves an organization by ID
|
|
func (r *organizationRepository) GetByID(ctx context.Context, id uuid.UUID) (*models.Organization, error) {
|
|
query := `
|
|
SELECT id, name, slug, avatar_url, owner_user_id, created_at, updated_at,
|
|
deletion_scheduled_at, deletion_scheduled_for,
|
|
presence_show_online, presence_show_activity,
|
|
product_description, icp_notes, voice_profile, inbox_agent_enabled,
|
|
assistant_shared_history, timezone, category
|
|
FROM organizations WHERE id = $1
|
|
`
|
|
return r.scanOrganization(ctx, query, id)
|
|
}
|
|
|
|
// GetBySlug retrieves an organization by slug
|
|
func (r *organizationRepository) GetBySlug(ctx context.Context, slug string) (*models.Organization, error) {
|
|
query := `
|
|
SELECT id, name, slug, avatar_url, owner_user_id, created_at, updated_at,
|
|
deletion_scheduled_at, deletion_scheduled_for,
|
|
presence_show_online, presence_show_activity,
|
|
product_description, icp_notes, voice_profile, inbox_agent_enabled,
|
|
assistant_shared_history, timezone, category
|
|
FROM organizations WHERE slug = $1
|
|
`
|
|
return r.scanOrganization(ctx, query, slug)
|
|
}
|
|
|
|
func (r *organizationRepository) scanOrganization(ctx context.Context, query string, args ...interface{}) (*models.Organization, error) {
|
|
row := r.db.QueryRow(ctx, query, args...)
|
|
var org models.Organization
|
|
err := row.Scan(&org.ID, &org.Name, &org.Slug, &org.AvatarURL, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt, &org.DeletionScheduledAt, &org.DeletionScheduledFor, &org.PresenceShowOnline, &org.PresenceShowActivity, &org.ProductDescription, &org.ICPNotes, &org.VoiceProfile, &org.InboxAgentEnabled, &org.AssistantSharedHistory, &org.Timezone, &org.Category)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &org, nil
|
|
}
|
|
|
|
// Update updates an organization
|
|
func (r *organizationRepository) Update(ctx context.Context, org *models.Organization) error {
|
|
query := `
|
|
UPDATE organizations
|
|
SET name = $2, slug = $3, presence_show_online = $4,
|
|
presence_show_activity = $5,
|
|
product_description = $7, icp_notes = $8, voice_profile = $9,
|
|
inbox_agent_enabled = $10,
|
|
assistant_shared_history = $11,
|
|
timezone = $12,
|
|
updated_at = $6
|
|
WHERE id = $1
|
|
`
|
|
_, err := r.db.Exec(ctx, query, org.ID, org.Name, org.Slug, org.PresenceShowOnline, org.PresenceShowActivity, time.Now(), org.ProductDescription, org.ICPNotes, org.VoiceProfile, org.InboxAgentEnabled, org.AssistantSharedHistory, org.Timezone)
|
|
return err
|
|
}
|
|
|
|
// UpdateAvatar sets (or clears) the organization's avatar URL.
|
|
func (r *organizationRepository) UpdateAvatar(ctx context.Context, orgID uuid.UUID, avatarURL *string) error {
|
|
const q = `UPDATE organizations SET avatar_url = $2, updated_at = NOW() WHERE id = $1`
|
|
_, err := r.db.Exec(ctx, q, orgID, avatarURL)
|
|
return err
|
|
}
|
|
|
|
// Delete deletes an organization
|
|
var ErrOrganizationCloudLinked = errors.New("disconnect workspace Cloud link before deleting")
|
|
|
|
func (r *organizationRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, id)
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.ConstraintName == "cloud_link_organization_id_fkey" {
|
|
return ErrOrganizationCloudLinked
|
|
}
|
|
return err
|
|
}
|
|
|
|
// GetUserOrganizations retrieves all organizations a user is a member of
|
|
func (r *organizationRepository) GetUserOrganizations(ctx context.Context, userID uuid.UUID) ([]models.OrganizationMember, error) {
|
|
query := `
|
|
SELECT
|
|
om.id, om.organization_id, om.user_id, om.role, om.permissions,
|
|
om.invited_by, om.invited_at, om.accepted_at, om.access_scope,
|
|
COALESCE((SELECT bit_or(r.permissions)::int FROM organization_member_roles mr
|
|
JOIN organization_roles r ON r.id = mr.role_id AND r.organization_id = om.organization_id
|
|
WHERE mr.organization_id = om.organization_id AND mr.user_id = om.user_id AND r.acts_in_scope), 0) & om.permissions::int,
|
|
o.id, o.name, o.slug, o.avatar_url, o.owner_user_id, o.created_at, o.updated_at,
|
|
o.deletion_scheduled_at, o.deletion_scheduled_for, o.category,
|
|
ag.id, ag.name, COALESCE(ag.owner_user_id <> o.owner_user_id, false)
|
|
FROM organization_members om
|
|
JOIN organizations o ON o.id = om.organization_id
|
|
LEFT JOIN agency_clients ac ON ac.organization_id = o.id
|
|
LEFT JOIN agencies ag ON ag.id = ac.agency_id
|
|
WHERE om.user_id = $1
|
|
ORDER BY om.invited_at DESC
|
|
`
|
|
rows, err := r.db.Query(ctx, query, userID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var members []models.OrganizationMember
|
|
for rows.Next() {
|
|
var m models.OrganizationMember
|
|
var org models.Organization
|
|
var agencyID *uuid.UUID
|
|
var agencyName *string
|
|
var canLeave bool
|
|
err := rows.Scan(
|
|
&m.ID, &m.OrganizationID, &m.UserID, &m.Role, &m.Permissions,
|
|
&m.InvitedBy, &m.InvitedAt, &m.AcceptedAt, &m.AccessScope, &m.ScopeActions,
|
|
&org.ID, &org.Name, &org.Slug, &org.AvatarURL, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt,
|
|
&org.DeletionScheduledAt, &org.DeletionScheduledFor, &org.Category,
|
|
&agencyID, &agencyName, &canLeave,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.Organization = &org
|
|
if agencyID != nil && agencyName != nil {
|
|
m.Agency = &models.AgencyRef{ID: *agencyID, Name: *agencyName, CanLeave: canLeave}
|
|
}
|
|
if !m.IsRestricted() {
|
|
m.ScopeActions = 0
|
|
}
|
|
members = append(members, m)
|
|
}
|
|
return members, rows.Err()
|
|
}
|
|
|
|
// GetUserDefaultOrganization retrieves the first organization a user owns
|
|
func (r *organizationRepository) GetUserDefaultOrganization(ctx context.Context, userID uuid.UUID) (*models.Organization, error) {
|
|
query := `
|
|
SELECT id, name, slug, avatar_url, owner_user_id, created_at, updated_at,
|
|
deletion_scheduled_at, deletion_scheduled_for,
|
|
presence_show_online, presence_show_activity,
|
|
product_description, icp_notes, voice_profile, inbox_agent_enabled,
|
|
assistant_shared_history, timezone, category
|
|
FROM organizations WHERE owner_user_id = $1
|
|
ORDER BY created_at ASC LIMIT 1
|
|
`
|
|
return r.scanOrganization(ctx, query, userID)
|
|
}
|
|
|
|
// GetMembers retrieves all members of an organization
|
|
func (r *organizationRepository) GetMembers(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationMember, error) {
|
|
query := `
|
|
SELECT
|
|
om.id, om.organization_id, om.user_id, om.role, om.role_id, om.permissions,
|
|
om.invited_by, om.invited_at, om.accepted_at, om.access_scope,
|
|
u.id, u.first_name, u.last_name, u.email, u.created_at, u.updated_at
|
|
FROM organization_members om
|
|
JOIN users u ON u.id = om.user_id
|
|
WHERE om.organization_id = $1
|
|
ORDER BY om.role = 'owner' DESC, om.invited_at ASC
|
|
`
|
|
rows, err := r.db.Query(ctx, query, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var members []models.OrganizationMember
|
|
for rows.Next() {
|
|
var m models.OrganizationMember
|
|
var u models.User
|
|
err := rows.Scan(
|
|
&m.ID, &m.OrganizationID, &m.UserID, &m.Role, &m.RoleID, &m.Permissions,
|
|
&m.InvitedBy, &m.InvitedAt, &m.AcceptedAt, &m.AccessScope,
|
|
&u.ID, &u.FirstName, &u.LastName, &u.Email, &u.CreatedAt, &u.UpdatedAt,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.User = &u
|
|
m.Email = u.Email
|
|
m.Name = strings.TrimSpace(u.FirstName + " " + u.LastName)
|
|
members = append(members, m)
|
|
}
|
|
return members, nil
|
|
}
|
|
|
|
// GetMember retrieves a specific member of an organization
|
|
func (r *organizationRepository) GetMember(ctx context.Context, orgID, userID uuid.UUID) (*models.OrganizationMember, error) {
|
|
query := `
|
|
SELECT id, organization_id, user_id, role, role_id, permissions, invited_by, invited_at, accepted_at, access_scope
|
|
FROM organization_members
|
|
WHERE organization_id = $1 AND user_id = $2
|
|
`
|
|
row := r.db.QueryRow(ctx, query, orgID, userID)
|
|
var m models.OrganizationMember
|
|
err := row.Scan(&m.ID, &m.OrganizationID, &m.UserID, &m.Role, &m.RoleID, &m.Permissions, &m.InvitedBy, &m.InvitedAt, &m.AcceptedAt, &m.AccessScope)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// GetMemberByID retrieves a member by their membership ID
|
|
func (r *organizationRepository) GetMemberByID(ctx context.Context, memberID uuid.UUID) (*models.OrganizationMember, error) {
|
|
query := `
|
|
SELECT id, organization_id, user_id, role, role_id, permissions, invited_by, invited_at, accepted_at, access_scope
|
|
FROM organization_members WHERE id = $1
|
|
`
|
|
row := r.db.QueryRow(ctx, query, memberID)
|
|
var m models.OrganizationMember
|
|
err := row.Scan(&m.ID, &m.OrganizationID, &m.UserID, &m.Role, &m.RoleID, &m.Permissions, &m.InvitedBy, &m.InvitedAt, &m.AcceptedAt, &m.AccessScope)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &m, nil
|
|
}
|
|
|
|
// AddMember adds a member to an organization
|
|
func (r *organizationRepository) AddMember(ctx context.Context, member *models.OrganizationMember) error {
|
|
query := `
|
|
INSERT INTO organization_members (id, organization_id, user_id, role, role_id, permissions, invited_by, invited_at, accepted_at, access_scope)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
`
|
|
_, err := r.db.Exec(ctx, query,
|
|
member.ID, member.OrganizationID, member.UserID, member.Role, member.RoleID, member.Permissions,
|
|
member.InvitedBy, member.InvitedAt, member.AcceptedAt, memberScope(member),
|
|
)
|
|
return err
|
|
}
|
|
|
|
// UpdateMember updates a member's role and permissions
|
|
func (r *organizationRepository) UpdateMember(ctx context.Context, member *models.OrganizationMember) error {
|
|
query := `
|
|
UPDATE organization_members SET role = $3, role_id = $4, permissions = $5
|
|
WHERE organization_id = $1 AND user_id = $2
|
|
`
|
|
_, err := r.db.Exec(ctx, query, member.OrganizationID, member.UserID, member.Role, member.RoleID, member.Permissions)
|
|
return err
|
|
}
|
|
|
|
// RemoveMember removes a member from an organization
|
|
func (r *organizationRepository) RemoveMember(ctx context.Context, orgID, userID uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM organization_members WHERE organization_id = $1 AND user_id = $2`, orgID, userID)
|
|
return err
|
|
}
|
|
|
|
// GetMemberCount returns the number of members in an organization
|
|
func (r *organizationRepository) GetMemberCount(ctx context.Context, orgID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM organization_members WHERE organization_id = $1`, orgID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// CreateInvitation creates a new invitation
|
|
func (r *organizationRepository) CreateInvitation(ctx context.Context, inv *models.OrganizationInvitation) error {
|
|
query := `
|
|
INSERT INTO organization_invitations (id, organization_id, email, role, role_id, permissions, invited_by, token, expires_at, created_at,
|
|
access_scope, access_folder_ids, access_campaign_ids, access_email_account_ids)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
|
ON CONFLICT (organization_id, email) DO UPDATE SET
|
|
role = EXCLUDED.role,
|
|
role_id = EXCLUDED.role_id,
|
|
permissions = EXCLUDED.permissions,
|
|
invited_by = EXCLUDED.invited_by,
|
|
token = EXCLUDED.token,
|
|
link_token_hash = NULL,
|
|
expires_at = EXCLUDED.expires_at,
|
|
access_scope = EXCLUDED.access_scope,
|
|
access_folder_ids = EXCLUDED.access_folder_ids,
|
|
access_campaign_ids = EXCLUDED.access_campaign_ids,
|
|
access_email_account_ids = EXCLUDED.access_email_account_ids
|
|
RETURNING id
|
|
`
|
|
access := inv.Access
|
|
if access == nil {
|
|
access = models.WorkspaceAccess()
|
|
}
|
|
access.Normalize()
|
|
// A re-invite updates the existing row, so the stored id is the one its roles attach to.
|
|
return r.db.QueryRow(ctx, query,
|
|
inv.ID, inv.OrganizationID, inv.Email, inv.Role, inv.RoleID, inv.Permissions,
|
|
inv.InvitedBy, inv.Token, inv.ExpiresAt, inv.CreatedAt,
|
|
access.Scope, access.FolderIDs, access.CampaignIDs, access.EmailAccountIDs,
|
|
).Scan(&inv.ID)
|
|
}
|
|
|
|
// SetInvitationLinkToken replaces the digest of an invitation's copied-link token.
|
|
func (r *organizationRepository) SetInvitationLinkToken(ctx context.Context, orgID, invitationID uuid.UUID, linkTokenHash string) (bool, error) {
|
|
tag, err := r.db.Exec(ctx, `UPDATE organization_invitations SET link_token_hash = $3 WHERE organization_id = $1 AND id = $2`,
|
|
orgID, invitationID, linkTokenHash)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
// GetInvitationByToken retrieves an invitation by the digest of its emailed or copied-link token.
|
|
func (r *organizationRepository) GetInvitationByToken(ctx context.Context, token string) (*models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT
|
|
i.id, i.organization_id, i.email, i.role, i.role_id, i.permissions, i.invited_by, i.token, i.expires_at, i.created_at,
|
|
o.id, o.name, o.slug, o.avatar_url, o.owner_user_id, o.created_at, o.updated_at,
|
|
o.deletion_scheduled_at, o.deletion_scheduled_for,
|
|
` + invitationAccessCols + `
|
|
FROM organization_invitations i
|
|
JOIN organizations o ON o.id = i.organization_id
|
|
WHERE i.token = $1 OR i.link_token_hash = $1
|
|
`
|
|
row := r.db.QueryRow(ctx, query, token)
|
|
var inv models.OrganizationInvitation
|
|
var org models.Organization
|
|
var acc invitationAccess
|
|
err := row.Scan(
|
|
&inv.ID, &inv.OrganizationID, &inv.Email, &inv.Role, &inv.RoleID, &inv.Permissions,
|
|
&inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt,
|
|
&org.ID, &org.Name, &org.Slug, &org.AvatarURL, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt,
|
|
&org.DeletionScheduledAt, &org.DeletionScheduledFor,
|
|
&acc.scope, &acc.folders, &acc.campaigns, &acc.mailboxes,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inv.Access = acc.access()
|
|
inv.Organization = &org
|
|
return &inv, nil
|
|
}
|
|
|
|
// GetInvitationByID retrieves an invitation by its id, with org joined.
|
|
func (r *organizationRepository) GetInvitationByID(ctx context.Context, id uuid.UUID) (*models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT
|
|
i.id, i.organization_id, i.email, i.role, i.role_id, i.permissions, i.invited_by, i.token, i.expires_at, i.created_at,
|
|
o.id, o.name, o.slug, o.avatar_url, o.owner_user_id, o.created_at, o.updated_at,
|
|
o.deletion_scheduled_at, o.deletion_scheduled_for,
|
|
` + invitationAccessCols + `
|
|
FROM organization_invitations i
|
|
JOIN organizations o ON o.id = i.organization_id
|
|
WHERE i.id = $1
|
|
`
|
|
row := r.db.QueryRow(ctx, query, id)
|
|
var inv models.OrganizationInvitation
|
|
var org models.Organization
|
|
var acc invitationAccess
|
|
err := row.Scan(
|
|
&inv.ID, &inv.OrganizationID, &inv.Email, &inv.Role, &inv.RoleID, &inv.Permissions,
|
|
&inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt,
|
|
&org.ID, &org.Name, &org.Slug, &org.AvatarURL, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt,
|
|
&org.DeletionScheduledAt, &org.DeletionScheduledFor,
|
|
&acc.scope, &acc.folders, &acc.campaigns, &acc.mailboxes,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inv.Access = acc.access()
|
|
inv.Organization = &org
|
|
return &inv, nil
|
|
}
|
|
|
|
// GetInvitationByEmail retrieves an invitation by email for a specific organization
|
|
func (r *organizationRepository) GetInvitationByEmail(ctx context.Context, orgID uuid.UUID, email string) (*models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT id, organization_id, email, role, permissions, invited_by, token, expires_at, created_at
|
|
FROM organization_invitations
|
|
WHERE organization_id = $1 AND email = $2
|
|
`
|
|
row := r.db.QueryRow(ctx, query, orgID, email)
|
|
var inv models.OrganizationInvitation
|
|
err := row.Scan(&inv.ID, &inv.OrganizationID, &inv.Email, &inv.Role, &inv.Permissions, &inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &inv, nil
|
|
}
|
|
|
|
// GetPendingInvitations retrieves all pending invitations for an organization
|
|
func (r *organizationRepository) GetPendingInvitations(ctx context.Context, orgID uuid.UUID) ([]models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT id, organization_id, email, role, role_id, permissions, invited_by, token, expires_at, created_at,
|
|
` + invitationAccessCols + `
|
|
FROM organization_invitations i
|
|
WHERE organization_id = $1 AND expires_at > NOW()
|
|
ORDER BY created_at DESC
|
|
`
|
|
return r.queryInvitations(ctx, query, orgID)
|
|
}
|
|
|
|
// GetExpiredInvitations returns an organization's most recently expired invitations, so they can be sent again.
|
|
func (r *organizationRepository) GetExpiredInvitations(ctx context.Context, orgID uuid.UUID, limit int) ([]models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT id, organization_id, email, role, role_id, permissions, invited_by, token, expires_at, created_at,
|
|
` + invitationAccessCols + `
|
|
FROM organization_invitations i
|
|
WHERE organization_id = $1 AND expires_at <= NOW()
|
|
ORDER BY expires_at DESC
|
|
LIMIT $2
|
|
`
|
|
return r.queryInvitations(ctx, query, orgID, limit)
|
|
}
|
|
|
|
func (r *organizationRepository) queryInvitations(ctx context.Context, query string, args ...any) ([]models.OrganizationInvitation, error) {
|
|
rows, err := r.db.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var invitations []models.OrganizationInvitation
|
|
for rows.Next() {
|
|
var inv models.OrganizationInvitation
|
|
var acc invitationAccess
|
|
err := rows.Scan(&inv.ID, &inv.OrganizationID, &inv.Email, &inv.Role, &inv.RoleID, &inv.Permissions, &inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt,
|
|
&acc.scope, &acc.folders, &acc.campaigns, &acc.mailboxes)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inv.Access = acc.access()
|
|
invitations = append(invitations, inv)
|
|
}
|
|
return invitations, rows.Err()
|
|
}
|
|
|
|
// GetUserPendingInvitations retrieves all pending invitations for a user's email
|
|
func (r *organizationRepository) GetUserPendingInvitations(ctx context.Context, email string) ([]models.OrganizationInvitation, error) {
|
|
query := `
|
|
SELECT
|
|
i.id, i.organization_id, i.email, i.role, i.permissions, i.invited_by, i.token, i.expires_at, i.created_at,
|
|
o.id, o.name, o.slug, o.avatar_url, o.owner_user_id, o.created_at, o.updated_at,
|
|
o.deletion_scheduled_at, o.deletion_scheduled_for
|
|
FROM organization_invitations i
|
|
JOIN organizations o ON o.id = i.organization_id
|
|
WHERE i.email = $1 AND i.expires_at > NOW()
|
|
ORDER BY i.created_at DESC
|
|
`
|
|
rows, err := r.db.Query(ctx, query, email)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var invitations []models.OrganizationInvitation
|
|
for rows.Next() {
|
|
var inv models.OrganizationInvitation
|
|
var org models.Organization
|
|
err := rows.Scan(
|
|
&inv.ID, &inv.OrganizationID, &inv.Email, &inv.Role, &inv.Permissions,
|
|
&inv.InvitedBy, &inv.Token, &inv.ExpiresAt, &inv.CreatedAt,
|
|
&org.ID, &org.Name, &org.Slug, &org.AvatarURL, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt,
|
|
&org.DeletionScheduledAt, &org.DeletionScheduledFor,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inv.Organization = &org
|
|
invitations = append(invitations, inv)
|
|
}
|
|
return invitations, nil
|
|
}
|
|
|
|
// DeleteInvitation deletes an invitation
|
|
|
|
func (r *organizationRepository) DeleteInvitation(ctx context.Context, id uuid.UUID) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM organization_invitations WHERE id = $1`, id)
|
|
return err
|
|
}
|
|
|
|
// DeleteExpiredInvitations deletes all expired invitations
|
|
|
|
func (r *organizationRepository) DeleteExpiredInvitations(ctx context.Context) error {
|
|
_, err := r.db.Exec(ctx, `DELETE FROM organization_invitations WHERE expires_at < NOW()`)
|
|
return err
|
|
}
|
|
|
|
// ErrOwnershipNotHeld means the caller does not own the workspace when the transfer is written.
|
|
var ErrOwnershipNotHeld = errors.New("caller does not own the workspace")
|
|
|
|
// ErrNewOwnerNotMember means the proposed owner has no membership in the workspace.
|
|
var ErrNewOwnerNotMember = errors.New("new owner is not a member of the workspace")
|
|
|
|
// ErrNewOwnerUnavailable means the proposed owner's account cannot take a workspace.
|
|
var ErrNewOwnerUnavailable = errors.New("new owner's account cannot take a workspace")
|
|
|
|
// TransferOwnership moves ownership from currentOwnerUserID to another member
|
|
// in one transaction, decided against the locked organization row.
|
|
func (r *organizationRepository) TransferOwnership(ctx context.Context, orgID, currentOwnerUserID, newOwnerUserID uuid.UUID) error {
|
|
tx, err := r.db.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx) //nolint:errcheck
|
|
|
|
var owner uuid.UUID
|
|
err = tx.QueryRow(ctx, `SELECT owner_user_id FROM organizations WHERE id = $1 FOR UPDATE`, orgID).Scan(&owner)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if owner != currentOwnerUserID {
|
|
return ErrOwnershipNotHeld
|
|
}
|
|
if newOwnerUserID == owner {
|
|
return ErrNewOwnerUnavailable
|
|
}
|
|
|
|
// An account deletion takes the workspaces it owns with it, and a banned account cannot run one.
|
|
var available bool
|
|
err = tx.QueryRow(ctx, `SELECT banned_at IS NULL AND deletion_scheduled_for IS NULL FROM users WHERE id = $1 FOR SHARE`, newOwnerUserID).Scan(&available)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return ErrNewOwnerNotMember
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !available {
|
|
return ErrNewOwnerUnavailable
|
|
}
|
|
|
|
// Owner is a membership status, not a role: role_id must be NULL so role
|
|
// edits can never write through onto the owner row, and it is never scoped.
|
|
tag, err := tx.Exec(ctx, `
|
|
UPDATE organization_members SET role = 'owner', role_id = NULL, permissions = $3, access_scope = $4
|
|
WHERE organization_id = $1 AND user_id = $2`,
|
|
orgID, newOwnerUserID, models.RolePermissions[models.RoleOwner], models.AccessScopeWorkspace)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNewOwnerNotMember
|
|
}
|
|
if _, err = tx.Exec(ctx, `DELETE FROM organization_member_roles WHERE organization_id = $1 AND user_id = $2`, orgID, newOwnerUserID); err != nil {
|
|
return err
|
|
}
|
|
if err = writeMemberGrants(ctx, tx, orgID, newOwnerUserID, &models.MemberAccess{Scope: models.AccessScopeWorkspace}, uuid.Nil); err != nil {
|
|
return err
|
|
}
|
|
|
|
if _, err = tx.Exec(ctx, `UPDATE organizations SET owner_user_id = $2, updated_at = NOW() WHERE id = $1`, orgID, newOwnerUserID); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Re-home the old owner onto the org's Admin role row when one exists
|
|
// (roles are data); otherwise fall back to a detached Admin-mask member.
|
|
_, err = tx.Exec(ctx, `
|
|
UPDATE organization_members om SET
|
|
role = COALESCE(r.name, 'Admin'),
|
|
role_id = r.id,
|
|
permissions = COALESCE(r.permissions, $3)
|
|
FROM (SELECT 1) one
|
|
LEFT JOIN organization_roles r ON r.organization_id = $1 AND r.name = 'Admin'
|
|
WHERE om.organization_id = $1 AND om.user_id = $2`,
|
|
orgID, owner, models.RolePermissions[models.RoleAdmin])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// The assignment row keeps the snapshot above true through a later recompute.
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO organization_member_roles (organization_id, user_id, role_id)
|
|
SELECT om.organization_id, om.user_id, om.role_id FROM organization_members om
|
|
WHERE om.organization_id = $1 AND om.user_id = $2 AND om.role_id IS NOT NULL
|
|
ON CONFLICT DO NOTHING`, orgID, owner)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
// GetCampaignCounts returns total and active campaign counts for an organization
|
|
func (r *organizationRepository) GetCampaignCounts(ctx context.Context, orgID uuid.UUID) (total int, active int, err error) {
|
|
query := `
|
|
SELECT
|
|
COUNT(*) as total,
|
|
COUNT(*) FILTER (WHERE status = 'active') as active
|
|
FROM campaigns WHERE organization_id = $1
|
|
`
|
|
err = r.db.QueryRow(ctx, query, orgID).Scan(&total, &active)
|
|
return
|
|
}
|
|
|
|
// GetScopedOrganizationCounts intersects every aggregate with grants and organization ownership.
|
|
func (r *organizationRepository) GetScopedOrganizationCounts(ctx context.Context, orgID uuid.UUID, scope *models.ResourceScope) (*models.OrganizationCounts, error) {
|
|
if scope == nil {
|
|
return nil, errors.New("member access was not resolved")
|
|
}
|
|
counts := &models.OrganizationCounts{}
|
|
err := r.db.QueryRow(ctx, `
|
|
WITH campaigns_in_scope AS (
|
|
SELECT id, status FROM campaigns WHERE organization_id = $1 AND id = ANY($2::uuid[])
|
|
), mailboxes_in_scope AS (
|
|
SELECT id FROM email_accounts WHERE organization_id = $1 AND id = ANY($3::uuid[])
|
|
)
|
|
SELECT
|
|
(SELECT COUNT(*) FROM campaigns_in_scope),
|
|
(SELECT COUNT(*) FROM campaigns_in_scope WHERE status = 'active'),
|
|
(SELECT COUNT(*) FROM contacts c WHERE c.organization_id = $1 AND EXISTS (
|
|
SELECT 1 FROM campaign_leads cl JOIN campaigns_in_scope cs ON cs.id = cl.campaign_id
|
|
WHERE cl.contact_id = c.id)),
|
|
(SELECT COUNT(*) FROM mailboxes_in_scope),
|
|
(SELECT COUNT(*) FROM tasks t
|
|
JOIN campaign_tasks ct ON ct.task_id = t.id
|
|
JOIN campaigns_in_scope cs ON cs.id = ct.campaign_id
|
|
JOIN mailboxes_in_scope ms ON ms.id = t.email_account_id
|
|
WHERE `+campaignSendToday+`)
|
|
`, orgID, nonNilUUIDs(scope.Campaigns), nonNilUUIDs(scope.Mailboxes)).Scan(
|
|
&counts.TotalCampaigns, &counts.ActiveCampaigns, &counts.TotalContacts,
|
|
&counts.EmailAccounts, &counts.EmailsSentToday)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return counts, nil
|
|
}
|
|
|
|
// GetMemberCounts returns the member count for an organization
|
|
func (r *organizationRepository) GetMemberCounts(ctx context.Context, orgID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM organization_members WHERE organization_id = $1`, orgID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// GetEmailAccountCount returns the email account count for an organization
|
|
func (r *organizationRepository) GetEmailAccountCount(ctx context.Context, orgID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM email_accounts WHERE organization_id = $1`, orgID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// GetContactCount returns the contact count for an organization
|
|
func (r *organizationRepository) GetContactCount(ctx context.Context, orgID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM contacts WHERE organization_id = $1`, orgID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// GetEmailsSentTodayCount counts campaign emails sent today by an organization.
|
|
func (r *organizationRepository) GetEmailsSentTodayCount(ctx context.Context, orgID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT COUNT(*)
|
|
FROM tasks t
|
|
JOIN email_accounts ea ON ea.id = t.email_account_id
|
|
WHERE ea.organization_id = $1
|
|
AND t.task_type = 'campaign'
|
|
AND `+completedSendTaskSQL("t")+`
|
|
AND t.completed_at >= CURRENT_DATE
|
|
AND `+taskDispatchedEmail+`
|
|
`, orgID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// GetUserOwnedOrganizationCount returns the number of organizations owned by a user
|
|
func (r *organizationRepository) GetUserOwnedOrganizationCount(ctx context.Context, userID uuid.UUID) (int, error) {
|
|
var count int
|
|
err := r.db.QueryRow(ctx, `SELECT COUNT(*) FROM organizations WHERE owner_user_id = $1`, userID).Scan(&count)
|
|
return count, err
|
|
}
|
|
|
|
// CreateEnterpriseInquiry creates a new enterprise inquiry
|
|
func (r *organizationRepository) CreateEnterpriseInquiry(ctx context.Context, inquiry *models.EnterpriseInquiry) error {
|
|
query := `
|
|
INSERT INTO enterprise_inquiries (id, company_name, contact_name, contact_email, estimated_volume, team_size, notes, status, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
|
`
|
|
_, err := r.db.Exec(ctx, query,
|
|
inquiry.ID, inquiry.CompanyName, inquiry.ContactName, inquiry.ContactEmail,
|
|
inquiry.EstimatedVolume, inquiry.TeamSize, inquiry.Notes, inquiry.Status, inquiry.CreatedAt,
|
|
)
|
|
return err
|
|
}
|
|
|
|
// GetEnterpriseInquiry retrieves an enterprise inquiry by ID
|
|
func (r *organizationRepository) GetEnterpriseInquiry(ctx context.Context, id uuid.UUID) (*models.EnterpriseInquiry, error) {
|
|
query := `
|
|
SELECT id, company_name, contact_name, contact_email, estimated_volume, team_size, notes, status, created_at, processed_at, processed_by
|
|
FROM enterprise_inquiries WHERE id = $1
|
|
`
|
|
row := r.db.QueryRow(ctx, query, id)
|
|
var inq models.EnterpriseInquiry
|
|
err := row.Scan(
|
|
&inq.ID, &inq.CompanyName, &inq.ContactName, &inq.ContactEmail,
|
|
&inq.EstimatedVolume, &inq.TeamSize, &inq.Notes, &inq.Status,
|
|
&inq.CreatedAt, &inq.ProcessedAt, &inq.ProcessedBy,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &inq, nil
|
|
}
|
|
|
|
// ListEnterpriseInquiries lists enterprise inquiries with optional status filter
|
|
func (r *organizationRepository) ListEnterpriseInquiries(ctx context.Context, status string, limit, offset int) ([]models.EnterpriseInquiry, error) {
|
|
query := `
|
|
SELECT id, company_name, contact_name, contact_email, estimated_volume, team_size, notes, status, created_at, processed_at, processed_by
|
|
FROM enterprise_inquiries
|
|
WHERE ($1 = '' OR status = $1)
|
|
ORDER BY created_at DESC
|
|
LIMIT $2 OFFSET $3
|
|
`
|
|
rows, err := r.db.Query(ctx, query, status, limit, offset)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var inquiries []models.EnterpriseInquiry
|
|
for rows.Next() {
|
|
var inq models.EnterpriseInquiry
|
|
err := rows.Scan(
|
|
&inq.ID, &inq.CompanyName, &inq.ContactName, &inq.ContactEmail,
|
|
&inq.EstimatedVolume, &inq.TeamSize, &inq.Notes, &inq.Status,
|
|
&inq.CreatedAt, &inq.ProcessedAt, &inq.ProcessedBy,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
inquiries = append(inquiries, inq)
|
|
}
|
|
return inquiries, nil
|
|
}
|
|
|
|
// UpdateEnterpriseInquiryStatus updates the status of an enterprise inquiry
|
|
func (r *organizationRepository) UpdateEnterpriseInquiryStatus(ctx context.Context, id uuid.UUID, status string, processedBy uuid.UUID) error {
|
|
query := `
|
|
UPDATE enterprise_inquiries SET status = $2, processed_at = $3, processed_by = $4
|
|
WHERE id = $1
|
|
`
|
|
_, err := r.db.Exec(ctx, query, id, status, time.Now(), processedBy)
|
|
return err
|
|
}
|
|
|
|
// GetUserAdminPermissions retrieves the admin permissions for a user
|
|
func (r *organizationRepository) GetUserAdminPermissions(ctx context.Context, userID uuid.UUID) (uint32, error) {
|
|
var perms uint32
|
|
err := r.db.QueryRow(ctx, `SELECT admin_permissions FROM users WHERE id = $1`, userID).Scan(&perms)
|
|
if err == pgx.ErrNoRows {
|
|
return 0, nil
|
|
}
|
|
return perms, err
|
|
}
|
|
|
|
// adminOrgListColumns is the projection used by both the list and detail
|
|
// queries so the AdminOrgListItem scan stays identical across both.
|
|
const adminOrgListColumns = `
|
|
o.id, o.name, o.slug, o.owner_user_id,
|
|
u.email, u.first_name, u.last_name, u.banned_at,
|
|
o.created_at, o.deletion_scheduled_for,
|
|
(SELECT COUNT(*) FROM organization_members om WHERE om.organization_id = o.id) AS member_count,
|
|
(SELECT COUNT(*) FROM email_accounts ea WHERE ea.organization_id = o.id) AS email_account_count,
|
|
(SELECT COUNT(*) FROM campaigns c WHERE c.organization_id = o.id) AS campaign_count,
|
|
(SELECT COUNT(*) FROM campaigns c WHERE c.organization_id = o.id AND c.status = 'active') AS active_campaigns,
|
|
o.risk_state,
|
|
oa.utm_source, oa.utm_medium, oa.utm_campaign, oa.landing_path, oa.referrer_host, o.category`
|
|
|
|
// LEFT JOIN preserves workspaces with no recorded acquisition.
|
|
const adminOrgAcquisitionJoin = `
|
|
LEFT JOIN organization_acquisition oa ON oa.organization_id = o.id`
|
|
|
|
// SearchOrganizationsForAdmin lists orgs for the admin panel with cursor
|
|
// pagination. The cursor is the last seen org id; rows are returned in
|
|
// descending created_at order by default. Counts are computed inline so
|
|
// the table can render usage without an extra fetch per row.
|
|
func (r *organizationRepository) SearchOrganizationsForAdmin(ctx context.Context, search *models.AdminOrgSearch) (*models.AdminOrgsResult, error) {
|
|
limit := search.Limit
|
|
if limit <= 0 || limit > 100 {
|
|
limit = 50
|
|
}
|
|
|
|
args := []interface{}{}
|
|
argNum := 1
|
|
where := "WHERE 1=1"
|
|
|
|
if search.Query != "" {
|
|
where += ` AND (o.name ILIKE $` + itoa(argNum) +
|
|
` OR o.slug ILIKE $` + itoa(argNum) +
|
|
` OR u.email ILIKE $` + itoa(argNum) + `)`
|
|
args = append(args, "%"+search.Query+"%")
|
|
argNum++
|
|
}
|
|
|
|
switch search.Status {
|
|
case "pending_deletion":
|
|
where += ` AND o.deletion_scheduled_for IS NOT NULL`
|
|
case "active":
|
|
where += ` AND o.deletion_scheduled_for IS NULL`
|
|
}
|
|
|
|
if search.PlanID != nil {
|
|
where += ` AND s.plan_id = $` + itoa(argNum)
|
|
args = append(args, search.PlanID.UUID)
|
|
argNum++
|
|
}
|
|
switch search.PlanVisibility {
|
|
case "public":
|
|
where += ` AND p.public = TRUE`
|
|
case "private":
|
|
where += ` AND p.public = FALSE`
|
|
case "none":
|
|
where += ` AND s.id IS NULL`
|
|
}
|
|
if search.Enterprise {
|
|
where += ` AND s.is_enterprise = TRUE`
|
|
}
|
|
if search.ManagedPlan {
|
|
where += ` AND s.managed_at IS NOT NULL`
|
|
}
|
|
if search.CreatedWithin > 0 {
|
|
where += ` AND o.created_at >= NOW() - ($` + itoa(argNum) + `::int * INTERVAL '1 day')`
|
|
args = append(args, search.CreatedWithin)
|
|
argNum++
|
|
}
|
|
if search.HasOverrides {
|
|
where += ` AND EXISTS (SELECT 1 FROM organization_limit_overrides olo WHERE olo.organization_id = o.id)`
|
|
}
|
|
if models.OrgRiskState(search.RiskState).Valid() {
|
|
where += ` AND o.risk_state = $` + itoa(argNum)
|
|
args = append(args, search.RiskState)
|
|
argNum++
|
|
} else if search.RiskFlagged {
|
|
where += ` AND o.risk_state <> 'trusted'`
|
|
}
|
|
|
|
// Local helpers, same style as the rest of this builder.
|
|
addInt := func(frag string, v *int) {
|
|
if v != nil {
|
|
where += " AND " + fmt.Sprintf(frag, argNum)
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
addAfter := func(col string, v *time.Time) {
|
|
if v != nil {
|
|
where += " AND " + col + " >= $" + itoa(argNum)
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
addBefore := func(col string, v *time.Time) {
|
|
if v != nil {
|
|
where += " AND " + col + " < ($" + itoa(argNum) + "::timestamptz + INTERVAL '1 day')"
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
|
|
// Subscription state
|
|
if search.SubscriptionStatus != "" {
|
|
where += ` AND s.status::text = $` + itoa(argNum)
|
|
args = append(args, search.SubscriptionStatus)
|
|
argNum++
|
|
}
|
|
if search.CancelAtPeriodEnd {
|
|
where += ` AND s.cancel_at_period_end = TRUE`
|
|
}
|
|
if search.HasActiveSubscription {
|
|
where += ` AND EXISTS (SELECT 1 FROM subscriptions s2 WHERE s2.organization_id = o.id AND s2.status IN ('active','trialing'))`
|
|
}
|
|
if search.NoSubscription {
|
|
where += ` AND NOT EXISTS (SELECT 1 FROM subscriptions s2 WHERE s2.organization_id = o.id)`
|
|
}
|
|
if search.OwnerBanned {
|
|
where += ` AND u.banned_at IS NOT NULL`
|
|
}
|
|
|
|
// Acquisition channel
|
|
addChannel := func(col, v string) {
|
|
if v == "" {
|
|
return
|
|
}
|
|
where += ` AND oa.` + col + ` = $` + itoa(argNum)
|
|
args = append(args, v)
|
|
argNum++
|
|
}
|
|
addChannel("utm_source", search.UTMSource)
|
|
addChannel("utm_medium", search.UTMMedium)
|
|
addChannel("utm_campaign", search.UTMCampaign)
|
|
addChannel("referrer_host", search.ReferrerHost)
|
|
// Record presence is not proof of a known source; both set applies only HasAcquisition.
|
|
if search.HasAcquisition {
|
|
where += ` AND oa.organization_id IS NOT NULL`
|
|
} else if search.NoAcquisition {
|
|
where += ` AND oa.organization_id IS NULL`
|
|
}
|
|
|
|
// Relationship existence
|
|
if search.HasActiveCampaigns {
|
|
where += ` AND EXISTS (SELECT 1 FROM campaigns c WHERE c.organization_id = o.id AND c.status = 'active')`
|
|
}
|
|
if search.HasEmailAccounts {
|
|
where += ` AND EXISTS (SELECT 1 FROM email_accounts ea WHERE ea.organization_id = o.id)`
|
|
}
|
|
|
|
// Count ranges
|
|
addInt(`(SELECT COUNT(*) FROM organization_members om WHERE om.organization_id = o.id) >= $%d`, search.MemberCountMin)
|
|
addInt(`(SELECT COUNT(*) FROM organization_members om WHERE om.organization_id = o.id) <= $%d`, search.MemberCountMax)
|
|
addInt(`(SELECT COUNT(*) FROM email_accounts ea WHERE ea.organization_id = o.id) >= $%d`, search.EmailAccountCountMin)
|
|
addInt(`(SELECT COUNT(*) FROM email_accounts ea WHERE ea.organization_id = o.id) <= $%d`, search.EmailAccountCountMax)
|
|
addInt(`(SELECT COUNT(*) FROM campaigns c WHERE c.organization_id = o.id) >= $%d`, search.CampaignCountMin)
|
|
addInt(`(SELECT COUNT(*) FROM campaigns c WHERE c.organization_id = o.id) <= $%d`, search.CampaignCountMax)
|
|
|
|
// Date ranges
|
|
addAfter("o.created_at", search.CreatedAfter)
|
|
addBefore("o.created_at", search.CreatedBefore)
|
|
addAfter("s.trial_end", search.TrialEndAfter)
|
|
addBefore("s.trial_end", search.TrialEndBefore)
|
|
addAfter("s.current_period_end", search.CurrentPeriodEndAfter)
|
|
addBefore("s.current_period_end", search.CurrentPeriodEndBefore)
|
|
addAfter("o.updated_at", search.UpdatedAfter)
|
|
addBefore("o.updated_at", search.UpdatedBefore)
|
|
|
|
offset := search.Offset
|
|
|
|
orderCol := "o.created_at"
|
|
switch search.SortBy {
|
|
case "name":
|
|
orderCol = "o.name"
|
|
case "owner_email":
|
|
orderCol = "u.email"
|
|
case "member_count":
|
|
orderCol = "(SELECT COUNT(*) FROM organization_members om WHERE om.organization_id = o.id)"
|
|
case "email_account_count":
|
|
orderCol = "(SELECT COUNT(*) FROM email_accounts ea WHERE ea.organization_id = o.id)"
|
|
case "campaign_count":
|
|
orderCol = "(SELECT COUNT(*) FROM campaigns c WHERE c.organization_id = o.id)"
|
|
}
|
|
orderDir := "DESC"
|
|
if search.SortBy != "" && !search.SortDesc {
|
|
orderDir = "ASC"
|
|
}
|
|
orderBy := "ORDER BY " + orderCol + " " + orderDir + ", o.id DESC"
|
|
|
|
args = append(args, limit+1)
|
|
|
|
query := `
|
|
SELECT ` + adminOrgListColumns + `,
|
|
p.name, p.public, COALESCE(s.is_enterprise, FALSE),
|
|
s.managed_at, s.managed_reason, s.managed_until
|
|
FROM organizations o
|
|
JOIN users u ON u.id = o.owner_user_id
|
|
LEFT JOIN subscriptions s ON s.organization_id = o.id
|
|
LEFT JOIN plans p ON p.id = s.plan_id` + adminOrgAcquisitionJoin + `
|
|
` + where + `
|
|
` + orderBy + `
|
|
` + adminLimitOffset("$"+itoa(argNum), offset)
|
|
|
|
rows, err := r.db.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
items := []models.AdminOrgListItem{}
|
|
for rows.Next() {
|
|
var item models.AdminOrgListItem
|
|
var planName *string
|
|
var planPublic *bool
|
|
var isEnterprise bool
|
|
var managedAt *time.Time
|
|
var managedReason *string
|
|
var managedUntil *time.Time
|
|
if err := rows.Scan(
|
|
&item.ID, &item.Name, &item.Slug, &item.OwnerUserID,
|
|
&item.OwnerEmail, &item.OwnerFirstName, &item.OwnerLastName, &item.OwnerBannedAt,
|
|
&item.CreatedAt, &item.DeletionScheduledFor,
|
|
&item.MemberCount, &item.EmailAccountCount, &item.CampaignCount, &item.ActiveCampaigns,
|
|
&item.RiskState,
|
|
&item.UTMSource, &item.UTMMedium, &item.UTMCampaign, &item.LandingPath,
|
|
&item.ReferrerHost,
|
|
&item.Category,
|
|
&planName, &planPublic, &isEnterprise,
|
|
&managedAt, &managedReason, &managedUntil,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
item.PlanName = planName
|
|
item.PlanPublic = planPublic
|
|
item.IsEnterprise = isEnterprise
|
|
// Resolved here rather than in SQL so the in-force rule lives in one
|
|
// place, models.Subscription.IsManaged, and cannot drift between the
|
|
// list and the entitlement check.
|
|
if managedAt != nil {
|
|
probe := models.Subscription{ManagedAt: managedAt, ManagedUntil: managedUntil}
|
|
item.ManagedPlan = probe.IsManaged()
|
|
item.ManagedPlanExpired = probe.ManagedExpired()
|
|
item.ManagedPlanReason = managedReason
|
|
item.ManagedPlanUntil = managedUntil
|
|
}
|
|
items = append(items, item)
|
|
}
|
|
|
|
result := &models.AdminOrgsResult{
|
|
Data: items,
|
|
Pagination: models.Pagination{HasMore: len(items) > limit},
|
|
}
|
|
if len(items) > limit {
|
|
result.Data = items[:limit]
|
|
result.Pagination.NextCursor = adminNextCursor(offset, limit)
|
|
}
|
|
|
|
// Total count for the same filter — drop the trailing LIMIT arg.
|
|
countQuery := `SELECT COUNT(*) FROM organizations o JOIN users u ON u.id = o.owner_user_id LEFT JOIN subscriptions s ON s.organization_id = o.id LEFT JOIN plans p ON p.id = s.plan_id` + adminOrgAcquisitionJoin + ` ` + where
|
|
var total int64
|
|
if err := r.db.QueryRow(ctx, countQuery, args[:len(args)-1]...).Scan(&total); err == nil {
|
|
result.Pagination.Total = &total
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// GetOrganizationAdminDetail returns the per-org detail payload. Plan
|
|
// and subscription fields are LEFT JOINed so an org without an active
|
|
// subscription still resolves.
|
|
func (r *organizationRepository) GetOrganizationAdminDetail(ctx context.Context, orgID uuid.UUID) (*models.AdminOrgDetail, error) {
|
|
query := `
|
|
SELECT ` + adminOrgListColumns + `,
|
|
o.updated_at, o.deletion_scheduled_at,
|
|
p.name, s.status::text, s.is_enterprise, s.current_period_end, s.trial_end
|
|
FROM organizations o
|
|
JOIN users u ON u.id = o.owner_user_id
|
|
LEFT JOIN subscriptions s ON s.organization_id = o.id
|
|
LEFT JOIN plans p ON p.id = s.plan_id` + adminOrgAcquisitionJoin + `
|
|
WHERE o.id = $1`
|
|
|
|
var detail models.AdminOrgDetail
|
|
var isEnterprise *bool
|
|
err := r.db.QueryRow(ctx, query, orgID).Scan(
|
|
&detail.ID, &detail.Name, &detail.Slug, &detail.OwnerUserID,
|
|
&detail.OwnerEmail, &detail.OwnerFirstName, &detail.OwnerLastName, &detail.OwnerBannedAt,
|
|
&detail.CreatedAt, &detail.DeletionScheduledFor,
|
|
&detail.MemberCount, &detail.EmailAccountCount, &detail.CampaignCount, &detail.ActiveCampaigns,
|
|
&detail.RiskState,
|
|
&detail.UTMSource, &detail.UTMMedium, &detail.UTMCampaign, &detail.LandingPath,
|
|
&detail.ReferrerHost,
|
|
&detail.Category,
|
|
&detail.UpdatedAt, &detail.DeletionScheduledAt,
|
|
&detail.PlanName, &detail.SubscriptionStatus, &isEnterprise, &detail.CurrentPeriodEnd, &detail.TrialEnd,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if isEnterprise != nil {
|
|
detail.IsEnterprise = *isEnterprise
|
|
}
|
|
return &detail, nil
|
|
}
|
|
|
|
// GetOrganizationMembersForAdmin returns the members of an org with their
|
|
// joined user info, for admin consumption.
|
|
func (r *organizationRepository) GetOrganizationMembersForAdmin(ctx context.Context, orgID uuid.UUID) ([]models.AdminOrgMember, error) {
|
|
query := `
|
|
SELECT
|
|
om.id, om.organization_id, om.user_id, om.role, om.permissions,
|
|
om.invited_by, om.invited_at, om.accepted_at,
|
|
u.id, u.first_name, u.last_name, u.email
|
|
FROM organization_members om
|
|
JOIN users u ON u.id = om.user_id
|
|
WHERE om.organization_id = $1
|
|
ORDER BY om.invited_at ASC`
|
|
|
|
rows, err := r.db.Query(ctx, query, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
members := []models.AdminOrgMember{}
|
|
for rows.Next() {
|
|
var m models.AdminOrgMember
|
|
var summary models.AdminUserSummary
|
|
if err := rows.Scan(
|
|
&m.ID, &m.OrganizationID, &m.UserID, &m.Role, &m.Permissions,
|
|
&m.InvitedBy, &m.InvitedAt, &m.AcceptedAt,
|
|
&summary.ID, &summary.FirstName, &summary.LastName, &summary.Email,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
m.User = &summary
|
|
members = append(members, m)
|
|
}
|
|
return members, nil
|
|
}
|
|
|
|
// GetOrganizationLimitOverrides reads the override row for an org.
|
|
// Returns (nil, nil) when no row exists — callers should treat that as
|
|
// "no overrides set, inherit everything from plan."
|
|
func (r *organizationRepository) GetOrganizationLimitOverrides(ctx context.Context, orgID uuid.UUID) (*models.OrganizationLimitOverrides, error) {
|
|
query := `
|
|
SELECT organization_id, max_campaigns, max_active_campaigns, max_team_members,
|
|
max_email_accounts, max_contacts, daily_campaign_limit,
|
|
granted_by, granted_at, updated_at, notes
|
|
FROM organization_limit_overrides
|
|
WHERE organization_id = $1`
|
|
|
|
var o models.OrganizationLimitOverrides
|
|
err := r.db.QueryRow(ctx, query, orgID).Scan(
|
|
&o.OrganizationID, &o.MaxCampaigns, &o.MaxActiveCampaigns, &o.MaxTeamMembers,
|
|
&o.MaxEmailAccounts, &o.MaxContacts, &o.DailyCampaignLimit,
|
|
&o.GrantedBy, &o.GrantedAt, &o.UpdatedAt, &o.Notes,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &o, nil
|
|
}
|
|
|
|
// UpsertOrganizationLimitOverrides applies a partial update. Nil fields
|
|
// in the request are left untouched on existing rows; on first-insert
|
|
// they default to 0 (= no override) via the table defaults.
|
|
//
|
|
// granted_by / granted_at are stamped on every write so the audit trail
|
|
// reflects the most recent admin who touched any field. updated_at is
|
|
// always advanced.
|
|
func (r *organizationRepository) UpsertOrganizationLimitOverrides(ctx context.Context, orgID uuid.UUID, req *models.UpdateOrgOverridesRequest, grantedBy uuid.UUID) (*models.OrganizationLimitOverrides, error) {
|
|
maxCampaigns := nullableInt(req.MaxCampaigns)
|
|
maxActive := nullableInt(req.MaxActiveCampaigns)
|
|
maxMembers := nullableInt(req.MaxTeamMembers)
|
|
maxEmails := nullableInt(req.MaxEmailAccounts)
|
|
maxContacts := nullableInt(req.MaxContacts)
|
|
dailyLimit := nullableInt(req.DailyCampaignLimit)
|
|
notes := req.Notes
|
|
|
|
query := `
|
|
INSERT INTO organization_limit_overrides (
|
|
organization_id,
|
|
max_campaigns, max_active_campaigns, max_team_members,
|
|
max_email_accounts, max_contacts, daily_campaign_limit,
|
|
granted_by, granted_at, updated_at, notes
|
|
) VALUES (
|
|
$1,
|
|
COALESCE($2, 0), COALESCE($3, 0), COALESCE($4, 0),
|
|
COALESCE($5, 0), COALESCE($6, 0), COALESCE($7, 0),
|
|
$8, NOW(), NOW(), COALESCE($9, '')
|
|
)
|
|
ON CONFLICT (organization_id) DO UPDATE SET
|
|
max_campaigns = COALESCE($2, organization_limit_overrides.max_campaigns),
|
|
max_active_campaigns = COALESCE($3, organization_limit_overrides.max_active_campaigns),
|
|
max_team_members = COALESCE($4, organization_limit_overrides.max_team_members),
|
|
max_email_accounts = COALESCE($5, organization_limit_overrides.max_email_accounts),
|
|
max_contacts = COALESCE($6, organization_limit_overrides.max_contacts),
|
|
daily_campaign_limit = COALESCE($7, organization_limit_overrides.daily_campaign_limit),
|
|
granted_by = $8,
|
|
granted_at = NOW(),
|
|
updated_at = NOW(),
|
|
notes = COALESCE($9, organization_limit_overrides.notes)
|
|
RETURNING organization_id, max_campaigns, max_active_campaigns, max_team_members,
|
|
max_email_accounts, max_contacts, daily_campaign_limit,
|
|
granted_by, granted_at, updated_at, notes`
|
|
|
|
var o models.OrganizationLimitOverrides
|
|
err := r.db.QueryRow(ctx, query,
|
|
orgID,
|
|
maxCampaigns, maxActive, maxMembers,
|
|
maxEmails, maxContacts, dailyLimit,
|
|
grantedBy, notes,
|
|
).Scan(
|
|
&o.OrganizationID, &o.MaxCampaigns, &o.MaxActiveCampaigns, &o.MaxTeamMembers,
|
|
&o.MaxEmailAccounts, &o.MaxContacts, &o.DailyCampaignLimit,
|
|
&o.GrantedBy, &o.GrantedAt, &o.UpdatedAt, &o.Notes,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &o, nil
|
|
}
|
|
|
|
func nullableInt(p *int) interface{} {
|
|
if p == nil {
|
|
return nil
|
|
}
|
|
return *p
|
|
}
|
|
|
|
// CreateLimitRequest inserts a new limit-increase request row. The
|
|
// (organization_id, field) WHERE status = 'pending' partial unique
|
|
// index in migration 000046 makes duplicate-pending rejection a
|
|
// constraint violation rather than a service-side query.
|
|
func (r *organizationRepository) CreateLimitRequest(ctx context.Context, req *models.LimitIncreaseRequest) error {
|
|
const query = `
|
|
INSERT INTO limit_increase_requests
|
|
(id, organization_id, field, current_effective, requested,
|
|
reason, status, submitted_by, submitted_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7, NOW())
|
|
RETURNING submitted_at`
|
|
return r.db.QueryRow(ctx, query,
|
|
req.ID, req.OrganizationID, req.Field, req.CurrentEffective, req.Requested,
|
|
req.Reason, req.SubmittedBy,
|
|
).Scan(&req.SubmittedAt)
|
|
}
|
|
|
|
func (r *organizationRepository) GetLimitRequest(ctx context.Context, id uuid.UUID) (*models.LimitIncreaseRequest, error) {
|
|
const query = `
|
|
SELECT id, organization_id, field, current_effective, requested,
|
|
reason, status, submitted_by, submitted_at,
|
|
reviewed_by, reviewed_at, review_notes
|
|
FROM limit_increase_requests
|
|
WHERE id = $1`
|
|
var lr models.LimitIncreaseRequest
|
|
err := r.db.QueryRow(ctx, query, id).Scan(
|
|
&lr.ID, &lr.OrganizationID, &lr.Field, &lr.CurrentEffective, &lr.Requested,
|
|
&lr.Reason, &lr.Status, &lr.SubmittedBy, &lr.SubmittedAt,
|
|
&lr.ReviewedBy, &lr.ReviewedAt, &lr.ReviewNotes,
|
|
)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &lr, nil
|
|
}
|
|
|
|
func (r *organizationRepository) ListLimitRequestsForOrg(ctx context.Context, orgID uuid.UUID) ([]models.LimitIncreaseRequest, error) {
|
|
const query = `
|
|
SELECT id, organization_id, field, current_effective, requested,
|
|
reason, status, submitted_by, submitted_at,
|
|
reviewed_by, reviewed_at, review_notes
|
|
FROM limit_increase_requests
|
|
WHERE organization_id = $1
|
|
ORDER BY submitted_at DESC`
|
|
rows, err := r.db.Query(ctx, query, orgID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []models.LimitIncreaseRequest{}
|
|
for rows.Next() {
|
|
var lr models.LimitIncreaseRequest
|
|
if err := rows.Scan(
|
|
&lr.ID, &lr.OrganizationID, &lr.Field, &lr.CurrentEffective, &lr.Requested,
|
|
&lr.Reason, &lr.Status, &lr.SubmittedBy, &lr.SubmittedAt,
|
|
&lr.ReviewedBy, &lr.ReviewedAt, &lr.ReviewNotes,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, lr)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ListLimitRequestsForAdmin joins org + submitter so the admin queue can show
|
|
// context per row without an extra fan-out fetch. Faceted + cursor paginated,
|
|
// mirroring SearchOrganizationsForAdmin (incremental WHERE builder, id keyset,
|
|
// LIMIT+1 has_more, separate COUNT).
|
|
func (r *organizationRepository) ListLimitRequestsForAdmin(ctx context.Context, search *models.AdminLimitRequestSearch) (*models.AdminLimitRequestsResult, error) {
|
|
limit := search.Limit
|
|
if limit <= 0 || limit > 100 {
|
|
limit = 50
|
|
}
|
|
|
|
args := []interface{}{}
|
|
argNum := 1
|
|
where := "WHERE 1=1"
|
|
|
|
if search.Query != "" {
|
|
where += ` AND (o.name ILIKE $` + itoa(argNum) + ` OR o.slug ILIKE $` + itoa(argNum) + ` OR u.email ILIKE $` + itoa(argNum) + ` OR lr.reason ILIKE $` + itoa(argNum) + `)`
|
|
args = append(args, "%"+search.Query+"%")
|
|
argNum++
|
|
}
|
|
if search.Status != "" && search.Status != "all" {
|
|
where += " AND lr.status = $" + itoa(argNum)
|
|
args = append(args, search.Status)
|
|
argNum++
|
|
}
|
|
if search.Field != "" {
|
|
where += " AND lr.field = $" + itoa(argNum)
|
|
args = append(args, search.Field)
|
|
argNum++
|
|
}
|
|
if search.OrgID != nil {
|
|
where += " AND lr.organization_id = $" + itoa(argNum)
|
|
args = append(args, search.OrgID.UUID)
|
|
argNum++
|
|
}
|
|
if search.SubmittedBy != nil {
|
|
where += " AND lr.submitted_by = $" + itoa(argNum)
|
|
args = append(args, search.SubmittedBy.UUID)
|
|
argNum++
|
|
}
|
|
if search.Reviewed {
|
|
where += " AND lr.reviewed_at IS NOT NULL"
|
|
}
|
|
if search.Unreviewed {
|
|
where += " AND lr.reviewed_at IS NULL"
|
|
}
|
|
|
|
addInt := func(frag string, v *int) {
|
|
if v != nil {
|
|
where += " AND " + fmt.Sprintf(frag, argNum)
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
addAfter := func(col string, v *time.Time) {
|
|
if v != nil {
|
|
where += " AND " + col + " >= $" + itoa(argNum)
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
addBefore := func(col string, v *time.Time) {
|
|
if v != nil {
|
|
where += " AND " + col + " < ($" + itoa(argNum) + "::timestamptz + INTERVAL '1 day')"
|
|
args = append(args, *v)
|
|
argNum++
|
|
}
|
|
}
|
|
|
|
addInt(`lr.requested >= $%d`, search.RequestedMin)
|
|
addInt(`lr.requested <= $%d`, search.RequestedMax)
|
|
addInt(`lr.current_effective >= $%d`, search.CurrentEffectiveMin)
|
|
addInt(`lr.current_effective <= $%d`, search.CurrentEffectiveMax)
|
|
|
|
if search.SubmittedWithin > 0 {
|
|
where += ` AND lr.submitted_at >= NOW() - ($` + itoa(argNum) + `::int * INTERVAL '1 day')`
|
|
args = append(args, search.SubmittedWithin)
|
|
argNum++
|
|
}
|
|
addAfter("lr.submitted_at", search.SubmittedAfter)
|
|
addBefore("lr.submitted_at", search.SubmittedBefore)
|
|
addAfter("lr.reviewed_at", search.ReviewedAfter)
|
|
addBefore("lr.reviewed_at", search.ReviewedBefore)
|
|
|
|
offset := search.Offset
|
|
|
|
orderCol := "lr.submitted_at"
|
|
switch search.SortBy {
|
|
case "requested":
|
|
orderCol = "lr.requested"
|
|
case "current_effective":
|
|
orderCol = "lr.current_effective"
|
|
case "reviewed_at":
|
|
orderCol = "lr.reviewed_at"
|
|
case "status":
|
|
orderCol = "lr.status::text"
|
|
case "field":
|
|
orderCol = "lr.field"
|
|
case "org_name":
|
|
orderCol = "o.name"
|
|
}
|
|
orderDir := "DESC"
|
|
if search.SortBy != "" && !search.SortDesc {
|
|
orderDir = "ASC"
|
|
}
|
|
orderBy := "ORDER BY " + orderCol + " " + orderDir + ", lr.id DESC"
|
|
|
|
args = append(args, limit+1)
|
|
|
|
query := `
|
|
SELECT lr.id, lr.organization_id, lr.field, lr.current_effective, lr.requested,
|
|
lr.reason, lr.status, lr.submitted_by, lr.submitted_at,
|
|
lr.reviewed_by, lr.reviewed_at, lr.review_notes,
|
|
o.id, o.name, o.slug, o.owner_user_id, o.created_at, o.updated_at,
|
|
COALESCE(u.id, '00000000-0000-0000-0000-000000000000'::uuid), COALESCE(u.first_name, ''), COALESCE(u.last_name, ''), COALESCE(u.email, ''),
|
|
COALESCE(u.created_at, lr.submitted_at), COALESCE(u.updated_at, lr.submitted_at)
|
|
FROM limit_increase_requests lr
|
|
JOIN organizations o ON o.id = lr.organization_id
|
|
LEFT JOIN users u ON u.id = lr.submitted_by
|
|
` + where + `
|
|
` + orderBy + `
|
|
` + adminLimitOffset("$"+itoa(argNum), offset)
|
|
|
|
rows, err := r.db.Query(ctx, query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []models.LimitIncreaseRequest{}
|
|
for rows.Next() {
|
|
var lr models.LimitIncreaseRequest
|
|
var org models.Organization
|
|
var user models.User
|
|
if err := rows.Scan(
|
|
&lr.ID, &lr.OrganizationID, &lr.Field, &lr.CurrentEffective, &lr.Requested,
|
|
&lr.Reason, &lr.Status, &lr.SubmittedBy, &lr.SubmittedAt,
|
|
&lr.ReviewedBy, &lr.ReviewedAt, &lr.ReviewNotes,
|
|
&org.ID, &org.Name, &org.Slug, &org.OwnerUserID, &org.CreatedAt, &org.UpdatedAt,
|
|
&user.ID, &user.FirstName, &user.LastName, &user.Email, &user.CreatedAt, &user.UpdatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
lr.Organization = &org
|
|
// A submitter whose account was deleted has no summary.
|
|
if user.ID != uuid.Nil {
|
|
lr.SubmittedByUser = &user
|
|
}
|
|
items = append(items, lr)
|
|
}
|
|
|
|
result := &models.AdminLimitRequestsResult{
|
|
Data: items,
|
|
Pagination: models.Pagination{HasMore: len(items) > limit},
|
|
}
|
|
if len(items) > limit {
|
|
result.Data = items[:limit]
|
|
result.Pagination.NextCursor = adminNextCursor(offset, limit)
|
|
}
|
|
|
|
// Total count for the same filter — drop the trailing LIMIT arg.
|
|
countQuery := `SELECT COUNT(*) FROM limit_increase_requests lr JOIN organizations o ON o.id = lr.organization_id LEFT JOIN users u ON u.id = lr.submitted_by ` + where
|
|
var total int64
|
|
if err := r.db.QueryRow(ctx, countQuery, args[:len(args)-1]...).Scan(&total); err == nil {
|
|
result.Pagination.Total = &total
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func (r *organizationRepository) UpdateLimitRequestStatus(ctx context.Context, id uuid.UUID, status models.LimitRequestStatus, reviewedBy uuid.UUID, notes string) error {
|
|
const query = `
|
|
UPDATE limit_increase_requests
|
|
SET status = $2, reviewed_by = $3, reviewed_at = NOW(), review_notes = $4
|
|
WHERE id = $1`
|
|
_, err := r.db.Exec(ctx, query, id, status, reviewedBy, notes)
|
|
return err
|
|
}
|
|
|
|
// RecordOrganizationAcquisition stores where a signup came from. First write
|
|
// wins: the row is the account's origin, and nothing later changes it.
|
|
func (r *organizationRepository) RecordOrganizationAcquisition(ctx context.Context, acq *models.OrgAcquisition) error {
|
|
if acq == nil {
|
|
return nil
|
|
}
|
|
n := acq.Normalize()
|
|
if n.Empty() {
|
|
return nil
|
|
}
|
|
_, err := r.db.Exec(ctx, `
|
|
INSERT INTO organization_acquisition (
|
|
organization_id, landing_path, referrer_host,
|
|
utm_source, utm_medium, utm_campaign, utm_term, utm_content
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
ON CONFLICT (organization_id) DO NOTHING`,
|
|
acq.OrganizationID,
|
|
nullIfEmpty(n.LandingPath), nullIfEmpty(n.ReferrerHost),
|
|
nullIfEmpty(n.UTMSource), nullIfEmpty(n.UTMMedium), nullIfEmpty(n.UTMCampaign),
|
|
nullIfEmpty(n.UTMTerm), nullIfEmpty(n.UTMContent),
|
|
)
|
|
return err
|
|
}
|
|
|
|
// GetOrganizationAcquisition returns nil when the signup carried nothing,
|
|
// which is the normal case for a direct visit.
|
|
func (r *organizationRepository) GetOrganizationAcquisition(ctx context.Context, orgID uuid.UUID) (*models.OrgAcquisition, error) {
|
|
acq := &models.OrgAcquisition{OrganizationID: orgID}
|
|
var landingPath, referrerHost, source, medium, campaign, term, content *string
|
|
err := r.db.QueryRow(ctx, `
|
|
SELECT landing_path, referrer_host, utm_source, utm_medium, utm_campaign, utm_term, utm_content
|
|
FROM organization_acquisition WHERE organization_id = $1`, orgID).
|
|
Scan(&landingPath, &referrerHost, &source, &medium, &campaign, &term, &content)
|
|
if err == pgx.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
acq.LandingPath = derefString(landingPath)
|
|
acq.ReferrerHost = derefString(referrerHost)
|
|
acq.UTMSource = derefString(source)
|
|
acq.UTMMedium = derefString(medium)
|
|
acq.UTMCampaign = derefString(campaign)
|
|
acq.UTMTerm = derefString(term)
|
|
acq.UTMContent = derefString(content)
|
|
return acq, nil
|
|
}
|
|
|
|
func derefString(v *string) string {
|
|
if v == nil {
|
|
return ""
|
|
}
|
|
return *v
|
|
}
|
|
|
|
// nullIfEmpty writes SQL NULL for an empty string, so an optional text column
|
|
// stores NULL rather than ” and IS NULL checks keep working.
|
|
func nullIfEmpty(s string) any {
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
return s
|
|
}
|