Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

fix: dates (hopefully) (#1708)

Mattb49ba768aeb0
diff --git a/backend/internal/data/repo/date_roundtrip_tz_test.go b/backend/internal/data/repo/date_roundtrip_tz_test.go
new file mode 100644
index 00000000..85543ae6
--- /dev/null
+++ b/backend/internal/data/repo/date_roundtrip_tz_test.go
@@ -0,0 +1,145 @@
+package repo
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/types"
+)
+
+// unmarshalDate parses a date the way the API does when the browser PUTs it.
+func unmarshalDate(t *testing.T, yyyymmdd string) types.Date {
+ t.Helper()
+
+ var body struct {
+ Date types.Date `json:"date"`
+ }
+ require.NoError(t, json.Unmarshal([]byte(`{"date":"`+yyyymmdd+`"}`), &body))
+ return body.Date
+}
+
+// Dates entered in the UI must survive the round-trip unchanged, and must keep
+// surviving it when the item is saved again without touching the picker. Run
+// under TZ=America/Chicago (or any zone west of Greenwich) to cover the
+// timezone shift that made purchase dates drift a day earlier per save.
+func TestEntityDatesRoundTripUnchanged(t *testing.T) {
+ ctx := context.Background()
+ itemET := useItemEntityType(t)
+
+ cf := containerFactory()
+ cf.EntityTypeID = useContainerEntityType(t).ID
+ container, err := tRepos.Entities.Create(ctx, tGroup.ID, cf)
+ require.NoError(t, err)
+
+ ef := entityFactory()
+ ef.EntityTypeID = itemET.ID
+ ef.ParentID = container.ID
+ e, err := tRepos.Entities.Create(ctx, tGroup.ID, ef)
+ require.NoError(t, err)
+
+ const (
+ purchase = "2026-08-27"
+ warranty = "2030-01-01"
+ sold = "2026-12-31"
+ )
+
+ upd := EntityUpdate{
+ ID: e.ID,
+ Name: e.Name,
+ EntityTypeID: itemET.ID,
+ ParentID: container.ID,
+ Quantity: 1,
+ PurchaseDate: unmarshalDate(t, purchase),
+ WarrantyExpires: unmarshalDate(t, warranty),
+ SoldDate: unmarshalDate(t, sold),
+ }
+
+ // Three saves: the first is the user's edit, the next two echo back
+ // exactly what the API served, as the edit form does for untouched fields.
+ for save := 1; save <= 3; save++ {
+ out, err := tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, upd)
+ require.NoError(t, err)
+
+ require.Equal(t, purchase, out.PurchaseDate.String(), "purchase date after save %d", save)
+ require.Equal(t, warranty, out.WarrantyExpires.String(), "warranty expiry after save %d", save)
+ require.Equal(t, sold, out.SoldDate.String(), "sold date after save %d", save)
+
+ upd.PurchaseDate = out.PurchaseDate
+ upd.WarrantyExpires = out.WarrantyExpires
+ upd.SoldDate = out.SoldDate
+ }
+
+ got, err := tRepos.Entities.GetOne(ctx, e.ID)
+ require.NoError(t, err)
+ require.Equal(t, purchase, got.PurchaseDate.String())
+ require.Equal(t, warranty, got.WarrantyExpires.String())
+ require.Equal(t, sold, got.SoldDate.String())
+}
+
+// ZeroOutTimeFields rewrites every date column in the group. It must not move
+// the day while it strips the time.
+func TestZeroOutTimeFieldsKeepsTheDay(t *testing.T) {
+ ctx := context.Background()
+ itemET := useItemEntityType(t)
+
+ cf := containerFactory()
+ cf.EntityTypeID = useContainerEntityType(t).ID
+ container, err := tRepos.Entities.Create(ctx, tGroup.ID, cf)
+ require.NoError(t, err)
+
+ ef := entityFactory()
+ ef.EntityTypeID = itemET.ID
+ ef.ParentID = container.ID
+ e, err := tRepos.Entities.Create(ctx, tGroup.ID, ef)
+ require.NoError(t, err)
+
+ const purchase = "2026-08-27"
+
+ _, err = tRepos.Entities.UpdateByGroup(ctx, tGroup.ID, EntityUpdate{
+ ID: e.ID,
+ Name: e.Name,
+ EntityTypeID: itemET.ID,
+ ParentID: container.ID,
+ Quantity: 1,
+ PurchaseDate: unmarshalDate(t, purchase),
+ })
+ require.NoError(t, err)
+
+ _, err = tRepos.Entities.ZeroOutTimeFields(ctx, tGroup.ID)
+ require.NoError(t, err)
+
+ got, err := tRepos.Entities.GetOne(ctx, e.ID)
+ require.NoError(t, err)
+ require.Equal(t, purchase, got.PurchaseDate.String())
+}
+
+// Maintenance entries map their dates with a plain type conversion, which is
+// exactly where a driver-supplied local zone used to leak through.
+func TestMaintenanceEntryDatesRoundTripUnchanged(t *testing.T) {
+ ctx := context.Background()
+ item := useEntities(t, 1)[0]
+
+ const (
+ completed = "2026-08-27"
+ scheduled = "2026-09-15"
+ )
+
+ created, err := tRepos.MaintEntry.Create(ctx, tGroup.ID, item.ID, MaintenanceEntryCreate{
+ CompletedDate: unmarshalDate(t, completed),
+ ScheduledDate: unmarshalDate(t, scheduled),
+ Name: "Oil change",
+ Description: "Maintenance description",
+ Cost: 10,
+ })
+ require.NoError(t, err)
+ require.Equal(t, completed, created.CompletedDate.String())
+ require.Equal(t, scheduled, created.ScheduledDate.String())
+
+ entries, err := tRepos.MaintEntry.GetMaintenanceByItemID(ctx, tGroup.ID, item.ID, MaintenanceFilters{})
+ require.NoError(t, err)
+ require.Len(t, entries, 1)
+ require.Equal(t, completed, entries[0].CompletedDate.String())
+ require.Equal(t, scheduled, entries[0].ScheduledDate.String())
+}
diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.go
index 51baa435..efc6c38c 100644
--- a/backend/internal/data/repo/repo_entities.go
+++ b/backend/internal/data/repo/repo_entities.go
@@ -280,7 +280,7 @@ func mapEntitySummary(e *ent.Entity) EntitySummary {
ThumbnailId: thumbnailID,
// Sale
- SoldDate: types.DateFromTime(e.SoldDate),
+ SoldDate: types.DateFromDBTime(e.SoldDate),
}
}
@@ -335,7 +335,7 @@ func mapEntityOut(e *ent.Entity) EntityOut {
AssetID: AssetID(e.AssetID),
EntitySummary: mapEntitySummary(e),
LifetimeWarranty: e.LifetimeWarranty,
- WarrantyExpires: types.DateFromTime(e.WarrantyExpires),
+ WarrantyExpires: types.DateFromDBTime(e.WarrantyExpires),
WarrantyDetails: e.WarrantyDetails,
SyncChildEntityLocations: e.SyncChildEntityLocations,
@@ -345,11 +345,11 @@ func mapEntityOut(e *ent.Entity) EntityOut {
Manufacturer: e.Manufacturer,
// Purchase
- PurchaseDate: types.DateFromTime(e.PurchaseDate),
+ PurchaseDate: types.DateFromDBTime(e.PurchaseDate),
PurchaseFrom: e.PurchaseFrom,
// Sold
- SoldDate: types.DateFromTime(e.SoldDate),
+ SoldDate: types.DateFromDBTime(e.SoldDate),
SoldTo: e.SoldTo,
SoldPrice: e.SoldPrice,
SoldNotes: e.SoldNotes,
@@ -2028,8 +2028,12 @@ func (r *EntityRepository) ZeroOutTimeFields(ctx context.Context, gid uuid.UUID)
loadSpan.SetAttributes(attribute.Int("entities.count", len(entities)))
loadSpan.End()
+ // Normalize in UTC, not in t's own zone. Drivers may return a date-only
+ // column in the server's local zone (pgx does), and re-zeroing that value
+ // in place would write back the previous calendar day — turning a
+ // cosmetic read shift into permanent data loss.
toDateOnly := func(t time.Time) time.Time {
- return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
+ return types.DateFromDBTime(t).Time()
}
_, updateSpan := entityTracer().Start(ctx, "repo.EntityRepository.ZeroOutTimeFields.update",
diff --git a/backend/internal/data/repo/repo_maintenance_entry.go b/backend/internal/data/repo/repo_maintenance_entry.go
index 930d9ba2..b57b677d 100644
--- a/backend/internal/data/repo/repo_maintenance_entry.go
+++ b/backend/internal/data/repo/repo_maintenance_entry.go
@@ -70,8 +70,8 @@ var (
func mapMaintenanceEntry(entry *ent.MaintenanceEntry) MaintenanceEntry {
return MaintenanceEntry{
ID: entry.ID,
- CompletedDate: types.Date(entry.Date),
- ScheduledDate: types.Date(entry.ScheduledDate),
+ CompletedDate: types.DateFromDBTime(entry.Date),
+ ScheduledDate: types.DateFromDBTime(entry.ScheduledDate),
Name: entry.Name,
Description: entry.Description,
Cost: entry.Cost,
diff --git a/backend/internal/data/types/date.go b/backend/internal/data/types/date.go
index 9401e06c..36ddfd15 100644
--- a/backend/internal/data/types/date.go
+++ b/backend/internal/data/types/date.go
@@ -29,6 +29,25 @@ func DateFromTime(t time.Time) Date {
return Date(dateOnlyTime)
}
+// DateFromDBTime returns a Date from a timestamp read out of a date-only
+// database column.
+//
+// Date-only columns always hold UTC midnight of the intended calendar day —
+// that is the invariant DateFromTime establishes on the way in. Drivers are
+// not required to hand that instant back in UTC though: pgx decodes timestamptz
+// into the process's local zone, so a server running with TZ=America/Chicago
+// gets 2006-01-02T00:00:00Z back as 2006-01-01 18:00 CST. Reading the calendar
+// components off that value yields the day before, and saving the entity again
+// persists the shift. Normalize to UTC first so the stored day is recovered
+// exactly, on every driver and in every server timezone.
+func DateFromDBTime(t time.Time) Date {
+ if t.IsZero() {
+ return Date{}
+ }
+
+ return DateFromTime(t.UTC())
+}
+
// DateFromString returns a Date type from a string by parsing the
// string into a time.Time type and then stripping the time and
// timezone information.
@@ -61,7 +80,13 @@ func (d Date) String() string {
return ""
}
- return time.Time(d).Format("2006-01-02")
+ // Formatted in UTC, not in the value's own zone: every constructor here
+ // normalizes to UTC midnight, so UTC is where the intended calendar day
+ // lives. A Date produced by converting a driver-supplied time.Time
+ // directly (types.Date(row.Field)) may still carry a local zone, and
+ // formatting that in place would render the previous day west of
+ // Greenwich. See DateFromDBTime.
+ return time.Time(d).UTC().Format("2006-01-02")
}
func (d Date) MarshalJSON() ([]byte, error) {
diff --git a/backend/internal/data/types/date_test.go b/backend/internal/data/types/date_test.go
new file mode 100644
index 00000000..05f8176d
--- /dev/null
+++ b/backend/internal/data/types/date_test.go
@@ -0,0 +1,129 @@
+package types
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+// zones spanning both sides of Greenwich; the western ones are where the
+// off-by-one used to show up.
+var zones = []string{
+ "UTC",
+ "America/Los_Angeles",
+ "America/Chicago",
+ "America/New_York",
+ "Europe/Berlin",
+ "Pacific/Auckland",
+}
+
+func loadZones(t *testing.T) []*time.Location {
+ t.Helper()
+
+ locs := make([]*time.Location, 0, len(zones))
+ for _, name := range zones {
+ loc, err := time.LoadLocation(name)
+ if err != nil {
+ t.Skipf("timezone database unavailable: %v", err)
+ }
+ locs = append(locs, loc)
+ }
+ return locs
+}
+
+// A date-only column holds UTC midnight of the intended day. pgx hands that
+// instant back in the process's local zone, so the calendar components must be
+// read in UTC or the day slips backwards west of Greenwich.
+func TestDateFromDBTimePreservesDayInEveryZone(t *testing.T) {
+ const want = "2026-04-18"
+ stored := time.Date(2026, 4, 18, 0, 0, 0, 0, time.UTC)
+
+ for _, loc := range loadZones(t) {
+ asDriverReturnsIt := stored.In(loc)
+
+ if got := DateFromDBTime(asDriverReturnsIt).String(); got != want {
+ t.Errorf("DateFromDBTime in %s = %q, want %q", loc, got, want)
+ }
+ }
+}
+
+func TestDateFromDBTimeZeroStaysZero(t *testing.T) {
+ if got := DateFromDBTime(time.Time{}).String(); got != "" {
+ t.Errorf("DateFromDBTime(zero) = %q, want empty", got)
+ }
+}
+
+// Date.String is the last line of defence: a Date built by converting a
+// driver value directly (types.Date(row.Field)) still carries the local zone.
+func TestDateStringRendersUTCDay(t *testing.T) {
+ const want = "2026-04-18"
+ stored := time.Date(2026, 4, 18, 0, 0, 0, 0, time.UTC)
+
+ for _, loc := range loadZones(t) {
+ d := Date(stored.In(loc))
+
+ if got := d.String(); got != want {
+ t.Errorf("Date(%v).String() = %q, want %q", loc, got, want)
+ }
+
+ b, err := json.Marshal(d)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if string(b) != `"`+want+`"` {
+ t.Errorf("Date(%v) marshalled to %s, want %q", loc, b, want)
+ }
+ }
+}
+
+// The full API round-trip: the browser sends YYYY-MM-DD, we persist UTC
+// midnight, the driver reads it back in the server's zone, and the response
+// must carry the same day the user picked — and keep doing so when the
+// unchanged value is saved again.
+func TestDateRoundTripIsStableAcrossSaves(t *testing.T) {
+ const want = "2026-08-27"
+
+ for _, loc := range loadZones(t) {
+ var body struct {
+ PurchaseDate Date `json:"purchaseDate"`
+ }
+ if err := json.Unmarshal([]byte(`{"purchaseDate":"`+want+`"}`), &body); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ date := body.PurchaseDate
+ for hop := 1; hop <= 3; hop++ {
+ // Persist, then read back the way the driver would hand it over.
+ date = DateFromDBTime(date.Time().In(loc))
+
+ if got := date.String(); got != want {
+ t.Fatalf("save %d in %s produced %q, want %q", hop, loc, got, want)
+ }
+ }
+ }
+}
+
+func TestDateFromStringHonoursTheSendersOffset(t *testing.T) {
+ tests := []struct {
+ in string
+ want string
+ }{
+ {"2026-04-18", "2026-04-18"},
+ // An offset-bearing timestamp means the day its own offset shows,
+ // not the day it lands on in UTC.
+ {"2026-04-18T00:00:00+02:00", "2026-04-18"},
+ {"2026-04-18T00:00:00Z", "2026-04-18"},
+ // Why clients must not send Date.toISOString(): a UTC-normalized
+ // timestamp has already lost the picked day before it reaches us,
+ // and nothing here can recover it. This is the shape the pre-v0.26
+ // frontend sent, and the reason those rows are a day early at rest.
+ {"2026-04-17T22:00:00Z", "2026-04-17"},
+ {"", ""},
+ }
+
+ for _, tt := range tests {
+ if got := DateFromString(tt.in).String(); got != tt.want {
+ t.Errorf("DateFromString(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ }
+}
diff --git a/frontend/components/Form/DatePicker.vue b/frontend/components/Form/DatePicker.vue
index 8f2b22db..a3493186 100644
--- a/frontend/components/Form/DatePicker.vue
+++ b/frontend/components/Form/DatePicker.vue
@@ -12,8 +12,7 @@
<script setup lang="ts">
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
- import * as datelib from "~/lib/datelib/datelib";
- import { toDateOnlyString } from "~/lib/datelib/dateOnly";
+ import { isDateOnlyString, parseDateOnly, toDateOnlyString } from "~/lib/datelib/dateOnly";
import { Label } from "@/components/ui/label";
import { darkThemes } from "~/lib/data/themes";
@@ -33,19 +32,6 @@
type: String,
default: "Date",
},
- // When true, this field represents a date-only value (no time-of-day or
- // timezone semantics). modelValue is bound as a YYYY-MM-DD string and the
- // component emits a YYYY-MM-DD string. Use this for any field stored as
- // types.Date on the backend (purchaseDate, scheduledDate, etc.) — it
- // prevents the timezone day-shift bug that occurs when JSON.stringify
- // converts a Date object to a UTC ISO string.
- //
- // Leave false (the default) for true timestamp fields like invite expiry,
- // which need full Date-object precision.
- dateOnly: {
- type: Boolean,
- default: false,
- },
});
const isDark = useIsThemeInList(darkThemes);
@@ -66,7 +52,21 @@
return null;
}
- return datelib.parse(props.modelValue);
+ // YYYY-MM-DD is read through local components. `new Date("2026-04-18")`
+ // would be UTC midnight, which the calendar then highlights as the
+ // 17th for anyone west of Greenwich.
+ if (isDateOnlyString(props.modelValue)) {
+ // parseDateOnly also rejects impossible days. Those must not reach
+ // the constructor below: `new Date("2026-02-30")` rolls over to
+ // March 2 rather than failing, and the picker would then re-emit
+ // that invented date on the next save.
+ return parseDateOnly(props.modelValue);
+ }
+
+ // Timestamps from older records still fall back to the plain
+ // constructor.
+ const parsed = new Date(props.modelValue);
+ return isNaN(parsed.getTime()) ? null : parsed;
}
// Date
@@ -86,20 +86,14 @@
return null;
},
set(value: Date | null) {
- if (props.dateOnly) {
- // Always emit YYYY-MM-DD strings, derived from local components, so
- // the user's calendar day is preserved across the API round-trip.
- emit("update:modelValue", value ? toDateOnlyString(value) : "");
- return;
- }
-
- if (value instanceof Date) {
- value = datelib.zeroTime(value);
- emit("update:modelValue", value);
- } else {
- value = value ? datelib.zeroTime(new Date(value)) : null;
- emit("update:modelValue", value);
- }
+ // Always a YYYY-MM-DD string built from local components. Emitting a
+ // Date instead would let JSON.stringify serialize it as a UTC instant,
+ // which lands on the previous day for every user west of Greenwich and
+ // shifts again on each subsequent save. Every field this picker drives
+ // is a calendar date (types.Date on the backend), so there is no case
+ // where a Date object is the right thing to emit — a timestamp field
+ // should use VueDatePicker directly.
+ emit("update:modelValue", value ? toDateOnlyString(value) : "");
},
});
</script>
diff --git a/frontend/components/Maintenance/EditModal.vue b/frontend/components/Maintenance/EditModal.vue
index f839c7b8..2c0e710a 100644
--- a/frontend/components/Maintenance/EditModal.vue
+++ b/frontend/components/Maintenance/EditModal.vue
@@ -9,8 +9,8 @@
<form class="flex flex-col gap-2" @submit.prevent="dispatchFormSubmit">
<FormTextField v-model="entry.name" autofocus :label="$t('maintenance.modal.entry_name')" />
- <DatePicker v-model="entry.completedDate" date-only :label="$t('maintenance.modal.completed_date')" />
- <DatePicker v-model="entry.scheduledDate" date-only :label="$t('maintenance.modal.scheduled_date')" />
+ <DatePicker v-model="entry.completedDate" :label="$t('maintenance.modal.completed_date')" />
+ <DatePicker v-model="entry.scheduledDate" :label="$t('maintenance.modal.scheduled_date')" />
<FormTextArea v-model="entry.description" :label="$t('maintenance.modal.notes')" />
<FormTextField v-model="entry.cost" autofocus :label="$t('maintenance.modal.cost')" />
diff --git a/frontend/pages/item/[id]/index/edit.vue b/frontend/pages/item/[id]/index/edit.vue
index 1bc2424b..50396280 100644
--- a/frontend/pages/item/[id]/index/edit.vue
+++ b/frontend/pages/item/[id]/index/edit.vue
@@ -742,7 +742,6 @@
v-else-if="field.type === 'date'"
v-model="item[field.ref]"
:label="$t(field.label)"
- date-only
inline
/>
<FormCheckbox
@@ -930,7 +929,6 @@
v-else-if="field.type === 'date'"
v-model="item[field.ref]"
:label="$t(field.label)"
- date-only
inline
/>
<FormCheckbox
@@ -980,7 +978,6 @@
v-else-if="field.type === 'date'"
v-model="item[field.ref]"
:label="$t(field.label)"
- date-only
inline
/>
<FormCheckbox
@@ -1030,7 +1027,6 @@
v-else-if="field.type === 'date'"
v-model="item[field.ref]"
:label="$t(field.label)"
- date-only
inline
/>
<FormCheckbox