diff --git a/docs/api.md b/docs/api.md index cea73a2..1db6aa0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -31,7 +31,7 @@ The design shows "Email sudah terdaftar" on the sign up screen. That text tells ## Time -The service stores every moment in UTC and keeps an IANA time zone for each business, `Asia/Jakarta` by default. The zone decides the day, the month and the working hours. The moments of the home screen, the running report, the devices and the relay carry the offset of that zone, for example `+07:00`. They are the same instants as in UTC and only the text differs. The other moments of `/v1` (the list of gateways, the list of sessions and the times of a tip) and the moments in the answers under `/device/v1` are written in UTC with `Z`. The times that a gateway sends in its batches are Unix seconds. +The service stores every moment in UTC and keeps an IANA time zone for each business, `Asia/Jakarta` by default. The zone decides the day, the month and the working hours. The moments of the home screen, the running report, the devices, the relay, the list and the claim answer of the gateways and the times of a tip carry the offset of that zone, for example `+07:00`. They are the same instants as in UTC and only the text differs. The moments of the list of sessions and the moments in the answers under `/device/v1` are written in UTC with `Z`. The times that a gateway sends in its batches are Unix seconds. ## Money diff --git a/docs/faq.md b/docs/faq.md index 8cabac6..65a9fea 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -31,7 +31,7 @@ The app is in Indonesian, and the API keeps a few of those words in its fields a **Does a schedule work while the gateway has no internet?** No. The service makes the command at the set time, and a gateway that is away for more than 10 minutes never receives it. -**Why do some moments end in `Z` and others have `+07:00`?** The service stores every moment in UTC. The moments of the home screen, the running report, the devices and the relay are written with the offset of the business zone. The moments of the list of gateways, the list of sessions and the times of a tip are written in UTC, and so are the moments in the answers under `/device/v1`. A gateway sends its own times as Unix seconds. A client that wants the local clock for those converts them with the `timeZone` of `/v1/settings`. +**Why do some moments end in `Z` and others have `+07:00`?** The service stores every moment in UTC. The moments of the home screen, the running report, the devices, the relay, the list and the claim answer of the gateways and the times of a tip are written with the offset of the business zone. The moments of the list of sessions are written in UTC, and so are the moments in the answers under `/device/v1`. A gateway sends its own times as Unix seconds. A client that wants the local clock for those converts them with the `timeZone` of `/v1/settings`. **Why does the verification mail not arrive in a development run?** A development run sends no mail. It writes the message to the log, link included. Production needs the `SMTP_*` settings. See [Operations](operations.md). diff --git a/internal/gateway/enroll.go b/internal/gateway/enroll.go index 8082e02..09cf098 100644 --- a/internal/gateway/enroll.go +++ b/internal/gateway/enroll.go @@ -291,8 +291,8 @@ func (s *Service) Claim(ctx context.Context, businessID, rawCode, rawName string } // the business is locked first and the count is a statement of its own, so two claims at the same time count one after the other - var locked int - if err := tx.QueryRow(ctx, "SELECT 1 FROM businesses WHERE id = $1 FOR UPDATE", businessID).Scan(&locked); err != nil { + var zone string + if err := tx.QueryRow(ctx, "SELECT time_zone FROM businesses WHERE id = $1 FOR UPDATE", businessID).Scan(&zone); err != nil { return Gateway{}, fmt.Errorf("lock the business %w", err) } @@ -345,12 +345,27 @@ func (s *Service) Claim(ctx context.Context, businessID, rawCode, rawName string return Gateway{}, fmt.Errorf("finish the claim %w", err) } + gw.LastSeenAt = gw.LastSeenAt.In(zoneOf(zone)) + return gw, nil } -// List returns the gateways of a business by name +// zoneOf loads the time zone of a business, which the moments of an answer are written in. It is the same instant and only the offset +// in the text changes. A name that cannot be loaded falls back to UTC. +func zoneOf(name string) *time.Location { + loc, err := time.LoadLocation(name) + if err != nil { + return time.UTC + } + + return loc +} + +// List returns the gateways of a business by name, with the time of the last batch in the time zone of the business func (s *Service) List(ctx context.Context, businessID string) ([]Gateway, error) { - rows, err := s.pool.Query(ctx, "SELECT id, name, COALESCE(last_seen_at, created_at), key_revoked_at IS NOT NULL FROM gateways WHERE business_id = $1 ORDER BY lower(name), id", businessID) + rows, err := s.pool.Query(ctx, + `SELECT g.id, g.name, COALESCE(g.last_seen_at, g.created_at), g.key_revoked_at IS NOT NULL, b.time_zone + FROM gateways g JOIN businesses b ON b.id = g.business_id WHERE g.business_id = $1 ORDER BY lower(g.name), g.id`, businessID) if err != nil { return nil, fmt.Errorf("list the gateways %w", err) } @@ -359,11 +374,17 @@ func (s *Service) List(ctx context.Context, businessID string) ([]Gateway, error out := []Gateway{} for rows.Next() { - var g Gateway - if err := rows.Scan(&g.ID, &g.Name, &g.LastSeenAt, &g.KeyRevoked); err != nil { + var ( + g Gateway + zone string + ) + + if err := rows.Scan(&g.ID, &g.Name, &g.LastSeenAt, &g.KeyRevoked, &zone); err != nil { return nil, fmt.Errorf("read a gateway %w", err) } + g.LastSeenAt = g.LastSeenAt.In(zoneOf(zone)) + out = append(out, g) } diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index c963ba8..bd196fa 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -115,6 +115,67 @@ func TestEnrollClaimAndSendReadings(t *testing.T) { } } +func TestTheLastSeenTimeOfAGatewayCarriesTheOffsetOfTheBusinessZone(t *testing.T) { + g := enrolled(t, "budi@example.com", "ESP32-AABBCC", "a") + + lastSeen := func(call func() testutil.Reply) time.Time { + t.Helper() + + r := call() + if r.Status != http.StatusOK && r.Status != http.StatusCreated { + t.Fatalf("answered %d %v", r.Status, r.Body) + } + + text := r.Body["lastSeenAt"] + if items, ok := r.Body["items"].([]any); ok { + text = items[0].(map[string]any)["lastSeenAt"] + } + + parsed, err := time.Parse(time.RFC3339Nano, text.(string)) + if err != nil { + t.Fatalf("the time %v does not parse %v", text, err) + } + + return parsed + } + + list := func() testutil.Reply { return g.e.Call(t, http.MethodGet, "/v1/gateways", "", g.session) } + + got := lastSeen(list) + if _, offset := got.Zone(); offset != 7*3600 { + t.Fatalf("the default zone gave the offset %d seconds, want 25200", offset) + } + + var stored time.Time + if err := g.e.Pool.QueryRow(t.Context(), "SELECT COALESCE(last_seen_at, created_at) FROM gateways WHERE id = $1", g.gateway).Scan(&stored); err != nil { + t.Fatal(err) + } + + if !got.Equal(stored) { + t.Fatalf("the answer is the instant %v and the row holds %v", got, stored) + } + + g.e.Exec(t, "UPDATE businesses SET time_zone = 'Asia/Makassar'") + + if _, offset := lastSeen(list).Zone(); offset != 8*3600 { + t.Fatalf("Makassar gave the offset %d seconds, want 28800", offset) + } + + // the claim answer of a second hub is written in the same zone + _, hash := key("b") + + r := g.e.CallWith(t, http.MethodPost, "/device/v1/enroll", `{"hardwareId":"ESP32-DDEEFF","firmware":"0.1.0","keyHash":"`+hash+`"}`, nil) + code, _ := r.Body["claimCode"].(string) + + claim := func() testutil.Reply { + return g.e.Call(t, http.MethodPost, "/v1/gateways", `{"claimCode":"`+code+`","name":"Hub kedua"}`, g.session) + } + + if _, offset := lastSeen(claim).Zone(); offset != 8*3600 { + t.Fatalf("the claim answer gave the offset %d seconds, want 28800", offset) + } +} + func TestACodeWorksOnceAndOnlyForTheRightFormat(t *testing.T) { e := testutil.New(t) session := e.SignUp(t, "budi@example.com") diff --git a/internal/tips/service.go b/internal/tips/service.go index 51a35e0..dd54176 100644 --- a/internal/tips/service.go +++ b/internal/tips/service.go @@ -590,7 +590,7 @@ func (s *Service) detail(ctx context.Context, businessID, id string) (Detail, er t := f.all() out := Detail{ID: r.id, Title: t.Title, DeviceName: r.deviceName, Status: r.status, SavingPerMonthRp: r.savingRp(p), - TariffIsDefault: p.tariffDefault, WhatToDo: t.WhatToDo, Why: t.Why, HowCalculated: t.How, AppliedAt: r.appliedAt, RejectedAt: r.rejectedAt} + TariffIsDefault: p.tariffDefault, WhatToDo: t.WhatToDo, Why: t.Why, HowCalculated: t.How, AppliedAt: inZone(r.appliedAt, p.loc), RejectedAt: inZone(r.rejectedAt, p.loc)} if r.status == StatusApplied { out.Verification = &Progress{CollectedDays: r.elapsed(p, s.now()), NeededDays: VerifyDays} @@ -604,6 +604,17 @@ func (s *Service) detail(ctx context.Context, businessID, id string) (Detail, er return out, nil } +// inZone writes a moment in the time zone of the business. It is the same instant and only the offset in the text changes. +func inZone(t *time.Time, loc *time.Location) *time.Time { + if t == nil { + return nil + } + + local := t.In(loc) + + return &local +} + var transitions = map[string]struct { from []string to string diff --git a/internal/tips/tips_test.go b/internal/tips/tips_test.go index 2ec4c6c..84031bf 100644 --- a/internal/tips/tips_test.go +++ b/internal/tips/tips_test.go @@ -115,6 +115,15 @@ func TestTheOwnerDecidesAndTheStatesFollowTheRules(t *testing.T) { } } + // the moment of the rejection is written in the zone of the business, in the detail as well as in the answer of the decision + g.e.Exec(t, "UPDATE businesses SET time_zone = 'Asia/Makassar'") + + detail := g.e.Call(t, http.MethodGet, "/v1/recommendations/"+id, "", g.Session) + + if at, _ := detail.Body["rejectedAt"].(string); !strings.HasSuffix(at, "+08:00") { + t.Fatalf("rejectedAt is %v, want the offset +08:00", detail.Body["rejectedAt"]) + } + // a rejected tip is final, and the refresh does not bring it back or change it g.hours(t, 9*24, 8*24+1, 100, 0.1) @@ -152,6 +161,11 @@ func TestAnAppliedTipShowsItsDayAndIsVerifiedAfterFourteenDays(t *testing.T) { t.Fatalf("a new applied tip is %v", r.Body) } + // the moment is written in the zone of the business, which is Asia/Jakarta by default + if at, _ := r.Body["appliedAt"].(string); !strings.HasSuffix(at, "+07:00") { + t.Fatalf("appliedAt is %q, want the offset +07:00", at) + } + // with no production records the check cannot run, so the tip stays applied after the 14 days g.e.Exec(t, "UPDATE tips SET applied_at = now() - interval '15 days'") g.e.Exec(t, "UPDATE businesses SET tips_refreshed_at = NULL") diff --git a/openapi.yaml b/openapi.yaml index 289a1f1..3d02ab7 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -4,7 +4,7 @@ info: version: 0.1.0 summary: The API of the energy audit dashboard for small businesses description: | - The API serves two clients. The web app of a business reads and writes under `/v1`, and the gateway of a business sends its readings under `/device/v1`. Every amount of money is a whole number of rupiah. Every moment is ISO 8601 and the service stores it in UTC. The moments of the home screen, the running report, the devices and the relay are written with the offset of the time zone of the business. The other moments of `/v1` and the moments in the answers under `/device/v1` are written in UTC with `Z`. The times that a gateway sends in its batches are Unix seconds. + The API serves two clients. The web app of a business reads and writes under `/v1`, and the gateway of a business sends its readings under `/device/v1`. Every amount of money is a whole number of rupiah. Every moment is ISO 8601 and the service stores it in UTC. The moments of the home screen, the running report, the devices, the relay, the list and the claim answer of the gateways and the tips are written with the offset of the time zone of the business. The moments of the list of sessions and the moments in the answers under `/device/v1` are written in UTC with `Z`. The times that a gateway sends in its batches are Unix seconds. The paths under `/v1` that the frontend already assumes keep the shapes of `docs/api-assumptions.md` of the frontend repository. Where this file adds to them, the text says so. license: