| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
| 7 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 8 | "gorm.io/gorm" |
| 9 | ) |
| 10 | |
| 11 | // orderedItems retains server-owned sort keys without adding them to API projections. |
| 12 | type orderedItems struct { |
| 13 | Values any |
| 14 | Positions map[string]listPosition |
| 15 | } |
| 16 | type listPosition struct { |
| 17 | At time.Time |
| 18 | ID string |
| 19 | } |
| 20 | |
| 21 | func (p listPosition) before(q listPosition) bool { |
| 22 | if !p.At.Equal(q.At) { |
| 23 | return p.At.After(q.At) |
| 24 | } |
| 25 | return p.ID < q.ID |
| 26 | } |
| 27 | |
| 28 | // Resource audit times include edits as well as creation. IDs break timestamp |
| 29 | // ties; resources predating audit history sort last in a deterministic order. |
| 30 | func (s *Reader) order(ctx context.Context, a kernel.Actor, values any, resources map[string]string) (orderedItems, error) { |
| 31 | out := orderedItems{Values: values, Positions: map[string]listPosition{}} |
| 32 | ids := make([]string, 0, len(resources)) |
| 33 | for id, resource := range resources { |
| 34 | ids = append(ids, resource) |
| 35 | out.Positions[id] = listPosition{ID: id} |
| 36 | } |
| 37 | err := s.ReadTeam(ctx, a, func(tx *gorm.DB, _ Team) error { |
| 38 | var rows []struct { |
| 39 | RecordID string |
| 40 | At time.Time |
| 41 | } |
| 42 | if err := tx.Table("audit_events").Select("record_id,at").Where("record_id IN ?", ids).Order("at").Find(&rows).Error; err != nil { |
| 43 | return err |
| 44 | } |
| 45 | times := map[string]time.Time{} |
| 46 | for _, row := range rows { |
| 47 | if row.At.After(times[row.RecordID]) { |
| 48 | times[row.RecordID] = row.At.UTC() |
| 49 | } |
| 50 | } |
| 51 | for id, resource := range resources { |
| 52 | out.Positions[id] = listPosition{At: times[resource], ID: id} |
| 53 | } |
| 54 | return nil |
| 55 | }) |
| 56 | return out, err |
| 57 | } |
| 58 | |