Batch signature and approval notifications via debounced worker

Replace the immediate per-document approval email and the manual
"send signing notifications" action with a single debounced worker that
batches pending requests per recipient and organization.

The worker (go.gearno.de/kit/worker) polls on an interval (default 5m)
and claims one (organization, recipient) group at a time, sending one
consolidated signing email and/or one approval email per recipient/org
that lists every document awaiting their signature or approval. The
claim is a conditional UPDATE that doubles as concurrency-safe dedup, so
several workers never email the same group twice.

Each request is notified once it has been pending past the debounce
delay (default 15m), then reminded at 1x, 2x and 3x the reminder
interval (default 1 day) after the previous email, after which it stops.
New last_notified_at and notification_count columns on signatures and
approval decisions drive the debounce, the widening reminder cadence and
the four-email cap.

Email copy lists each document with its title, type and a deep link to
the employee page. Removed the inline approval-on-publish email, the
SendSigningNotifications service method/mutation/MCP tool, its IAM action,
and the related console UI and n8n operation.

Signed-off-by: Sacha Al Himdani <sacha@probo.com>
This commit is contained in:
Sacha Al Himdani
2026-06-15 09:13:31 +02:00
committed by Sacha Al Himdani
parent c9b74bac4a
commit f462b124e6
33 changed files with 1281 additions and 524 deletions

View File

@@ -298,7 +298,8 @@ INSERT INTO document_version_approval_decisions (
electronic_signature_id,
decided_at,
created_at,
updated_at
updated_at,
notification_count
) VALUES (
@id,
@tenant_id,
@@ -310,7 +311,8 @@ INSERT INTO document_version_approval_decisions (
@electronic_signature_id,
@decided_at,
@created_at,
@updated_at
@updated_at,
@notification_count
)
`
@@ -326,6 +328,7 @@ INSERT INTO document_version_approval_decisions (
"decided_at": d.DecidedAt,
"created_at": d.CreatedAt,
"updated_at": d.UpdatedAt,
"notification_count": 0,
}
_, err := conn.Exec(ctx, q, args)
@@ -367,6 +370,7 @@ func (ds DocumentVersionApprovalDecisions) BulkInsert(
d.DecidedAt,
d.CreatedAt,
d.UpdatedAt,
0,
},
)
}
@@ -386,6 +390,7 @@ func (ds DocumentVersionApprovalDecisions) BulkInsert(
"decided_at",
"created_at",
"updated_at",
"notification_count",
},
pgx.CopyFromRows(rows),
)
@@ -393,6 +398,211 @@ func (ds DocumentVersionApprovalDecisions) BulkInsert(
return err
}
// LoadNextDueGroupForNotification loads every still-PENDING approval decision
// for the next (organization, approver) group that has at least one decision due
// for a notification, so the whole group can be emailed together. A decision is
// due once it is past its scheduled offset (see documentNotificationMaxCount)
// and has not reached the cap. The receiver is left empty when no group is due.
//
// A decision is only ever PENDING while its quorum is pending — resolving a
// quorum either approves all decisions or voids the remaining ones — so there is
// no need to join the quorum table here.
func (d *DocumentVersionApprovalDecisions) LoadNextDueGroupForNotification(
ctx context.Context,
conn pg.Querier,
now time.Time,
debounceBefore time.Time,
reminderInterval time.Duration,
) error {
q := `
WITH next_group AS (
SELECT
organization_id,
approver_id
FROM
document_version_approval_decisions
WHERE
state = @state
AND notification_count < @max_notifications
AND (
(notification_count = 0 AND created_at < @debounce_before)
OR (notification_count > 0 AND last_notified_at < @now::timestamptz - make_interval(secs => @reminder_interval_seconds * notification_count))
)
AND EXISTS (
SELECT 1
FROM document_version_approval_quorums q
JOIN document_versions dv ON dv.id = q.version_id
JOIN documents doc ON doc.id = dv.document_id
WHERE q.id = document_version_approval_decisions.quorum_id
AND doc.deleted_at IS NULL
AND doc.archived_at IS NULL
)
GROUP BY
organization_id,
approver_id
ORDER BY
organization_id,
approver_id
LIMIT 1
)
SELECT
d.id,
d.organization_id,
d.quorum_id,
d.approver_id,
d.state,
d.comment,
d.electronic_signature_id,
d.decided_at,
d.created_at,
d.updated_at
FROM
document_version_approval_decisions d
INNER JOIN next_group g
ON g.organization_id = d.organization_id
AND g.approver_id = d.approver_id
WHERE
d.state = @state
AND d.notification_count < @max_notifications
AND EXISTS (
SELECT 1
FROM document_version_approval_quorums q
JOIN document_versions dv ON dv.id = q.version_id
JOIN documents doc ON doc.id = dv.document_id
WHERE q.id = d.quorum_id
AND doc.deleted_at IS NULL
AND doc.archived_at IS NULL
)
ORDER BY
d.quorum_id
`
args := pgx.StrictNamedArgs{
"state": DocumentVersionApprovalDecisionStatePending,
"max_notifications": documentNotificationMaxCount,
"now": now,
"debounce_before": debounceBefore,
"reminder_interval_seconds": reminderInterval.Seconds(),
}
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query due approval decisions for notification: %w", err)
}
decisions, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[DocumentVersionApprovalDecision])
if err != nil {
return fmt.Errorf("cannot collect due approval decisions for notification: %w", err)
}
*d = decisions
return nil
}
// ClaimForNotification claims the receiver's decisions that are individually
// due for a notification and returns their ids. The conditional update doubles
// as the claim, so concurrent workers never email the same group twice. Callers
// advance the rest of the group with BumpRemainingForNotification in the same
// transaction.
func (d DocumentVersionApprovalDecisions) ClaimForNotification(
ctx context.Context,
conn pg.Tx,
now time.Time,
debounceBefore time.Time,
reminderInterval time.Duration,
) ([]gid.GID, error) {
ids := make([]gid.GID, len(d))
for i, decision := range d {
ids[i] = decision.ID
}
q := `
UPDATE document_version_approval_decisions
SET
notification_count = notification_count + 1,
last_notified_at = @now
WHERE
id = ANY(@ids::text[])
AND state = @state
AND notification_count < @max_notifications
AND (
(notification_count = 0 AND created_at < @debounce_before)
OR (notification_count > 0 AND last_notified_at < @now::timestamptz - make_interval(secs => @reminder_interval_seconds * notification_count))
)
RETURNING id
`
rows, err := conn.Query(ctx, q, pgx.StrictNamedArgs{
"ids": ids,
"state": DocumentVersionApprovalDecisionStatePending,
"max_notifications": documentNotificationMaxCount,
"now": now,
"debounce_before": debounceBefore,
"reminder_interval_seconds": reminderInterval.Seconds(),
})
if err != nil {
return nil, fmt.Errorf("cannot claim due approval decisions for notification: %w", err)
}
claimed, err := pgx.CollectRows(rows, pgx.RowTo[gid.GID])
if err != nil {
return nil, fmt.Errorf("cannot collect claimed approval decisions for notification: %w", err)
}
return claimed, nil
}
// BumpRemainingForNotification advances the notification schedule for the
// still-pending decisions in the group that were not individually claimed, so
// the whole emailed list moves forward together. It must run in the same
// transaction as ClaimForNotification.
func (d DocumentVersionApprovalDecisions) BumpRemainingForNotification(
ctx context.Context,
conn pg.Tx,
claimed []gid.GID,
now time.Time,
) ([]gid.GID, error) {
ids := make([]gid.GID, len(d))
for i, decision := range d {
ids[i] = decision.ID
}
rest := remainingNotificationIDs(ids, claimed)
if len(rest) == 0 {
return nil, nil
}
q := `
UPDATE document_version_approval_decisions
SET
notification_count = notification_count + 1,
last_notified_at = @now
WHERE
id = ANY(@ids::text[])
AND state = @state
AND notification_count < @max_notifications
RETURNING id
`
rows, err := conn.Query(ctx, q, pgx.StrictNamedArgs{
"ids": rest,
"state": DocumentVersionApprovalDecisionStatePending,
"max_notifications": documentNotificationMaxCount,
"now": now,
})
if err != nil {
return nil, fmt.Errorf("cannot bump remaining approval decisions for notification: %w", err)
}
bumped, err := pgx.CollectRows(rows, pgx.RowTo[gid.GID])
if err != nil {
return nil, fmt.Errorf("cannot collect bumped approval decisions for notification: %w", err)
}
return bumped, nil
}
func (d *DocumentVersionApprovalDecision) Update(
ctx context.Context,
conn pg.Tx,