-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
367 lines (318 loc) · 9.37 KB
/
main.go
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package main
import (
"context"
"database/sql"
"encoding/csv"
"fmt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/labstack/gommon/log"
_ "github.com/lib/pq"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
var TaxLevelToggle bool = true
var db *sql.DB
var PersonalDeduction float64
var KReceiptDeductionLimit float64
func loadDeductions() error {
row := db.QueryRow("SELECT personal, receipt FROM deductions ORDER BY id DESC LIMIT 1")
err := row.Scan(&PersonalDeduction, &KReceiptDeductionLimit)
if err != nil {
if err == sql.ErrNoRows {
PersonalDeduction = 60000.0
KReceiptDeductionLimit = 50000.0
_, err = db.Exec("INSERT INTO deductions (personal, receipt) VALUES ($1, $2)", PersonalDeduction, KReceiptDeductionLimit)
} else {
return err
}
}
return nil
}
type Err struct {
Message string `json:"message"`
}
type Allowance struct {
AllowanceType string
Amount float64
}
type IncomeStatement struct {
TotalIncome float64 `json:"totalIncome"`
Wht float64 `json:"wht"`
Allowances []Allowance `json:"allowances"`
}
type TaxLevelDetail struct {
Level string `json:"level"`
Tax float64 `json:"tax"`
}
type TaxResult struct {
TotalIncome float64 `json:"totalIncome,omitempty"`
Tax float64 `json:"tax,omitempty"`
TaxRefund float64 `json:"taxRefund,omitempty"`
}
type DetailedTaxResult struct {
Tax float64 `json:"tax"`
Levels []TaxLevelDetail `json:"levels"`
}
type Deduction struct {
Amount float64 `json:"amount"`
}
type PersonalResponse struct {
PersonalDeduction float64 `json:"personalDeduction"`
}
type KReceiptResponse struct {
KReceiptDeductionLimit float64 `json:"kReceipt"`
}
func HealthCheckHandler(c echo.Context) error {
return c.JSON(http.StatusOK, "Hello, Go Bootcamp!")
}
// TaxCalculationsHandler
//
// @Summary Handles tax calculation
// @Description Calculate tax based on total income, WHT, and allowances
// @Tags tax
// @Accept json
// @Produce json
// @Success 200 {object} Tax
// @Failure 500 {object} Err
// @Router /tax/calculations [post]
func TaxCalculationsHandler(c echo.Context) error {
var i IncomeStatement
err := c.Bind(&i)
if err != nil {
return c.JSON(http.StatusBadRequest, Err{Message: err.Error()})
}
calculatedTax, err := CalculateTotalTax(i.TotalIncome, i.Wht, i.Allowances)
if calculatedTax < 0 {
calculatedTax *= -1
return c.JSON(http.StatusOK, TaxResult{TaxRefund: calculatedTax})
}
if TaxLevelToggle == true {
return c.JSON(http.StatusOK, DetailedTaxResult{Tax: calculatedTax, Levels: CalculateTaxLevel(calculatedTax, i.Wht)})
}
return c.JSON(http.StatusOK, TaxResult{Tax: calculatedTax})
}
func PersonalDeductionsHandler(c echo.Context) error {
var d Deduction
err := c.Bind(&d)
if err != nil {
return c.JSON(http.StatusBadRequest, Err{Message: err.Error()})
}
if d.Amount > 100000 {
return c.JSON(http.StatusBadRequest, Err{Message: "Personal deduction must not exceed 100,000"})
}
if d.Amount < 60000 {
return c.JSON(http.StatusBadRequest, Err{Message: "Personal deduction must start from 60000"})
}
PersonalDeduction = d.Amount
_, err = db.Exec("UPDATE deductions SET personal = $1 WHERE id = (SELECT MAX(id) FROM deductions)", PersonalDeduction)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
return c.JSON(http.StatusOK, PersonalResponse{PersonalDeduction: PersonalDeduction})
}
func KReceiptDeductionsHandler(c echo.Context) error {
var d Deduction
err := c.Bind(&d)
if err != nil {
return c.JSON(http.StatusBadRequest, Err{Message: err.Error()})
}
if d.Amount > 100000 {
return c.JSON(http.StatusBadRequest, Err{Message: "K-Receipt deduction must not exceed 100,000"})
}
KReceiptDeductionLimit = d.Amount
_, err = db.Exec("UPDATE deductions SET receipt = $1 WHERE id = (SELECT MAX(id) FROM deductions)", KReceiptDeductionLimit)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
return c.JSON(http.StatusOK, KReceiptResponse{KReceiptDeductionLimit: KReceiptDeductionLimit})
}
func CSVTaxCalculationsHandler(c echo.Context) error {
file, err := c.FormFile("file")
if err != nil {
return c.JSON(http.StatusBadRequest, Err{Message: err.Error()})
}
src, err := file.Open()
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
defer src.Close()
reader := csv.NewReader(src)
taxRecords, err := reader.ReadAll()
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
taxRecords = taxRecords[1:]
var csvResult []TaxResult
var csvA []Allowance
for _, taxRecord := range taxRecords {
totalIncome, err := strconv.ParseFloat(taxRecord[0], 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
wht, err := strconv.ParseFloat(taxRecord[1], 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
donation, err := strconv.ParseFloat(taxRecord[2], 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
csvA = append(csvA, Allowance{AllowanceType: "donation", Amount: donation})
calculatedTax, err := CalculateTotalTax(totalIncome, wht, csvA)
if err != nil {
return c.JSON(http.StatusInternalServerError, Err{Message: err.Error()})
}
if calculatedTax < 0 {
csvResult = append(csvResult, TaxResult{TotalIncome: totalIncome, TaxRefund: calculatedTax * -1})
} else {
csvResult = append(csvResult, TaxResult{TotalIncome: totalIncome, Tax: calculatedTax})
}
}
return c.JSON(http.StatusOK, csvResult)
}
func CalculateAllowance(allowances []Allowance) float64 {
donationAllowance := 0.0
kReceiptAllowance := 0.0
for _, allowance := range allowances {
if allowance.Amount < 0 {
}
if allowance.AllowanceType == "donation" {
donationAllowance += allowance.Amount
}
if allowance.AllowanceType == "k-receipt" {
kReceiptAllowance += allowance.Amount
}
}
if donationAllowance > 100000 {
donationAllowance = 100000
}
if kReceiptAllowance > KReceiptDeductionLimit {
kReceiptAllowance = KReceiptDeductionLimit
}
return donationAllowance + kReceiptAllowance
}
func CalculateTaxLevel(tax float64, wht float64) []TaxLevelDetail {
var CalculatedTaxLevels []TaxLevelDetail
CalculatedTaxLevels = []TaxLevelDetail{
{"0-150,000", 0.0},
{"150,001-500,000", 0.0},
{"500,001-1,000,000", 0.0},
{"1,000,001-2,000,000", 0.0},
{"2,000,001 ขึ้นไป", 0.0},
}
base := tax + wht
if base <= 35000.0 {
CalculatedTaxLevels[1].Tax = base
return CalculatedTaxLevels
}
CalculatedTaxLevels[1].Tax = 35000.0
base -= 35000.0
if base <= 75000.0 {
CalculatedTaxLevels[2].Tax = base
return CalculatedTaxLevels
}
CalculatedTaxLevels[2].Tax = 75000.0
base -= 75000.0
if base <= 200000.0 {
CalculatedTaxLevels[3].Tax = base
return CalculatedTaxLevels
}
CalculatedTaxLevels[3].Tax = 200000.0
base -= 200000.0
CalculatedTaxLevels[4].Tax = base
return CalculatedTaxLevels
}
func CalculateTotalTax(totalIncome float64, wht float64, allowances []Allowance) (float64, error) {
totalAllowance := PersonalDeduction + CalculateAllowance(allowances)
grossIncome := totalIncome - totalAllowance
totalTax := 0.0
if grossIncome <= 150000 {
return totalTax, nil
}
grossIncome -= 150000
if grossIncome <= 350000 {
totalTax += grossIncome * 0.1
totalTax -= wht
return totalTax, nil
}
totalTax += 350000 * 0.1
grossIncome -= 350000
if grossIncome <= 500000 {
totalTax += grossIncome * 0.15
totalTax -= wht
return totalTax, nil
}
totalTax += 500000 * 0.15
grossIncome -= 500000
if grossIncome <= 1000000 {
totalTax += grossIncome * 0.2
totalTax -= wht
return totalTax, nil
}
totalTax += 1000000 * 0.2
grossIncome -= 1000000
totalTax += grossIncome * 0.35
totalTax -= wht
return totalTax, nil
}
func AuthMiddleware(username, password string, c echo.Context) (bool, error) {
if username == os.Getenv("ADMIN_USERNAME") && password == os.Getenv("ADMIN_PASSWORD") {
return true, nil
}
return false, nil
}
func main() {
var err error
db, err = sql.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal("Connect to database error", err)
}
defer db.Close()
createTb := `
CREATE TABLE IF NOT EXISTS deductions (
id SERIAL PRIMARY KEY,
personal FLOAT,
receipt FLOAT
);
`
_, err = db.Exec(createTb)
if err != nil {
log.Fatal("can't create table", err)
}
err = loadDeductions()
if err != nil {
log.Fatal("Failed to load deductions", err)
}
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Logger.SetLevel(log.INFO)
e.GET("/", HealthCheckHandler)
t := e.Group("/tax/calculations")
t.POST("", TaxCalculationsHandler)
t.POST("/upload-csv", CSVTaxCalculationsHandler)
ad := e.Group("/admin/deductions")
ad.Use(middleware.BasicAuth(AuthMiddleware))
ad.POST("/personal", PersonalDeductionsHandler)
ad.POST("/k-receipt", KReceiptDeductionsHandler)
port := os.Getenv("PORT")
go func() {
if err := e.Start(":" + port); err != nil && err != http.ErrServerClosed {
e.Logger.Fatal("shutting down the server")
}
}()
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
<-shutdown
fmt.Println("\nshutting down the server")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}