package notify import ( "encoding/json" "fmt" "strings" "time" "gitea.dooplex.hu/admin/felhom-hub/internal/i18n" "gitea.dooplex.hu/admin/felhom-hub/internal/store" ) // householdReceiptEvents (D84, `09` §3 decision 309) are mails that tell the household about its OWN press of a button // whose effect comes later and cannot be undone after it. One type today: `offsite_end_scheduled` — the household // pressed „delete backup data” (or „delete in 30 days”), and the mail names the app, the day from which the off-site // copies are deleted, how to take it back, and what to do if somebody else pressed it. The reviewer's reason, // accepted by the operator: the page alone does not warn a household whose login someone else uses. // // THE NOTICE LOCK (`09` §3 decision 315; `07-backup-architecture.md` §8.2f): the mail is a CONDITION of the deletion, // so it is not sent from the box's event (an event is lost when the hub is away for nine seconds — R-1361 — and a // failed send was never tried again). The hub sends it from its own state: api.endNotices calls SendEndNotice for // every app its record (store.offsite_end_notices) says is named in a report and not told, at every report, until the // mail service accepts it; only then does the record say „told”, and only 30 days after that does the hub agree. // // A receipt bypasses the household's group switches (whoever holds the login could switch a group off first), so it // is built so that a box can do nothing else with it: // - THE HUB WRITES IT. Subject and body come only from the hub's own bundle, with an app name the hub checked // (the shape of an app name, not reserved) and a day the hub computed from its own clock. Nothing of the box's. // - AT MOST receiptsPerDay PER HOUSEHOLD IN 24 HOURS, counted in the hub's own sent log (it survives a restart). // The limit DELAYS a notice — the record stays „not told” and the next report tries again — it never drops one. // - to the household's own notification address; never to the operator. // // A household with no address, or a blocked one, gets no mail: the caller then tells the operator in its place // (`offsite_end_notice_operator`), and sends the household's mail when an address appears. Pinned by TestNotice_*. var householdReceiptEvents = map[string]bool{ "offsite_end_scheduled": true, } // EndNoticeEvent is the type the household's notice is logged and counted under. const EndNoticeEvent = "offsite_end_scheduled" // receiptsPerDay is the most receipts ONE household is mailed in 24 hours (review of 2026-11-15). const receiptsPerDay = 5 // EndNoticeOutcome is what one try of the household's notice came to. Only EndNoticeSent tells the household. type EndNoticeOutcome string const ( EndNoticeSent EndNoticeOutcome = "sent" EndNoticeNoAddress EndNoticeOutcome = "no-address" // no notification address, or the household is blocked EndNoticeLimit EndNoticeOutcome = "limit" // the household's daily limit: later EndNoticeHeld EndNoticeOutcome = "held" // the MAIL-HOLD marker EndNoticeFailed EndNoticeOutcome = "failed" // the mail service did not accept it, or is not configured ) // receiptDate writes a day in the household's date form (the controller's i18n.FormatDate), in Budapest time. func receiptDate(lang string, t time.Time) string { if budapest != nil { t = t.In(budapest) } if i18n.Normalize(lang) == "en" { return t.Format("2006-01-02") } return t.Format("2006. 01. 02.") } // FormatReceiptEmail is the receipt's whole text — the hub's own words, a checked app name and the hub's own day. // The subject names the deletion and its day (`09` §3 decision 316); the body is the household mail frame with the // hub's sentence as the message line and the „if you did not ask for this” line after it (FormatCustomerEmail). func FormatReceiptEmail(lang, customerID, eventType, severity, app string, ends time.Time) (string, string) { b := i18n.Shared() lang = i18n.Normalize(lang) day := receiptDate(lang, ends) sentence := b.Msgf(lang, "mail.receipt."+eventType, app, day) // The details the frame reads (the app for the headline) are rebuilt from the CHECKED value. det, _ := json.Marshal(map[string]string{"stack_name": app}) _, body := FormatCustomerEmail(lang, customerID, eventType, severity, sentence, "", string(det)) return b.Msgf(lang, "mail.receipt."+eventType+".subject", app, day), body } // MailHeld reports whether the hub-wide mail hold is on (no mail of any kind goes out). func (d *Dispatcher) MailHeld() bool { return d.mailHold.Held() } // SendEndNotice tries ONCE to mail the household that the off-site copies of `app` are deleted from the day `ends` // (the hub's own day: the caller passes its clock + 30 days). It returns what the try came to and, when nobody was // told, the hub's own words for why. It keeps no state: the caller's record decides whether there is a next try. // app must have passed store.ValidPresenceApp; a name that has not is refused here again. func (d *Dispatcher) SendEndNotice(customerID, app string, ends time.Time) (EndNoticeOutcome, string) { if !store.ValidPresenceApp(app) || store.ReservedPresenceApp(app) { return EndNoticeFailed, "not an app name" } if d.resendAPIKey == "" { return EndNoticeFailed, "the hub has no mail service configured" } if d.store.IsCustomerBlocked(customerID) { return EndNoticeNoAddress, "the household is blocked" } prefs, err := d.store.GetNotificationPrefs(customerID) if err != nil { return EndNoticeFailed, "the household's notification address could not be read" } if prefs == nil || strings.TrimSpace(prefs.Email) == "" { return EndNoticeNoAddress, "the household has no notification address" } now := time.Now() sentToday, cerr := d.store.CountCustomerSentSince(customerID, EndNoticeEvent, now.Add(-24*time.Hour)) if cerr != nil { // A log that cannot be read is not „nothing sent”: no receipt goes, and the notice stays to be tried again. return EndNoticeLimit, "the hub's sent log could not be read" } if sentToday >= receiptsPerDay { return EndNoticeLimit, fmt.Sprintf("the household already got %d of these notices in the last 24 hours (the daily limit) — this one goes later", receiptsPerDay) } subject, body := FormatReceiptEmail(d.store.CustomerLanguage(customerID), customerID, EndNoticeEvent, "info", app, ends) logMsg := EndNoticeEvent + " " + app if err := d.deliver("customer receipt "+EndNoticeEvent, customerID, strings.TrimSpace(prefs.Email), subject, body, nil); isHeld(err) { d.store.LogNotification(customerID, EndNoticeEvent, "info", logMsg, "held", "MAIL-HOLD marker present — not sent; the notice stays to be sent", "customer") return EndNoticeHeld, "the hub is not sending mail (the MAIL-HOLD marker is present)" } else if err != nil { d.logger.Printf("[ERROR] Notice %s failed for %s/%s: %v — it stays to be sent", EndNoticeEvent, customerID, app, err) d.store.LogNotification(customerID, EndNoticeEvent, "info", logMsg, "failed", err.Error(), "customer") return EndNoticeFailed, "the mail service did not accept the mail" } d.logger.Printf("[INFO] Notice %s sent for %s/%s", EndNoticeEvent, customerID, app) // never the address (R-922) if lerr := d.store.LogNotification(customerID, EndNoticeEvent, "info", logMsg, "sent", "", "customer"); lerr != nil { d.logger.Printf("[WARN] Notice %s for %s/%s was sent, but the sent log could not be written: %v", EndNoticeEvent, customerID, app, lerr) } return EndNoticeSent, "" } // SendOperatorNow mails the operator ONE hub-made event and returns only when the mail service has answered: nil // means it accepted the mail. For an operator mail whose DELIVERY is a condition of something else (the notice that // starts an app's 30 days when the household has no address) — the ordinary operator path (processOperator) answers // at once and retries in the background, so its caller cannot know. No cooldown: the caller's own record tells each // thing once. The event type must be operator-only. func (d *Dispatcher) SendOperatorNow(customerID, eventType, severity, message, detailsJSON string) error { if !operatorOnlyEvents[eventType] { return fmt.Errorf("notify: %s is not an operator-only type", eventType) } if d.resendAPIKey == "" { return fmt.Errorf("the hub has no mail service configured") } if !d.operatorOn || d.operatorEmail == "" { return fmt.Errorf("the operator's mail is switched off") } subject, body := FormatOperatorEmail(customerID, eventType, severity, message, detailsJSON) if err := d.deliver("operator mail "+eventType, "operator", d.operatorEmail, subject, body, priorityHeaders(severity)); isHeld(err) { d.store.LogNotification(customerID, eventType, severity, message, "held", "MAIL-HOLD marker present — not sent", "operator") return err } else if err != nil { d.logger.Printf("[ERROR] Operator email failed for %s/%s: %v", customerID, eventType, err) d.store.LogNotification(customerID, eventType, severity, message, "failed", err.Error(), "operator") return err } d.logger.Printf("[INFO] Operator email sent for %s/%s", customerID, eventType) d.store.LogNotification(customerID, eventType, severity, message, "sent", "", "operator") return nil } // SetSendFnForTest replaces the function that hands a mail to the mail service. TEST-ONLY: it lets a test in another // package (api.endNotices) see every mail and fail a send, with no call to the real service. func (d *Dispatcher) SetSendFnForTest(fn func(to, subject, body string, headers map[string]string) error) { d.sendEmailFn = fn }