Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/.render-build-trigger
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
# This file is used to force Docker service rebuilds in PR previews
# Modify LAST_UPDATE to trigger rebuilds

LAST_UPDATE=2026-11-24T07:46:55Z
LAST_UPDATE=2026-12-01T17:36:57Z

# Instructions:
# 1. To force rebuild of Docker services in a PR, update LAST_UPDATE
# 2. Run: perl -i -pe "s/LAST_UPDATE=2026-11-24T07:46:55Z
# 2. Run: perl -i -pe "s/LAST_UPDATE=2026-12-01T17:36:57Z
# 2. Commit and push changes to trigger Docker rebuilds
16 changes: 16 additions & 0 deletions backend/database/migrations/065_legacy_products_by_org.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- Migration 065: per-product breakdown of the legacy systems counter.
--
-- The old my shows each reseller its "Installed products": how many systems run
-- NethService, NethSecurity and NethVoice (server.system_products). Sales still
-- needs those figures for the estate that has not migrated, so the legacy sync
-- pushes them next to the total of migration 044. A system running two products
-- counts in both columns, so they do not add up to total.

ALTER TABLE legacy_systems_by_org
ADD COLUMN IF NOT EXISTS nethservice INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS nethsecurity INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS nethvoice INTEGER NOT NULL DEFAULT 0;

COMMENT ON COLUMN legacy_systems_by_org.nethservice IS 'Of total, systems running NethService (legacy system_products); a system with several products counts in each';
COMMENT ON COLUMN legacy_systems_by_org.nethsecurity IS 'Of total, systems running NethSecurity (legacy system_products)';
COMMENT ON COLUMN legacy_systems_by_org.nethvoice IS 'Of total, systems running NethVoice (legacy system_products)';
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Rollback migration 065: drop the per-product breakdown, the total stays.

ALTER TABLE legacy_systems_by_org
DROP COLUMN IF EXISTS nethservice,
DROP COLUMN IF EXISTS nethsecurity,
DROP COLUMN IF EXISTS nethvoice;
8 changes: 7 additions & 1 deletion backend/database/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -948,17 +948,23 @@ COMMENT ON COLUMN alerts_totals_by_org.updated_at IS 'Last successful refresh fo
-- =============================================================================
-- LEGACY SYSTEMS COUNTER
-- =============================================================================
-- Systems still living on the old my, per organization (migration 044)
-- Systems still living on the old my, per organization (migrations 044, 065)

CREATE TABLE IF NOT EXISTS legacy_systems_by_org (
organization_id VARCHAR(255) PRIMARY KEY,
total INTEGER NOT NULL DEFAULT 0,
nethservice INTEGER NOT NULL DEFAULT 0,
nethsecurity INTEGER NOT NULL DEFAULT 0,
nethvoice INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

COMMENT ON TABLE legacy_systems_by_org IS 'Per-organization count of systems still living on the old my (legacy.my.nethesis.it), pushed by the proxy_sync cron on the legacy host. Transitional: drop at decommission';
COMMENT ON COLUMN legacy_systems_by_org.organization_id IS 'Logto org id of the reseller/distributor the legacy VAT maps to';
COMMENT ON COLUMN legacy_systems_by_org.total IS 'Systems on the old my with no counterpart here, excluding deleted and disabled ones';
COMMENT ON COLUMN legacy_systems_by_org.nethservice IS 'Of total, systems running NethService (legacy system_products); a system with several products counts in each';
COMMENT ON COLUMN legacy_systems_by_org.nethsecurity IS 'Of total, systems running NethSecurity (legacy system_products)';
COMMENT ON COLUMN legacy_systems_by_org.nethvoice IS 'Of total, systems running NethVoice (legacy system_products)';
COMMENT ON COLUMN legacy_systems_by_org.updated_at IS 'Last successful push for this org; stale rows mean the legacy sync is lagging or stopped';

-- =============================================================================
Expand Down
8 changes: 6 additions & 2 deletions backend/entities/local_customers.go
Original file line number Diff line number Diff line change
Expand Up @@ -1024,10 +1024,14 @@ func (r *LocalCustomerRepository) GetStats(id string) (*models.CustomerStats, er
(SELECT COUNT(*) FROM users WHERE organization_id = $1 AND deleted_at IS NULL) as users_count,
(SELECT COUNT(*) FROM systems WHERE organization_id = $1 AND deleted_at IS NULL) as systems_count,
` + assignedApplicationsCount("$1") + ` as applications_assigned_count,
` + unassignedApplicationsCount("$1") + ` as applications_unassigned_count
` + unassignedApplicationsCount("$1") + ` as applications_unassigned_count,
` + productsCount("$1", "") + `
`

err = r.db.QueryRow(query, *customer.LogtoID).Scan(&stats.UsersCount, &stats.SystemsCount, &stats.ApplicationsAssignedCount, &stats.ApplicationsUnassignedCount)
err = r.db.QueryRow(query, *customer.LogtoID).Scan(
&stats.UsersCount, &stats.SystemsCount, &stats.ApplicationsAssignedCount, &stats.ApplicationsUnassignedCount,
&stats.Products.NethService, &stats.Products.NethSecurity, &stats.Products.NethVoice,
)
if err != nil {
return nil, fmt.Errorf("failed to get customer stats: %w", err)
}
Expand Down
8 changes: 8 additions & 0 deletions backend/entities/local_distributors.go
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,10 @@ func (r *LocalDistributorRepository) GetStats(id string) (*models.DistributorSta
)) as systems_hierarchy_count,
` + legacySystemsCount("$1") + ` as legacy_systems_count,
` + legacySystemsCount(hierarchy) + ` as legacy_systems_hierarchy_count,
` + legacyProductsCount("$1", "") + `,
` + legacyProductsCount(hierarchy, "_hierarchy") + `,
` + productsCount("$1", "") + `,
` + productsCount(hierarchy, "_hierarchy") + `,
(SELECT COUNT(*) FROM resellers WHERE custom_data->>'createdBy' = $1 AND deleted_at IS NULL) as resellers_count,
(SELECT COUNT(*) FROM customers c WHERE c.deleted_at IS NULL AND (
c.custom_data->>'createdBy' = $1
Expand All @@ -894,6 +898,10 @@ func (r *LocalDistributorRepository) GetStats(id string) (*models.DistributorSta
&stats.UsersCount, &stats.UsersHierarchyCount,
&stats.SystemsCount, &stats.SystemsHierarchyCount,
&stats.LegacySystemsCount, &stats.LegacySystemsHierarchyCount,
&stats.LegacyProducts.NethService, &stats.LegacyProducts.NethSecurity, &stats.LegacyProducts.NethVoice,
&stats.LegacyProductsHierarchy.NethService, &stats.LegacyProductsHierarchy.NethSecurity, &stats.LegacyProductsHierarchy.NethVoice,
&stats.Products.NethService, &stats.Products.NethSecurity, &stats.Products.NethVoice,
&stats.ProductsHierarchy.NethService, &stats.ProductsHierarchy.NethSecurity, &stats.ProductsHierarchy.NethVoice,
&stats.ResellersCount, &stats.CustomersCount,
&stats.ApplicationsAssignedCount, &stats.ApplicationsUnassignedCount,
&stats.ApplicationsAssignedHierarchyCount, &stats.ApplicationsUnassignedHierarchyCount,
Expand Down
43 changes: 35 additions & 8 deletions backend/entities/local_legacy_systems_by_org.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/lib/pq"

"github.com/nethesis/my/backend/database"
"github.com/nethesis/my/backend/models"
)

// LocalLegacySystemsByOrgRepository serves the per-organization count of
Expand Down Expand Up @@ -49,11 +50,28 @@ func legacySystemsCount(orgSet string) string {
return "(SELECT COALESCE(SUM(l.total), 0) FROM legacy_systems_by_org l WHERE l.organization_id IN (" + orgSet + "))"
}

// legacyProductColumns are the per-product columns, in scan order.
var legacyProductColumns = []string{"nethservice", "nethsecurity", "nethvoice"}

// legacyProductsCount is legacySystemsCount for the per-product columns: three
// SQL expressions in legacyProductColumns order, aliased with the given suffix.
func legacyProductsCount(orgSet, suffix string) string {
out := ""
for i, col := range legacyProductColumns {
if i > 0 {
out += ",\n\t\t\t"
}
out += "(SELECT COALESCE(SUM(l." + col + "), 0) FROM legacy_systems_by_org l WHERE l.organization_id IN (" + orgSet + ")) as legacy_" + col + suffix
}
return out
}

// LegacySystemsSum is the aggregated answer for one scope. OldestUpdate is the
// MIN(updated_at) across the queried rows, so a caller can tell a genuine zero
// from a sync that stopped running. It is the zero time when no rows matched.
type LegacySystemsSum struct {
Total int
Products models.ProductCounts
OldestUpdate time.Time
}

Expand All @@ -72,10 +90,13 @@ func (r *LocalLegacySystemsByOrgRepository) SumByOrgIDs(orgIDs []string) (Legacy
err := r.db.QueryRow(`
SELECT
COALESCE(SUM(total), 0),
COALESCE(SUM(nethservice), 0),
COALESCE(SUM(nethsecurity), 0),
COALESCE(SUM(nethvoice), 0),
MIN(updated_at)
FROM legacy_systems_by_org
WHERE organization_id = ANY($1)
`, pq.Array(orgIDs)).Scan(&out.Total, &oldest)
`, pq.Array(orgIDs)).Scan(&out.Total, &out.Products.NethService, &out.Products.NethSecurity, &out.Products.NethVoice, &oldest)
if err != nil {
return LegacySystemsSum{}, fmt.Errorf("sum legacy_systems_by_org: %w", err)
}
Expand All @@ -92,8 +113,14 @@ func (r *LocalLegacySystemsByOrgRepository) SumAll() (LegacySystemsSum, error) {
var out LegacySystemsSum
var oldest sql.NullTime
err := r.db.QueryRow(`
SELECT COALESCE(SUM(total), 0), MIN(updated_at) FROM legacy_systems_by_org
`).Scan(&out.Total, &oldest)
SELECT
COALESCE(SUM(total), 0),
COALESCE(SUM(nethservice), 0),
COALESCE(SUM(nethsecurity), 0),
COALESCE(SUM(nethvoice), 0),
MIN(updated_at)
FROM legacy_systems_by_org
`).Scan(&out.Total, &out.Products.NethService, &out.Products.NethSecurity, &out.Products.NethVoice, &oldest)
if err != nil {
return LegacySystemsSum{}, fmt.Errorf("sum all legacy_systems_by_org: %w", err)
}
Expand All @@ -110,7 +137,7 @@ func (r *LocalLegacySystemsByOrgRepository) SumAll() (LegacySystemsSum, error) {
// the payload, and an upsert-only write would leave its last non-zero count
// there for good. Organizations whose VAT matches nothing here are simply not
// in the payload.
func (r *LocalLegacySystemsByOrgRepository) ReplaceAll(counts map[string]int) error {
func (r *LocalLegacySystemsByOrgRepository) ReplaceAll(counts map[string]models.LegacySystemCount) error {
tx, err := r.db.Begin()
if err != nil {
return fmt.Errorf("begin legacy_systems_by_org replace: %w", err)
Expand All @@ -122,19 +149,19 @@ func (r *LocalLegacySystemsByOrgRepository) ReplaceAll(counts map[string]int) er
}

stmt, err := tx.Prepare(`
INSERT INTO legacy_systems_by_org (organization_id, total, updated_at)
VALUES ($1, $2, NOW())
INSERT INTO legacy_systems_by_org (organization_id, total, nethservice, nethsecurity, nethvoice, updated_at)
VALUES ($1, $2, $3, $4, $5, NOW())
`)
if err != nil {
return fmt.Errorf("prepare legacy_systems_by_org insert: %w", err)
}
defer func() { _ = stmt.Close() }()

for orgID, total := range counts {
for orgID, count := range counts {
if orgID == "" {
continue
}
if _, err := stmt.Exec(orgID, total); err != nil {
if _, err := stmt.Exec(orgID, count.Total, count.NethService, count.NethSecurity, count.NethVoice); err != nil {
return fmt.Errorf("insert legacy count for %s: %w", orgID, err)
}
}
Expand Down
21 changes: 12 additions & 9 deletions backend/entities/local_legacy_systems_by_org_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/stretchr/testify/require"

"github.com/nethesis/my/backend/database"
"github.com/nethesis/my/backend/models"
)

func setupLegacySystemsMock(t *testing.T) (*LocalLegacySystemsByOrgRepository, sqlmock.Sqlmock, func()) {
Expand Down Expand Up @@ -48,12 +49,13 @@ func TestLegacySumByOrgIDs_AggregatesAcrossTheScope(t *testing.T) {

oldest := time.Now().Add(-3 * time.Hour).UTC()
mock.ExpectQuery("SELECT(.|\n)*FROM legacy_systems_by_org").
WillReturnRows(sqlmock.NewRows([]string{"sum", "min"}).AddRow(42, oldest))
WillReturnRows(sqlmock.NewRows([]string{"sum", "nethservice", "nethsecurity", "nethvoice", "min"}).AddRow(42, 7, 20, 9, oldest))

sum, err := repo.SumByOrgIDs([]string{"org-a", "org-b"})

assert.NoError(t, err)
assert.Equal(t, 42, sum.Total)
assert.Equal(t, models.ProductCounts{NethService: 7, NethSecurity: 20, NethVoice: 9}, sum.Products)
assert.WithinDuration(t, oldest, sum.OldestUpdate, time.Second)
assert.NoError(t, mock.ExpectationsWereMet())
}
Expand All @@ -66,7 +68,7 @@ func TestLegacySumByOrgIDs_NoRowsIsZeroWithNoTimestamp(t *testing.T) {
defer cleanup()

mock.ExpectQuery("SELECT(.|\n)*FROM legacy_systems_by_org").
WillReturnRows(sqlmock.NewRows([]string{"sum", "min"}).AddRow(0, nil))
WillReturnRows(sqlmock.NewRows([]string{"sum", "nethservice", "nethsecurity", "nethvoice", "min"}).AddRow(0, 0, 0, 0, nil))

sum, err := repo.SumByOrgIDs([]string{"org-never-synced"})

Expand All @@ -80,13 +82,14 @@ func TestLegacySumAll_CoversEveryOrganization(t *testing.T) {
repo, mock, cleanup := setupLegacySystemsMock(t)
defer cleanup()

mock.ExpectQuery("SELECT COALESCE\\(SUM\\(total\\), 0\\), MIN\\(updated_at\\) FROM legacy_systems_by_org").
WillReturnRows(sqlmock.NewRows([]string{"sum", "min"}).AddRow(19312, time.Now().UTC()))
mock.ExpectQuery("SELECT(.|\n)*FROM legacy_systems_by_org").
WillReturnRows(sqlmock.NewRows([]string{"sum", "nethservice", "nethsecurity", "nethvoice", "min"}).AddRow(19312, 3499, 10278, 7927, time.Now().UTC()))

sum, err := repo.SumAll()

assert.NoError(t, err)
assert.Equal(t, 19312, sum.Total)
assert.Equal(t, 10278, sum.Products.NethSecurity)
assert.NoError(t, mock.ExpectationsWereMet())
}

Expand All @@ -103,11 +106,11 @@ func TestLegacyReplaceAll_ClearsBeforeInserting(t *testing.T) {
WillReturnResult(sqlmock.NewResult(0, 7))
mock.ExpectPrepare("INSERT INTO legacy_systems_by_org").
ExpectExec().
WithArgs("org-a", 12).
WithArgs("org-a", 12, 3, 8, 2).
WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()

err := repo.ReplaceAll(map[string]int{"org-a": 12})
err := repo.ReplaceAll(map[string]models.LegacySystemCount{"org-a": {OrganizationID: "org-a", Total: 12, NethService: 3, NethSecurity: 8, NethVoice: 2}})

assert.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
Expand All @@ -126,7 +129,7 @@ func TestLegacyReplaceAll_EmptyPayloadEmptiesTheTable(t *testing.T) {
mock.ExpectPrepare("INSERT INTO legacy_systems_by_org")
mock.ExpectCommit()

err := repo.ReplaceAll(map[string]int{})
err := repo.ReplaceAll(map[string]models.LegacySystemCount{})

assert.NoError(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
Expand All @@ -141,11 +144,11 @@ func TestLegacyReplaceAll_RollsBackWhenAnInsertFails(t *testing.T) {
WillReturnResult(sqlmock.NewResult(0, 2))
mock.ExpectPrepare("INSERT INTO legacy_systems_by_org").
ExpectExec().
WithArgs("org-a", 5).
WithArgs("org-a", 5, 0, 0, 0).
WillReturnError(assert.AnError)
mock.ExpectRollback()

err := repo.ReplaceAll(map[string]int{"org-a": 5})
err := repo.ReplaceAll(map[string]models.LegacySystemCount{"org-a": {OrganizationID: "org-a", Total: 5}})

assert.Error(t, err)
assert.NoError(t, mock.ExpectationsWereMet())
Expand Down
Loading
Loading