| 1 | package calendar |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "time" |
| 6 | |
| 7 | "gorm.io/gorm" |
| 8 | ) |
| 9 | |
| 10 | // An exception belongs to the series containing its original occurrence, |
| 11 | // even when someone moved it across the split date. Cancelled exceptions |
| 12 | // move too, so splitting cannot restore a deleted occurrence. |
| 13 | func moveSplitOverrides(tx *gorm.DB, personID int64, master, tail Event, cut time.Time, rung bool) error { |
| 14 | writable := func() *gorm.DB { |
| 15 | return splitWritableEvents(tx, personID, master.CalendarID, rung).Where("series_id = ?", master.ID) |
| 16 | } |
| 17 | var overrides []Event |
| 18 | if err := writable().Find(&overrides).Error; err != nil { |
| 19 | return err |
| 20 | } |
| 21 | loc, err := Zone(master.TZ) |
| 22 | if err != nil { |
| 23 | return err |
| 24 | } |
| 25 | now := time.Now().UTC() |
| 26 | for _, override := range overrides { |
| 27 | original, _, err := ParseLocal(override.RecurrenceIDLocal, loc) |
| 28 | if err != nil { |
| 29 | return fmt.Errorf("calendar: read split occurrence: %w", err) |
| 30 | } |
| 31 | if original.Before(cut) { |
| 32 | continue |
| 33 | } |
| 34 | updates := map[string]any{"series_id": tail.ID, "uid_hash": tail.UIDHash, "uid_sealed": tail.UIDSealed, "sequence": gorm.Expr("sequence + 1"), "updated_at": now} |
| 35 | result := writable().Where("id = ?", override.ID). |
| 36 | Select("series_id", "uid_hash", "uid_sealed", "sequence", "updated_at").Updates(updates) |
| 37 | if result.Error != nil { |
| 38 | return result.Error |
| 39 | } |
| 40 | if result.RowsAffected != 1 { |
| 41 | return ErrNotFound |
| 42 | } |
| 43 | } |
| 44 | return nil |
| 45 | } |
| 46 | |
| 47 | // splitWritableEvents is the events on calendarID that personID may write, |
| 48 | // through the person's grant joined the way every scoped read joins it |
| 49 | // (grantJoin, on the reach the caller read once: team_reach.go). |
| 50 | func splitWritableEvents(tx *gorm.DB, personID, calendarID int64, rung bool) *gorm.DB { |
| 51 | calendars := tx.Table("calendars").Select("calendars.id"). |
| 52 | Joins(grantJoin("calendars.id", rung), personID). |
| 53 | Where("grants.role IN ?", []string{RoleOwner, RoleEditor}) |
| 54 | return tx.Model(&Event{}).Where("calendar_id = ? AND calendar_id IN (?)", calendarID, calendars) |
| 55 | } |
| 56 | |