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

@@ -80,6 +80,31 @@ func (v DocumentType) String() string {
return string(v)
}
func (v DocumentType) Label() string {
switch v {
case DocumentTypeGovernance:
return "Governance"
case DocumentTypePolicy:
return "Policy"
case DocumentTypeProcedure:
return "Procedure"
case DocumentTypePlan:
return "Plan"
case DocumentTypeRegister:
return "Register"
case DocumentTypeRecord:
return "Record"
case DocumentTypeReport:
return "Report"
case DocumentTypeTemplate:
return "Template"
case DocumentTypeStatementOfApplicability:
return "Statement of Applicability"
default:
return "Document"
}
}
func (v DocumentType) MarshalText() ([]byte, error) {
return []byte(v.String()), nil
}

View File

@@ -152,6 +152,58 @@ WHERE
return nil
}
func (dv *DocumentVersions) LoadByIDs(
ctx context.Context,
conn pg.Querier,
scope Scoper,
documentVersionIDs []gid.GID,
) error {
q := `
SELECT
id,
organization_id,
document_id,
title,
major,
minor,
classification,
document_type,
content,
changelog,
status,
orientation,
file_id,
pdf_attempt_count,
published_at,
created_at,
updated_at
FROM
document_versions
WHERE
%s
AND id = ANY(@document_version_ids)
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"document_version_ids": documentVersionIDs}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query document versions: %w", err)
}
documentVersions, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[DocumentVersion])
if err != nil {
return fmt.Errorf("cannot collect document versions: %w", err)
}
*dv = documentVersions
return nil
}
func (dv DocumentVersion) CursorKey(orderBy DocumentVersionOrderField) page.CursorKey {
switch orderBy {
case DocumentVersionOrderFieldCreatedAt:

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,

View File

@@ -135,6 +135,47 @@ WHERE
return nil
}
func (q *DocumentVersionApprovalQuorums) LoadByIDs(
ctx context.Context,
conn pg.Querier,
scope Scoper,
quorumIDs []gid.GID,
) error {
query := `
SELECT
id,
organization_id,
version_id,
status,
created_at,
updated_at
FROM
document_version_approval_quorums
WHERE
%s
AND id = ANY(@quorum_ids)
`
query = fmt.Sprintf(query, scope.SQLFragment())
args := pgx.StrictNamedArgs{"quorum_ids": quorumIDs}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, query, args)
if err != nil {
return fmt.Errorf("cannot query approval quorums: %w", err)
}
quorums, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[DocumentVersionApprovalQuorum])
if err != nil {
return fmt.Errorf("cannot collect approval quorums: %w", err)
}
*q = quorums
return nil
}
func (q *DocumentVersionApprovalQuorum) LoadLastByDocumentVersionID(
ctx context.Context,
conn pg.Querier,

View File

@@ -297,7 +297,8 @@ INSERT INTO document_version_signatures (
requested_at,
electronic_signature_id,
created_at,
updated_at
updated_at,
notification_count
) VALUES (
@id,
@tenant_id,
@@ -309,7 +310,8 @@ INSERT INTO document_version_signatures (
@requested_at,
@electronic_signature_id,
@created_at,
@updated_at
@updated_at,
@notification_count
)
`
@@ -325,6 +327,7 @@ INSERT INTO document_version_signatures (
"electronic_signature_id": pvs.ElectronicSignatureID,
"created_at": pvs.CreatedAt,
"updated_at": pvs.UpdatedAt,
"notification_count": 0,
}
_, err := conn.Exec(ctx, q, args)
@@ -399,6 +402,230 @@ WHERE
return nil
}
// documentNotificationMaxCount caps how many emails a signature/approval
// request gets: the first notice plus three reminders. A request is due for its
// next email once it is past its scheduled offset — the first email after the
// debounce delay, then reminders at 1x, 2x and 3x the reminder interval after
// the previous email — and stops once it reaches this cap.
const documentNotificationMaxCount = 4
func remainingNotificationIDs(all []gid.GID, claimed []gid.GID) []gid.GID {
claimedSet := make(map[gid.GID]struct{}, len(claimed))
for _, id := range claimed {
claimedSet[id] = struct{}{}
}
rest := make([]gid.GID, 0, len(all))
for _, id := range all {
if _, ok := claimedSet[id]; ok {
continue
}
rest = append(rest, id)
}
return rest
}
// LoadNextDueGroupForNotification loads every still-REQUESTED signature for the
// next (organization, signatory) group that has at least one request due for a
// notification, so the whole group can be emailed together. A request 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.
func (pvss *DocumentVersionSignatures) 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,
signed_by_profile_id
FROM
document_version_signatures
WHERE
state = @state
AND notification_count < @max_notifications
AND (
(notification_count = 0 AND requested_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_versions dv
JOIN documents doc ON doc.id = dv.document_id
WHERE dv.id = document_version_signatures.document_version_id
AND doc.deleted_at IS NULL
AND doc.archived_at IS NULL
)
GROUP BY
organization_id,
signed_by_profile_id
ORDER BY
organization_id,
signed_by_profile_id
LIMIT 1
)
SELECT
s.id,
s.organization_id,
s.document_version_id,
s.state,
s.signed_by_profile_id,
s.signed_at,
s.requested_at,
s.electronic_signature_id,
s.created_at,
s.updated_at
FROM
document_version_signatures s
INNER JOIN next_group g
ON g.organization_id = s.organization_id
AND g.signed_by_profile_id = s.signed_by_profile_id
WHERE
s.state = @state
AND s.notification_count < @max_notifications
AND EXISTS (
SELECT 1
FROM document_versions dv
JOIN documents doc ON doc.id = dv.document_id
WHERE dv.id = s.document_version_id
AND doc.deleted_at IS NULL
AND doc.archived_at IS NULL
)
ORDER BY
s.document_version_id
`
args := pgx.StrictNamedArgs{
"state": DocumentVersionSignatureStateRequested,
"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 signatures for notification: %w", err)
}
signatures, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[DocumentVersionSignature])
if err != nil {
return fmt.Errorf("cannot collect due signatures for notification: %w", err)
}
*pvss = signatures
return nil
}
// ClaimForNotification claims the receiver's signatures 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 (pvss DocumentVersionSignatures) ClaimForNotification(
ctx context.Context,
conn pg.Tx,
now time.Time,
debounceBefore time.Time,
reminderInterval time.Duration,
) ([]gid.GID, error) {
ids := make([]gid.GID, len(pvss))
for i, signature := range pvss {
ids[i] = signature.ID
}
q := `
UPDATE document_version_signatures
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 requested_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": DocumentVersionSignatureStateRequested,
"max_notifications": documentNotificationMaxCount,
"now": now,
"debounce_before": debounceBefore,
"reminder_interval_seconds": reminderInterval.Seconds(),
})
if err != nil {
return nil, fmt.Errorf("cannot claim due signatures for notification: %w", err)
}
claimed, err := pgx.CollectRows(rows, pgx.RowTo[gid.GID])
if err != nil {
return nil, fmt.Errorf("cannot collect claimed signatures for notification: %w", err)
}
return claimed, nil
}
// BumpRemainingForNotification advances the notification schedule for the
// still-pending signatures 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 (pvss DocumentVersionSignatures) BumpRemainingForNotification(
ctx context.Context,
conn pg.Tx,
claimed []gid.GID,
now time.Time,
) ([]gid.GID, error) {
ids := make([]gid.GID, len(pvss))
for i, signature := range pvss {
ids[i] = signature.ID
}
rest := remainingNotificationIDs(ids, claimed)
if len(rest) == 0 {
return nil, nil
}
q := `
UPDATE document_version_signatures
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": DocumentVersionSignatureStateRequested,
"max_notifications": documentNotificationMaxCount,
"now": now,
})
if err != nil {
return nil, fmt.Errorf("cannot bump remaining signatures for notification: %w", err)
}
bumped, err := pgx.CollectRows(rows, pgx.RowTo[gid.GID])
if err != nil {
return nil, fmt.Errorf("cannot collect bumped signatures for notification: %w", err)
}
return bumped, nil
}
func (pvs *DocumentVersionSignature) Update(
ctx context.Context,
conn pg.Tx,

View File

@@ -838,82 +838,6 @@ WHERE
return count, nil
}
func (p *MembershipProfiles) LoadAwaitingSigning(
ctx context.Context,
conn pg.Querier,
scope Scoper,
) error {
q := `
WITH signatories AS (
SELECT
signed_by_profile_id
FROM
document_version_signatures
WHERE
%s
AND state = 'REQUESTED'
GROUP BY
signed_by_profile_id
)
SELECT
p.id,
p.identity_id,
p.organization_id,
p.kind,
p.full_name,
i.email_address,
p.source,
p.state,
p.additional_email_addresses,
p.position,
p.contract_start_date,
p.contract_end_date,
'' AS organization_name,
p.user_name,
p.external_id,
p.nickname,
p.locale,
p.timezone,
p.profile_url,
p.preferred_language,
p.given_name,
p.family_name,
p.formatted_name,
p.middle_name,
p.honorific_prefix,
p.honorific_suffix,
p.employee_number,
p.department,
p.cost_center,
p.enterprise_organization,
p.division,
p.manager_value,
p.created_at,
p.updated_at
FROM
iam_membership_profiles p
INNER JOIN identities i
ON i.id = p.identity_id
INNER JOIN signatories ON p.id = signatories.signed_by_profile_id
`
q = fmt.Sprintf(q, scope.SQLFragment())
rows, err := conn.Query(ctx, q, scope.SQLArguments())
if err != nil {
return fmt.Errorf("cannot query profiles: %w", err)
}
profiles, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[MembershipProfile])
if err != nil {
return fmt.Errorf("cannot collect profiles: %w", err)
}
*p = profiles
return nil
}
func (p *MembershipProfiles) CountByIdentityID(
ctx context.Context,
conn pg.Querier,

View File

@@ -0,0 +1,31 @@
-- Copyright (c) 2026 Probo Inc <hello@probo.com>.
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-- PERFORMANCE OF THIS SOFTWARE.
ALTER TABLE document_version_signatures
ADD COLUMN last_notified_at TIMESTAMPTZ;
ALTER TABLE document_version_signatures
ADD COLUMN notification_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE document_version_signatures
ALTER COLUMN notification_count DROP DEFAULT;
ALTER TABLE document_version_approval_decisions
ADD COLUMN last_notified_at TIMESTAMPTZ;
ALTER TABLE document_version_approval_decisions
ADD COLUMN notification_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE document_version_approval_decisions
ALTER COLUMN notification_count DROP DEFAULT;