Skip to content

Commit

Permalink
Merge pull request #136 from vshn/fix-timezone-marshal
Browse files Browse the repository at this point in the history
Fix saving timezone when updating a payslip
  • Loading branch information
ccremer authored Nov 9, 2022
2 parents b2404d6 + a88f9ea commit 68f3073
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pkg/odoo/timezone.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ func (tz *TimeZone) UnmarshalJSON(b []byte) error {
return nil
}

// MarshalJSON implements json.Marshaler.
func (tz *TimeZone) MarshalJSON() ([]byte, error) {
if tz.IsEmpty() || tz.Location() == time.Local {
return []byte(`null`), nil
}
return []byte(fmt.Sprintf(`"%s"`, tz.loc)), nil
}

func (tz *TimeZone) Location() *time.Location {
if tz == nil {
return nil
Expand Down
24 changes: 24 additions & 0 deletions pkg/odoo/timezone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,30 @@ func TestTimeZone_UnmarshalJSON(t *testing.T) {
}
}

func TestTimeZone_MarshalJSON(t *testing.T) {
tests := map[string]struct {
givenLocation *time.Location
expectedOutput []byte
}{
"nil": {givenLocation: nil, expectedOutput: []byte("null")},
"EuropeZurich": {givenLocation: mustLoadLocation("Europe/Zurich"), expectedOutput: []byte(`"Europe/Zurich"`)},
"Local": {givenLocation: time.Local, expectedOutput: []byte("null")}, // "Local" isn't recognized by Odoo
"UTC": {givenLocation: time.UTC, expectedOutput: []byte(`"UTC"`)},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
subject := &TimeZone{loc: tt.givenLocation}
result, err := subject.MarshalJSON()
require.NoError(t, err)
if tt.expectedOutput == nil {
assert.Nil(t, result)
} else {
assert.Equal(t, tt.expectedOutput, result)
}
})
}
}

func mustLoadLocation(name string) *time.Location {
loc, err := time.LoadLocation(name)
if err != nil {
Expand Down

0 comments on commit 68f3073

Please sign in to comment.