~samwhited/paddle

ref: c8abffc53683631ce9b528be2aa2536c5f5b6bc9 paddle/coupon/coupons.go -rw-r--r-- 6.0 KiB
c8abffc5Sam Whited paddle, coupons: move coupon code to new package 2 years ago
                                                                                
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
// Package coupon provides the /product/*_coupon APIs.
package coupon

import (
	"bytes"
	"encoding/json"
	"net/url"
	"strconv"
	"strings"
	"time"

	"soquee.net/paddle"
	"soquee.net/paddle/internal"
)

const (
	createCouponsURL = "/product/create_coupon"
	listCouponsURL   = "/product/list_coupons"
	updateCouponsURL = "/product/update_coupon"
	deleteCouponsURL = "/product/delete_coupon"
)

// Client is used to perform API operations on Coupons.
type Client struct {
	*paddle.Client
}

// List requests a list of coupons available for the given product and returns
// an iterator that decodes them from the response body.
//
// If an error is returned, it is decoded and returned immediately.
func (c Client) List(productID int64) (Iter, error) {
	v := url.Values{}
	v.Add("product_id", strconv.FormatInt(productID, 10))

	msg, err := c.Do(listCouponsURL, v)
	if err != nil {
		return Iter{}, err
	}
	return Iter{
		d: json.NewDecoder(bytes.NewReader(msg)),
	}, nil
}

// Create creates a number of identical coupons.
// If num is greater than 1, coupon.Code is ignored and the codes are
// randomized.
// The coupon.Product field is ignored.
func (c Client) Create(num int, prefix, group string, couponType CouponType, recurring bool, coupon *Coupon) ([]string, error) {
	v := url.Values{}
	if num <= 1 {
		if coupon.Code != "" {
			v.Add("coupon_code", prefix+coupon.Code)
		}
	} else {
		v.Add("num_coupons", strconv.Itoa(num))
	}
	if prefix != "" && coupon.Code == "" {
		v.Add("coupon_prefix", prefix)
	}
	v.Add("description", coupon.Description)
	v.Add("coupon_type", string(couponType))
	var sb strings.Builder
	for _, product := range coupon.Product {
		if sb.Len() > 0 {
			sb.WriteByte(',')
		}
		/* #nosec */
		sb.WriteString(strconv.FormatInt(product, 10))
	}
	v.Add("product_ids", sb.String())
	v.Add("discount_type", string(coupon.DiscountType))
	v.Add("discount_amount", strconv.FormatFloat(coupon.DiscountAmount, 'f', -1, 64))
	if coupon.Currency != "" {
		v.Add("currency", coupon.Currency)
	}
	v.Add("allowed_uses", strconv.Itoa(coupon.AllowedUses))
	v.Add("expires", time.Time(coupon.Expires).Format(internal.DateFmt))
	// TODO: paddle claims that when creating this you should use "0" or "1"… WTF?
	// See: https://paddle.com/docs/api-generate-coupon/
	v.Add("recurring", strconv.FormatBool(coupon.Recurring))
	v.Add("minimum_threshold", strconv.FormatFloat(coupon.Minimum, 'f', -1, 64))
	if group != "" {
		v.Add("group", group)
	}

	msg, err := c.Do(createCouponsURL, v)
	if err != nil {
		return nil, err
	}
	codes := []string{}
	if num > 0 {
		err = json.Unmarshal(msg, codes)
	}
	return codes, err
}

// Update updates properties of a single coupon.
//
// Empty values will be ignored.
// If products is nil, it will be ignored, if it is an empty slice, all products
// will be removed.
func (c Client) Update(code string, coupon *Coupon) error {
	return c.updateCoupons("coupon_code", code, coupon.Code, coupon)
}

// UpdateGroup updates properties of an entire group of coupons.
//
// See UpdateCoupon for more information.
func (c Client) UpdateGroup(group, newGroup string, coupon *Coupon) error {
	return c.updateCoupons("code", group, newGroup, coupon)
}

func (c Client) updateCoupons(typ, code, newCode string, coupon *Coupon) error {
	v := url.Values{}
	v.Add(typ, code)
	if newCode != "" {
		v.Add("new_"+typ, newCode)
	}
	if coupon.Product != nil {
		var sb strings.Builder
		for _, product := range coupon.Product {
			if sb.Len() > 0 {
				sb.WriteByte(',')
			}
			/* #nosec */
			sb.WriteString(strconv.FormatInt(product, 10))
		}
		v.Add("product_ids", sb.String())
	}
	if !time.Time(coupon.Expires).IsZero() {
		v.Add("expires", time.Time(coupon.Expires).Format(internal.DateFmt))
	}
	if coupon.AllowedUses > 0 {
		v.Add("allowed_uses", strconv.Itoa(coupon.AllowedUses))
	}
	if coupon.DiscountType != "" {
		if coupon.DiscountType == DiscountFlat {
			v.Add("currency", coupon.Currency)
		}
		v.Add("discount_amount", strconv.FormatFloat(coupon.DiscountAmount, 'f', -1, 64))
	}

	_, err := c.Do(updateCouponsURL, v)
	return err
}

// DeleteCoupon deletes the given coupon from the given product.
func (c Client) DeleteCoupon(product int64, code string) error {
	v := url.Values{}
	v.Add("product_id", strconv.FormatInt(product, 64))
	v.Add("coupon_code", code)

	_, err := c.Do(deleteCouponsURL, v)
	return err
}

// Iter provides a mechanism for lazily decoding and iterating over a list of
// coupons.
type Iter struct {
	d *json.Decoder
}

// Next returns true if there are more coupons to decode.
func (c Iter) Next() bool {
	return c.d.More()
}

// Decode returns the next coupon.
func (c Iter) Decode() (*Coupon, error) {
	coupon := &Coupon{}
	err := c.d.Decode(coupon)
	return coupon, err
}

// Coupon represents a single coupon for a specific product.
type Coupon struct {
	ID             int64        `json:"id"`
	Code           string       `json:"coupon"`
	Description    string       `json:"description"`
	DiscountType   DiscountType `json:"discount_type"`
	DiscountAmount float64      `json:"discount_amount"`
	Currency       string       `json:"discount_currency"`
	AllowedUses    int          `json:"allowed_uses"`
	TimesUsed      int          `json:"times_used"`
	Recurring      bool         `json:"is_recurring"`
	Expires        paddle.Time  `json:"expires"`
	Product        []int64      `json:"-"`
	Minimum        float64      `json:"minimum_threshold"`
}

var _ json.Unmarshaler = (*Coupon)(nil)

// UnmarshalJSON satisfies the json.Unmarshaler interface for Coupon.
//
// It is necessary because when creating coupons a slice of product IDs is
// required, but when getting coupons an individual product ID is provided.
// When unmarshaling, convert the indivdiual product ID into a slice of length
// 1.
func (c *Coupon) UnmarshalJSON(b []byte) error {
	newC := struct {
		Coupon
		P int64 `json:"product_id"`
	}{}
	err := json.Unmarshal(b, &newC)
	if err != nil {
		return err
	}

	c.Product = []int64{newC.P}
	return nil
}

// CouponType is a specific type of coupon.
type CouponType string

// A list of valid coupon types.
const (
	CouponProduct  CouponType = "product"
	CouponCheckout CouponType = "checkout"
)