-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
287 lines (259 loc) · 9.12 KB
/
types.go
File metadata and controls
287 lines (259 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"time"
)
// Config represents the application configuration
type Config struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURI string `json:"redirect_uri"`
Scopes string `json:"scopes"`
TokenStorePath string `json:"token_store_path"`
Port string `json:"port"`
}
// TokenStore holds the authentication tokens
type TokenStore struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Expiry time.Time `json:"expiry"`
TenantID string `json:"tenant_id"`
TenantName string `json:"tenant_name"`
Scopes string `json:"scopes"`
UpdatedAt time.Time `json:"updated_at"`
}
// TokenResponse from Xero OAuth2
type TokenResponse struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
// Connection represents a Xero organization connection
type Connection struct {
ID string `json:"id"`
AuthEventID string `json:"authEventId"`
TenantID string `json:"tenantId"`
TenantType string `json:"tenantType"`
TenantName string `json:"tenantName"`
CreatedDate XeroTime `json:"createdDateUtc"`
UpdatedDate XeroTime `json:"updatedDateUtc"`
}
// Custom time format for Xero API timestamps with high precision
type XeroTime time.Time
func (xt *XeroTime) UnmarshalJSON(b []byte) error {
s := string(b)
if s == "null" {
return nil
}
s = s[1 : len(s)-1] // Remove quotes
// Handle escaped slashes in Microsoft JSON date format: \/Date(1234567890+0000)\/
s = strings.ReplaceAll(s, `\/`, `/`)
// Handle Microsoft JSON date format: /Date(1234567890+0000)/
if strings.HasPrefix(s, "/Date(") && strings.HasSuffix(s, ")/") {
msStr := s[6 : len(s)-2]
// Parse milliseconds
var ms int64
if dotIdx := strings.Index(msStr, "+"); dotIdx != -1 {
ms, _ = strconv.ParseInt(msStr[:dotIdx], 10, 64)
} else if dotIdx := strings.Index(msStr, "-"); dotIdx != -1 {
ms, _ = strconv.ParseInt(msStr[:dotIdx], 10, 64)
} else {
ms, _ = strconv.ParseInt(msStr, 10, 64)
}
*xt = XeroTime(time.Unix(ms/1000, (ms%1000)*1000000))
return nil
}
formats := []string{
"2006-01-02T15:04:05.9999999",
"2006-01-02T15:04:05.999999",
"2006-01-02T15:04:05.99999",
"2006-01-02T15:04:05.9999",
"2006-01-02T15:04:05.999",
"2006-01-02T15:04:05.99",
"2006-01-02T15:04:05.9",
"2006-01-02T15:04:05",
"2006-01-02T15:04:05Z07:00",
"2006-01-02T15:04:05.9999999Z07:00",
"2006-01-02T15:04:05Z",
"2006-01-02T15:04:05.9999999Z",
}
for _, format := range formats {
if t, err := time.Parse(format, s); err == nil {
*xt = XeroTime(t)
return nil
}
}
return fmt.Errorf("unable to parse time: %s", s)
}
func (xt XeroTime) MarshalJSON() ([]byte, error) {
t := time.Time(xt)
if t.IsZero() {
return []byte("null"), nil
}
return []byte(`"` + t.Format(time.RFC3339) + `"`), nil
}
// Invoice represents a Xero invoice
type Invoice struct {
InvoiceID string `json:"InvoiceID"`
InvoiceNumber string `json:"InvoiceNumber"`
Contact Contact `json:"Contact"`
Type string `json:"Type"`
Status string `json:"Status"`
LineAmountTypes string `json:"LineAmountTypes"`
Date XeroTime `json:"Date"`
DueDate XeroTime `json:"DueDate"`
LineItems []LineItem `json:"LineItems"`
SubTotal float64 `json:"SubTotal"`
TotalTax float64 `json:"TotalTax"`
Total float64 `json:"Total"`
CurrencyCode string `json:"CurrencyCode"`
AmountDue float64 `json:"AmountDue"`
AmountPaid float64 `json:"AmountPaid"`
AmountCredited float64 `json:"AmountCredited"`
CreatedDateUTC XeroTime `json:"CreatedDateUTC"`
UpdatedDateUTC XeroTime `json:"UpdatedDateUTC"`
}
// CreditNote represents a Xero credit note
type CreditNote struct {
CreditNoteID string `json:"CreditNoteID"`
CreditNoteNumber string `json:"CreditNoteNumber"`
Contact Contact `json:"Contact"`
Type string `json:"Type"`
Status string `json:"Status"`
LineAmountTypes string `json:"LineAmountTypes"`
Date XeroTime `json:"Date"`
LineItems []LineItem `json:"LineItems"`
SubTotal float64 `json:"SubTotal"`
TotalTax float64 `json:"TotalTax"`
Total float64 `json:"Total"`
CurrencyCode string `json:"CurrencyCode"`
AmountDue float64 `json:"AmountDue"`
AmountCredited float64 `json:"AmountCredited"`
RemainingCredit float64 `json:"RemainingCredit"`
CreatedDateUTC XeroTime `json:"CreatedDateUTC"`
UpdatedDateUTC XeroTime `json:"UpdatedDateUTC"`
}
// LineItem represents an invoice line item
type LineItem struct {
LineItemID string `json:"LineItemID"`
Description string `json:"Description"`
Quantity float64 `json:"Quantity"`
UnitAmount float64 `json:"UnitAmount"`
AccountCode string `json:"AccountCode"`
LineAmount float64 `json:"LineAmount"`
}
// Contact represents a Xero contact
type Contact struct {
ContactID string `json:"ContactID"`
Name string `json:"Name"`
EmailAddress string `json:"EmailAddress"`
FirstName string `json:"FirstName"`
LastName string `json:"LastName"`
Addresses []Address `json:"Addresses"`
Phones []Phone `json:"Phones"`
IsCustomer bool `json:"IsCustomer"`
IsSupplier bool `json:"IsSupplier"`
PaymentTerms PaymentTerms `json:"PaymentTerms"`
CreatedDateUTC XeroTime `json:"CreatedDateUTC"`
UpdatedDateUTC XeroTime `json:"UpdatedDateUTC"`
}
// Address represents a contact address
type Address struct {
AddressType string `json:"AddressType"`
AddressLine1 string `json:"AddressLine1"`
AddressLine2 string `json:"AddressLine2"`
City string `json:"City"`
Region string `json:"Region"`
PostalCode string `json:"PostalCode"`
Country string `json:"Country"`
}
// Phone represents a contact phone number
type Phone struct {
PhoneType string `json:"PhoneType"`
PhoneNumber string `json:"PhoneNumber"`
PhoneAreaCode string `json:"PhoneAreaCode"`
PhoneCountryCode string `json:"PhoneCountryCode"`
}
// PaymentTerms represents payment terms for a contact
type PaymentTerms struct {
Bills TermDetail `json:"Bills"`
Sales TermDetail `json:"Sales"`
}
// TermDetail represents payment term details
type TermDetail struct {
Day int `json:"Day"`
Type string `json:"Type"`
}
// Payment represents a Xero payment
type Payment struct {
PaymentID string `json:"PaymentID"`
Invoice Invoice `json:"Invoice"`
Amount float64 `json:"Amount"`
Date XeroTime `json:"Date"`
Reference string `json:"Reference"`
IsReconciled bool `json:"IsReconciled"`
Account Account `json:"Account"`
CreatedDateUTC XeroTime `json:"CreatedDateUTC"`
UpdatedDateUTC XeroTime `json:"UpdatedDateUTC"`
}
// Account represents a Xero account (chart of accounts)
type Account struct {
AccountID string `json:"AccountID"`
Code string `json:"Code"`
Name string `json:"Name"`
Type string `json:"Type"`
Class string `json:"Class"`
Status string `json:"Status"`
Description string `json:"Description"`
BankAccountNumber string `json:"BankAccountNumber"`
CurrencyCode string `json:"CurrencyCode"`
TaxType string `json:"TaxType"`
EnablePaymentsToAccount bool `json:"EnablePaymentsToAccount"`
ShowInExpenseClaims bool `json:"ShowInExpenseClaims"`
Balance float64 `json:"Balance"`
CreatedDateUTC XeroTime `json:"CreatedDateUTC"`
UpdatedDateUTC XeroTime `json:"UpdatedDateUTC"`
}
// APIError represents an Xero API error
type APIError struct {
Type string `json:"Type"`
Title string `json:"Title"`
Status int `json:"Status"`
Detail string `json:"Detail"`
Instance string `json:"Instance"`
Extensions map[string]interface{} `json:"Extensions"`
}
func (e *APIError) Error() string {
return fmt.Sprintf("%s (%d): %s", e.Title, e.Status, e.Detail)
}
// IsTokenExpired checks if this is a token expiration error
func (e *APIError) IsTokenExpired() bool {
if e.Extensions == nil {
return false
}
problem, ok := e.Extensions["oauth_problem"].(string)
return ok && problem == "token_expired"
}
// LoadFromJSON loads an object from JSON file
func LoadFromJSON(filePath string, target interface{}) error {
data, err := os.ReadFile(filePath)
if err != nil {
return err
}
return json.Unmarshal(data, target)
}
// SaveToJSON saves an object to JSON file
func SaveToJSON(filePath string, data interface{}) error {
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return os.WriteFile(filePath, jsonData, 0600)
}