Skip to content
Draft
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
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ AZURE_EMAIL_SENDER="noreply@polinetwork.org"
# Optional. Bank details for the soci's association fee. Until both are set, no fee year is opened.
# SOCI_IBAN=""
# SOCI_BENEFICIARI="PoliNetwork APS"
SOCI_AUTO_LAPSE=false

# Optional. PoliNetwork IdP (see "Authentication" in README.md).
# Set IDP_PUBLIC_URL and OAUTH_BACKEND_RESOURCE_URI to verify IdP access tokens.
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,22 @@ Signatures are checked against the CIE certification authorities of the Minister
catalog entries. Selected FAQs/categories must be replaced in Freshman before deleting them from the catalog.
The development seed also initializes the card slots and selections; `--force` clears those selections before
replacing the sample FAQ catalog.

### Membership lifecycle

`soci.members.end` and `restore` require `admin:access` and `soci:write`; ending keeps the Microsoft 365 account pending
deletion. `soci.accounts.pendingDeletion` requires `soci:read`, and `accounts.delete` requires `soci:delete` plus
`admin:access`. Deletion accepts one object ID and preserves the Libro Soci, numbers, fees and account snapshot.

`SOCI_AUTO_LAPSE` defaults to `false`. Only after the register and payments have been reconciled should it be enabled.
The Rome daily run ends active records with a registered Due fee whose 31 December deadline has passed. Uploaded,
Paid and Exempt fees and missing fee rows are protected. It evaluates the most recent 31 December deadline, including
late rejections after September; unrelated older fee years do not trigger a lapse. End date, history and the Italian
lapse email are saved together; a directory failure leaves
the record active for a later retry. Fee mutations and lifecycle changes share the single-instance member-write lock.

`soci.lapse.preview` requires `soci:read` and is read-only even when automatic lapse is disabled. It reports the
Due fee for the most recent renewal deadline for each active record. During December it evaluates 1 January, for the
register's advance warning;
otherwise it evaluates today. The response includes the configured switch and evaluation date. No missing debt is
inferred from an absent record or fee.
6 changes: 6 additions & 0 deletions src/cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export function cron() {
})
// Opens the fee year, sends the December reminders and the birthday emails. Idempotent, and a missed day is caught up the next one.
new Cron("0 0 8 * * *", { timezone: "Europe/Rome" }, async () => {
try {
const { soci } = await import("./soci")
await soci.runLapse()
} catch (err) {
logger.error(err, "[CRON] Soci automatic lapse")
}
try {
const { soci } = await import("./soci")
await soci.runDaily()
Expand Down
Binary file added src/emails/assets/headers/fee-lapsed.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/emails/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export const EMAIL_HEADERS = {
"fee-reminder": "Promemoria quota associativa",
"fee-confirmed": "Quota pagata",
"fee-rejected": "Ricevuta non accettata",
"fee-lapsed": "Status di socio terminato",
welcome: "Benvenuto in PoliNetwork APS",
"member-number-changed": "Il tuo numero socio è cambiato",
"signature-request": "È richiesta la tua firma",
Expand Down
2 changes: 2 additions & 0 deletions src/emails/mailer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { renderEmail } from "./render"
import type { SecretSantaEmailRequest } from "./secret-santa-routes"
import BirthdayEmail, { birthdaySubject } from "./templates/birthday"
import FeeConfirmedEmail, { feeConfirmedSubject } from "./templates/fee-confirmed"
import FeeLapsedEmail, { feeLapsedSubject } from "./templates/fee-lapsed"
import FeeOpeningEmail, { feeOpeningSubject } from "./templates/fee-opening"
import FeeRejectedEmail, { feeRejectedSubject } from "./templates/fee-rejected"
import FeeReminderEmail, { feeReminderSubject } from "./templates/fee-reminder"
Expand Down Expand Up @@ -179,6 +180,7 @@ const FEE_EMAILS = {
reminder: { subject: feeReminderSubject, Template: FeeReminderEmail },
confirmed: { subject: feeConfirmedSubject, Template: FeeConfirmedEmail },
rejected: { subject: feeRejectedSubject, Template: FeeRejectedEmail },
lapsed: { subject: feeLapsedSubject, Template: FeeLapsedEmail },
} satisfies Record<FeeMailKind, unknown>

/** Soci's outbox: throws on failure, and gives each email a stable Message-ID from its idempotency key. */
Expand Down
24 changes: 24 additions & 0 deletions src/emails/templates/fee-lapsed.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { FeeMailData } from "@/soci/types"
import { MailText as Text } from "../components/email-layout"
import { FeeLayout } from "../components/fee-layout"
import { FEE_PREVIEW } from "../components/fee-payment"
import type { EmailTemplate } from "../types"

export const feeLapsedSubject = (data: FeeMailData) => `Fine dello status di socio — quota ${data.yearLabel}`

const FeeLapsedEmail: EmailTemplate<FeeMailData> = (data) => (
<FeeLayout kind="fee-lapsed" name={data.name} preview={`Il tuo status di socio è terminato il ${data.deadline}`}>
<Text>
la quota associativa {data.yearLabel} non risulta pagata entro il {data.deadline}. Il tuo status di socio è quindi
terminato con questa data, come previsto dal Regolamento Interno.
</Text>
<Text>
L’account è stato rimosso dal gruppo Soci ed è in attesa di cancellazione. Se ritieni che ci sia un errore,
contatta il Consiglio Direttivo a direttivo@polinetwork.org.
</Text>
<Text>Grazie per aver fatto parte di PoliNetwork.</Text>
</FeeLayout>
)

FeeLapsedEmail.PreviewProps = FEE_PREVIEW
export default FeeLapsedEmail
4 changes: 4 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export const env = createEnv({
.pipe(z.string().regex(/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/, "an IBAN"))
.optional(),
SOCI_BENEFICIARI: z.string().trim().min(1).optional(),
SOCI_AUTO_LAPSE: z
.enum(["true", "false"])
.default("false")
.transform((v) => v === "true"),
/** Accept signing certificates not issued by the CIE CAs, e.g. the agent's development key. */
ESIGN_ALLOW_TEST_CERTIFICATES: z
.enum(["true", "false"])
Expand Down
34 changes: 34 additions & 0 deletions src/soci/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,27 @@ export const sociListSchema = z.object({
})
export type SociList = z.infer<typeof sociListSchema>

export const lapsePreviewSchema = z.object({
enabled: z.boolean(),
/** Today, or 1 January during December's advance warning. */
evaluatedOn: z.string(),
members: z.array(
z.object({
number: memberNumberSchema,
firstName: z.string(),
lastName: z.string(),
alias: z.string().nullable(),
mailbox: z.string(),
year: z.number(),
endedOn: z.string(),
})
),
})
export type LapsePreview = z.infer<typeof lapsePreviewSchema>

export const deleteAccountInputSchema = z.object({ entraObjectId: z.string().min(1).max(128) })
export type DeleteAccountInput = z.output<typeof deleteAccountInputSchema>

export const activitySchema = z.object({ actor: z.string(), text: z.string(), at: z.string() })
export type SocioActivity = z.infer<typeof activitySchema>

Expand Down Expand Up @@ -245,6 +266,19 @@ export const updateInputSchema = z.object({
})
export type UpdateInput = z.output<typeof updateInputSchema>

/** Ends membership immediately; `endedOn` is the date recorded in the Libro Soci. */
export const endInputSchema = z.object({
number: memberNumberSchema,
endedOn: dateSchema,
endReason: z.enum(["resigned", "expelled", "deceased", "other"]),
endNote: optional(z.string().trim().max(500)),
})
export type EndInput = z.output<typeof endInputSchema>

/** Corrects a mistaken end while the Microsoft 365 account still exists. */
export const restoreInputSchema = z.object({ number: memberNumberSchema, reason: text(500) })
export type RestoreInput = z.output<typeof restoreInputSchema>

export const setNumberInputSchema = z.object({
number: memberNumberSchema,
newNumber: memberNumberSchema,
Expand Down
1 change: 1 addition & 0 deletions src/soci/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export const soci = createSociService({
writes: { serialize: serializeMemberWrite, numberHolder, currentMember, rememberNumber },
mail: { welcome: sendWelcomeEmail, numberChanged: sendMemberNumberChangedEmail },
logger,
autoLapse: env.SOCI_AUTO_LAPSE,
fees: {
bank: env.SOCI_IBAN && env.SOCI_BENEFICIARI ? { iban: env.SOCI_IBAN, beneficiary: env.SOCI_BENEFICIARI } : null,
myAreaUrl: `${env.ESIGN_DASHBOARD_URL.replace(/\/$/, "")}/dashboard/account/me`,
Expand Down
10 changes: 10 additions & 0 deletions src/soci/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function createSociRouter(soci: SociService) {
})
const read = direttivo("soci:read")
const write = direttivo("soci:write")
const remove = direttivo("soci:delete")
const me = policy(dashboard("people:self")).use(({ ctx, next }) => {
if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN", message: "Only for signed-in soci" })
const entraObjectId = ctx.access?.current()?.bySub(ctx.actor.sub)?.entraObjectId ?? null
Expand Down Expand Up @@ -59,11 +60,20 @@ export function createSociRouter(soci: SociService) {
.output(C.numberInputSchema)
.mutation(({ ctx, input }) => soci.register(ctx.sub, input)),
update: write.input(C.updateInputSchema).mutation(({ ctx, input }) => soci.update(ctx.sub, input)),
end: write.input(C.endInputSchema).mutation(({ ctx, input }) => soci.end(ctx.sub, input)),
restore: write.input(C.restoreInputSchema).mutation(({ ctx, input }) => soci.restore(ctx.sub, input)),
setNumber: write
.input(C.setNumberInputSchema)
.output(C.setNumberResultSchema)
.mutation(({ ctx, input }) => soci.setNumber(ctx.sub, input)),
}),
lapse: createTRPCRouter({
preview: read.output(C.lapsePreviewSchema).query(() => soci.lapsePreview()),
}),
accounts: createTRPCRouter({
pendingDeletion: read.output(C.socioRowSchema.array()).query(() => soci.pendingDeletion()),
delete: remove.input(C.deleteAccountInputSchema).mutation(({ ctx, input }) => soci.deleteAccount(ctx.sub, input)),
}),
fees: createTRPCRouter({
list: read
.input(C.feesListInputSchema)
Expand Down
Loading