GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#255)
by
unknown
01:22
created

mollie/balances.go   A

Size/Duplication

Total Lines 395
Duplicated Lines 0 %

Test Coverage

Coverage 93.02%

Importance

Changes 0
Metric Value
cc 22
eloc 218
dl 0
loc 395
ccs 40
cts 43
cp 0.9302
crap 22.1645
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A mollie.*BalancesService.listTransactions 0 17 3
A mollie.*BalancesService.List 0 6 1
A mollie.*BalancesService.getReport 0 17 3
A mollie.*BalancesService.get 0 13 3
A mollie.*BalancesService.GetTransactionsList 0 10 1
A mollie.*BalancesService.GetReport 0 6 1
A mollie.*BalancesService.GetPrimaryReport 0 6 1
A mollie.*BalancesService.list 0 15 3
A mollie.*BalancesService.Get 0 2 1
A mollie.*BalancesService.Primary 0 4 1
A mollie.*BalancesService.GetPrimaryTransactionsList 0 6 1
A mollie.*ContextValues.UnmarshalJSON 0 15 3
1
package mollie
2
3
import (
4
	"context"
5
	"encoding/json"
6
	"fmt"
7
	"time"
8
)
9
10
// BalancesService allows you to retrieve real-time as well as historical
11
// information about your Mollie balance.
12
//
13
// Works with Organization access tokens and App access tokens.
14
//
15
// The API is in **BETA** so be careful and expect changes.
16
//
17
// See: https://docs.mollie.com/reference/v2/balances-api/overview
18
type BalancesService service
19
20
// BalanceStatus reflects whether a balance is operational or not.
21
type BalanceStatus string
22
23
// Possible values for type BalanceStatus.
24
const (
25
	BalanceActive   BalanceStatus = "active"
26
	BalanceInactive BalanceStatus = "inactive"
27
)
28
29
// TransferFrequency reflects the frequency at which the available amount
30
// on the balance will be settled to the configured transfer destination.
31
type TransferFrequency string
32
33
// Possible values for type TransferFrequency.
34
const (
35
	TransferDaily          TransferFrequency = "daily"
36
	TransferTwiceAWeek     TransferFrequency = "twice-a-week"
37
	TransferEveryMonday    TransferFrequency = "every-monday"
38
	TransferEveryTuesday   TransferFrequency = "every-tuesday"
39
	TransferEveryWednesday TransferFrequency = "every-wednesday"
40
	TransferEveryThursday  TransferFrequency = "every-thursday"
41
	TransferEveryFriday    TransferFrequency = "every-friday"
42
	TransferTwiceAMonth    TransferFrequency = "twice-a-month"
43
	TransferMonthly        TransferFrequency = "monthly"
44
	TransferNever          TransferFrequency = "never"
45
)
46
47
// TransferDestination where the available amount will be automatically
48
// transferred.
49
type TransferDestination struct {
50
	Type            string `json:"type,omitempty"`
51
	BankAccount     string `json:"bankAccount,omitempty"`
52
	BeneficiaryName string `json:"beneficiaryName,omitempty"`
53
}
54
55
// BalanceLinks holds URL objects relevant to the balance.
56
type BalanceLinks struct {
57
	Self          *URL `json:"self,omitempty"`
58
	Documentation *URL `json:"documentation,omitempty"`
59
}
60
61
// Balance holds the payments processed with Mollie once fees have been deducted.
62
type Balance struct {
63
	ID                  string               `json:"id,omitempty"`
64
	Resource            string               `json:"resource,omitempty"`
65
	Currency            string               `json:"currency,omitempty"`
66
	TransferReference   string               `json:"transferReference,omitempty"`
67
	Status              BalanceStatus        `json:"status,omitempty"`
68
	TransferFrequency   TransferFrequency    `json:"transferFrequency,omitempty"`
69
	TransferThreshold   *Amount              `json:"transferThreshold,omitempty"`
70
	AvailableAmount     *Amount              `json:"availableAmount,omitempty"`
71
	PendingAmount       *Amount              `json:"pendingAmount,omitempty"`
72
	TransferDestination *TransferDestination `json:"transferDestination,omitempty"`
73
	CreatedAt           *time.Time           `json:"createdAt,omitempty"`
74
	Links               BalanceLinks         `json:"_links,omitempty"`
75
}
76
77
// BalancesList describes a list of captures.
78
type BalancesList struct {
79
	Count    int `json:"count,omitempty"`
80
	Embedded struct {
81
		Balances []*Balance `json:"balances,omitempty"`
82
	} `json:"_embedded,omitempty"`
83
	Links PaginationLinks `json:"_links,omitempty"`
84
}
85
86
// BalanceListOptions contains valid query parameters
87
// for the list balances endpoint.
88
type BalanceListOptions struct {
89
	Currency string `url:"currency,omitempty"`
90
	From     string `url:"from,omitempty"`
91
	Limit    int    `url:"limit,omitempty"`
92
}
93
94
// BalanceGroupingFormat defines a grouping mechanism for transactions included
95
// in a balance report.
96
type BalanceGroupingFormat string
97
98
// Supported transaction grouping.
99
const (
100
	StatusBalancesGrouping        BalanceGroupingFormat = "status-balances"
101
	TransactionCategoriesGrouping BalanceGroupingFormat = "transaction-categories"
102
)
103
104
// BalanceReportOptions contains valid query parameters
105
// for the list balances endpoint.
106
type BalanceReportOptions struct {
107
	Grouping BalanceGroupingFormat `url:"grouping,omitempty"`
108
	From     *ShortDate            `url:"from,omitempty"`
109
	Until    *ShortDate            `url:"until,omitempty"`
110
}
111
112
// Subtotal balance descriptor.
113
type Subtotal struct {
114
	TransactionType string      `json:"transactionType,omitempty"`
115
	Count           int         `json:"count,omitempty"`
116
	Amount          *Amount     `json:"amount,omitempty"`
117
	Subtotals       []*Subtotal `json:"subtotals,omitempty"`
118
}
119
120
// BalanceReportLinks holds URL objects relevant to the balance report.
121
type BalanceReportLinks struct {
122
	Self          *URL `json:"self,omitempty"`
123
	Documentation *URL `json:"documentation,omitempty"`
124
}
125
126
// BalanceReport contains the common fields between
127
// different balance grouping options.
128
type BalanceReport struct {
129
	Resource  string                       `json:"resource,omitempty"`
130
	BalanceID string                       `json:"balanceId,omitempty"`
131
	TimeZone  string                       `json:"timeZone,omitempty"`
132
	From      *ShortDate                   `json:"from,omitempty"`
133
	Until     *ShortDate                   `json:"until,omitempty"`
134
	Totals    *BalanceReportTotalsGrouping `json:"totals,omitempty"`
135
	Grouping  BalanceGroupingFormat        `json:"grouping,omitempty"`
136
	Links     BalanceReportLinks           `json:"_links,omitempty"`
137
}
138
139
// BalanceAmount wraps the std Amount type.
140
type BalanceAmount struct {
141
	Amount *Amount `json:"amount,omitempty"`
142
}
143
144
// BalanceReportDetail contains the breakdown
145
// categories when grouping balance transactions.
146
type BalanceReportDetail struct {
147
	Open                 *BalanceAmount `json:"open,omitempty"`
148
	Pending              *BalanceAmount `json:"pending,omitempty"`
149
	MovedToAvailable     *BalanceAmount `json:"movedToAvailable,omitempty"`
150
	ImmediatelyAvailable *BalanceAmount `json:"immediatelyAvailable,omitempty"`
151
	Close                *BalanceAmount `json:"close,omitempty"`
152
}
153
154
// BalanceReportTotalsGrouping contains the per totals
155
// grouped balances for the requested period.
156
type BalanceReportTotalsGrouping struct {
157
	PendingBalance   *BalanceReportDetail `json:"pendingBalance,omitempty"`
158
	AvailableBalance *BalanceReportDetail `json:"availableBalance,omitempty"`
159
	Open             *BalanceReportDetail `json:"open,omitempty"`
160
	Payments         *BalanceReportDetail `json:"payments,omitempty"`
161
	Refunds          *BalanceReportDetail `json:"refunds,omitempty"`
162
	Chargebacks      *BalanceReportDetail `json:"chargebacks,omitempty"`
163
	Capital          *BalanceReportDetail `json:"capital,omitempty"`
164
	Transfers        *BalanceReportDetail `json:"transfers,omitempty"`
165
	FeePrePayments   *BalanceReportDetail `json:"fee-prepayments,omitempty"`
166
	Corrections      *BalanceReportDetail `json:"corrections,omitempty"`
167
	Close            *BalanceReportDetail `json:"close,omitempty"`
168
}
169
170
// BalanceTransaction represents a the movement on your balance.
171
type BalanceTransaction struct {
172
	Resource        string        `json:"resource,omitempty"`
173
	ID              string        `json:"id,omitempty"`
174
	TransactionType string        `json:"transactionType,omitempty"`
175
	ResultAmount    *Amount       `json:"resultAmount,omitempty"`
176
	InitialAmount   *Amount       `json:"initialAmount,omitempty"`
177
	Deductions      *Amount       `json:"deductions,omitempty"`
178
	CreatedAt       *time.Time    `json:"createdAt,omitempty"`
179
	Context         ContextValues `json:"context,omitempty"`
180
}
181
182
type (
183
	// TransactionType specifies the reason for the movement.
184
	TransactionType string
185
	// ContextValue represents a relevant value in the system
186
	// associated with a BalanceTransaction.
187
	ContextValue string
188
)
189
190
// Known and supported transaction types.
191
const (
192
	PaymentTransaction                     TransactionType = "payment"
193
	CaptureTransaction                     TransactionType = "capture"
194
	UnauthorizedDirectDebitTransaction     TransactionType = "unauthorized-direct-debit"
195
	FailedPaymentTransaction               TransactionType = "failed-payment"
196
	RefundTransaction                      TransactionType = "refund-transaction"
197
	ReturnedRefundTransaction              TransactionType = "returned-refund"
198
	ChargebackTransaction                  TransactionType = "chargeback"
199
	ChargebackReversalTransaction          TransactionType = "chargeback-reversal"
200
	OutgoingTransferTransaction            TransactionType = "outgoing-transfer"
201
	CanceledOutgoingTransfer               TransactionType = "canceled-outgoing-transfer"
202
	ReturnedTransferTransaction            TransactionType = "returned-transfer"
203
	InvoiceCompensationTransferTransaction TransactionType = "invoice-compensation"
204
	BalanceCorrectionTransaction           TransactionType = "balance-correction"
205
	ApplicationFeeTransaction              TransactionType = "application-fee"
206
	SplitPaymentTransaction                TransactionType = "split-payment"
207
	PlatformPaymentRefundTransaction       TransactionType = "platform-payment-refund"
208
	PlatformPaymentChargeback              TransactionType = "platform-payment-chargeback"
209
)
210
211
// ContextValues is a map of TransactionType to ContextValue.
212
type ContextValues map[TransactionType]ContextValue
213
214
// UnmarshalJSON is a custom unmarshal function for handling the "context" field.
215
// Needed for fault tolerance
216
func (cv *ContextValues) UnmarshalJSON(data []byte) error {
217
	// Check if the "context" field is an empty array and create empty map in this case
218 1
	if string(data) == "[]" {
219
		*cv = make(ContextValues)
220
		return nil
221
	}
222
223
	// If it is not an array, unmarshal it as a map
224 1
	var m map[TransactionType]ContextValue
225 1
	if err := json.Unmarshal(data, &m); err != nil {
226
		return err
227
	}
228
229 1
	*cv = ContextValues(m)
230 1
	return nil
231
}
232
233
// BalanceTransactionsList contains an array of embedded transactions.
234
type BalanceTransactionsList struct {
235
	Count    int `json:"count,omitempty"`
236
	Embedded struct {
237
		BalanceTransactions []*BalanceTransaction `json:"balance_transactions,omitempty"`
238
	} `json:"_embedded,omitempty"`
239
	Links PaginationLinks `json:"_links,omitempty"`
240
}
241
242
// BalanceTransactionsListOptions are valid query parameters for list
243
// balance transactions requests.
244
type BalanceTransactionsListOptions struct {
245
	From  string `url:"from,omitempty"`
246
	Limit int    `url:"limit,omitempty"`
247
}
248
249
// GetBalance retrieves a balance by its id.
250
//
251
// See: https://docs.mollie.com/reference/v2/balances-api/get-balance
252
func (bs *BalancesService) Get(ctx context.Context, balance string) (res *Response, b *Balance, err error) {
253 1
	return bs.get(ctx, balance)
254
}
255
256
// Primary retrieves the primary balance. This is the balance of your account’s
257
// primary currency, where all payments are settled to by default.
258
//
259
// See: https://docs.mollie.com/reference/v2/balances-api/get-primary-balance
260
func (bs *BalancesService) Primary(ctx context.Context) (res *Response, b *Balance, err error) {
261 1
	const id = "primary"
262
263 1
	return bs.get(ctx, id)
264
}
265
266
// List retrieves all the organization’s balances, including the primary
267
// balance, ordered from newest to oldest.
268
//
269
// See: https://docs.mollie.com/reference/v2/balances-api/list-balances
270
func (bs *BalancesService) List(ctx context.Context, options *BalanceListOptions) (
271
	res *Response,
272
	bl *BalancesList,
273
	err error,
274
) {
275 1
	return bs.list(ctx, "v2/balances", options)
276
}
277
278
// GetReport returns the balance report for the specified balance id.
279
//
280
// See: https://docs.mollie.com/reference/v2/balances-api/get-balance-report
281
func (bs *BalancesService) GetReport(ctx context.Context, balance string, options *BalanceReportOptions) (
282
	res *Response,
283
	br *BalanceReport,
284
	err error,
285
) {
286 1
	return bs.getReport(ctx, balance, options)
287
}
288
289
// GetPrimaryReport returns the report for the primary balance.
290
//
291
// See: https://docs.mollie.com/reference/v2/balances-api/get-primary-balance-report
292
func (bs *BalancesService) GetPrimaryReport(ctx context.Context, options *BalanceReportOptions) (
293
	res *Response,
294
	br *BalanceReport,
295
	err error,
296
) {
297 1
	return bs.getReport(ctx, "primary", options)
298
}
299
300
// GetTransactionsList retrieves a list of movements (transactions) for the
301
// specified balance.
302
//
303
// See: https://docs.mollie.com/reference/v2/balances-api/list-balance-transactions
304
func (bs *BalancesService) GetTransactionsList(
305
	ctx context.Context,
306
	balance string,
307
	options *BalanceTransactionsListOptions,
308
) (
309
	res *Response,
310
	btl *BalanceTransactionsList,
311
	err error,
312
) {
313 1
	return bs.listTransactions(ctx, balance, options)
314
}
315
316
// GetPrimaryTransactionsList retrieves the list of movements (transactions) for the
317
// primary balance of the account.
318
//
319
// See: https://docs.mollie.com/reference/v2/balances-api/list-primary-balance-transactions
320
func (bs *BalancesService) GetPrimaryTransactionsList(ctx context.Context, options *BalanceTransactionsListOptions) (
321
	res *Response,
322
	btl *BalanceTransactionsList,
323
	err error,
324
) {
325 1
	return bs.listTransactions(ctx, "primary", options)
326
}
327
328
func (bs *BalancesService) get(ctx context.Context, balance string) (res *Response, b *Balance, err error) {
329 1
	u := fmt.Sprintf("v2/balances/%s", balance)
330
331 1
	res, err = bs.client.get(ctx, u, nil)
332 1
	if err != nil {
333 1
		return
334
	}
335
336 1
	if err = json.Unmarshal(res.content, &b); err != nil {
337 1
		return
338
	}
339
340 1
	return
341
}
342
343
func (bs *BalancesService) list(
344
	ctx context.Context,
345
	uri string,
346
	options interface{},
347
) (res *Response, lb *BalancesList, err error) {
348 1
	res, err = bs.client.get(ctx, uri, options)
349 1
	if err != nil {
350 1
		return
351
	}
352
353 1
	if err = json.Unmarshal(res.content, &lb); err != nil {
354 1
		return
355
	}
356
357 1
	return
358
}
359
360
func (bs *BalancesService) getReport(
361
	ctx context.Context,
362
	balance string,
363
	options *BalanceReportOptions,
364
) (res *Response, br *BalanceReport, err error) {
365 1
	u := fmt.Sprintf("v2/balances/%s/report", balance)
366
367 1
	res, err = bs.client.get(ctx, u, options)
368 1
	if err != nil {
369 1
		return
370
	}
371
372 1
	if err = json.Unmarshal(res.content, &br); err != nil {
373 1
		return
374
	}
375
376 1
	return
377
}
378
379
func (bs *BalancesService) listTransactions(
380
	ctx context.Context,
381
	balance string,
382
	options *BalanceTransactionsListOptions,
383
) (res *Response, btl *BalanceTransactionsList, err error) {
384 1
	u := fmt.Sprintf("v2/balances/%s/transactions", balance)
385
386 1
	res, err = bs.client.get(ctx, u, options)
387 1
	if err != nil {
388 1
		return
389
	}
390
391 1
	if err = json.Unmarshal(res.content, &btl); err != nil {
392 1
		return
393
	}
394
395 1
	return
396
}
397