-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
382 lines (328 loc) · 10.6 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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v2"
)
type Config struct {
URL string `yaml:"url"`
Username string `yaml:"username"`
Password string `yaml:"password"`
}
type Stats struct {
Created int `xml:"created"`
Updated int `xml:"updated"`
Deleted int `xml:"deleted"`
Skipped int `xml:"skipped"`
Failed int `xml:"failed"`
}
type Response struct {
Success bool `xml:"success"`
Stats Stats `xml:"stats"`
}
type CentralConfig struct {
Directories []string `yaml:"directories"`
PaymentOrderDirectories []string `yaml:"payment_order_directories"`
LogToFile bool `yaml:"log_to_file"`
}
type PaymentOrder struct {
ID string `json:"id"`
LastUpdate string `json:"lastUpdate"`
DatSplat string `json:"datSplat"`
Mena string `json:"mena"`
}
type PaymentOrderResponse struct {
Winstrom struct {
Version string `json:"@version"`
PaymentOrders []PaymentOrder `json:"prikaz-k-uhrade"`
} `json:"winstrom"`
}
func loadConfig(configPath string) (*Config, error) {
data, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
var config Config
err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func loadCentralConfig(configPath string) (*CentralConfig, error) {
data, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
var centralConfig CentralConfig
err = yaml.Unmarshal(data, ¢ralConfig)
if err != nil {
return nil, err
}
return ¢ralConfig, nil
}
func processFiles(directory string, config *Config) error {
var foundGPCFile bool
err := filepath.Walk(directory, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && (strings.HasSuffix(info.Name(), ".GPC") || strings.HasSuffix(info.Name(), ".gpc")) {
foundGPCFile = true
fileContent, err := os.ReadFile(path)
if err != nil {
return err
}
req, err := http.NewRequest("POST", config.URL, bytes.NewReader(fileContent))
if err != nil {
return err
}
auth := config.Username + ":" + config.Password
encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Authorization", "Basic "+encodedAuth)
req.Header.Add("Content-Type", "application/octet-stream")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var response Response
err := xml.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return err
}
if response.Success {
newPath := strings.TrimSuffix(path, filepath.Ext(path)) + ".nahrano"
err := os.Rename(path, newPath)
if err != nil {
return err
}
log.Info().Msgf("Successfully processed (Uploaded to AbraCloud) and renamed file: %s", path)
log.Info().Msgf("Stats - Created: %d, Updated: %d, Deleted: %d, Skipped: %d, Failed: %d",
response.Stats.Created, response.Stats.Updated, response.Stats.Deleted, response.Stats.Skipped, response.Stats.Failed)
} else {
log.Warn().Msgf("Failed to process file: %s, success: %t", path, response.Success)
}
} else {
log.Warn().Msgf("Failed to process file: %s, status code: %d", path, resp.StatusCode)
}
}
return nil
})
if foundGPCFile {
log.Info().Msgf("GPC Files found and uploaded. Starting automatic bank pairing for directory: %s", directory)
// Use regex to extract the base URL
re := regexp.MustCompile(`^(https:\/\/[^\/]+\/c\/[^\/]+\/)`)
matches := re.FindStringSubmatch(config.URL)
if len(matches) < 2 {
return fmt.Errorf("failed to extract base URL from %s", config.URL)
}
baseURL := matches[1]
pairingURL := baseURL + "banka/automaticke-parovani"
req, err := http.NewRequest("PUT", pairingURL, nil)
if err != nil {
return err
}
auth := config.Username + ":" + config.Password
encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Authorization", "Basic "+encodedAuth)
req.Header.Add("Content-Type", "application/xml")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var response Response
err := xml.NewDecoder(resp.Body).Decode(&response)
if err != nil {
return err
}
if response.Success {
log.Info().Msgf("Successfully paired transactions for directory: %s", directory)
log.Info().Msgf("Pairing Stats - Created: %d, Updated: %d, Deleted: %d, Skipped: %d, Failed: %d",
response.Stats.Created, response.Stats.Updated, response.Stats.Deleted, response.Stats.Skipped, response.Stats.Failed)
} else {
log.Warn().Msgf("Failed to pair transactions for directory: %s, success: %t", directory, response.Success)
}
} else {
log.Warn().Msgf("Failed to pair transactions for directory: %s, status code: %d", directory, resp.StatusCode)
}
}
return err
}
func processPaymentOrders(directory string, config *Config) error {
req, err := http.NewRequest("GET", config.URL+"/prikaz-k-uhrade/(stavPrikazK='elPrikazStav.vytvoren').json", nil)
if err != nil {
return err
}
auth := config.Username + ":" + config.Password
encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Authorization", "Basic "+encodedAuth)
req.Header.Add("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Warn().Msgf("Failed to check for payment orders on %s, with status code: %d", config.URL+"/prikaz-k-uhrade/(stavPrikazK='elPrikazStav.neodeslan').json", resp.StatusCode)
return nil
}
var paymentOrderResponse PaymentOrderResponse
err = json.NewDecoder(resp.Body).Decode(&paymentOrderResponse)
if err != nil {
return err
}
if len(paymentOrderResponse.Winstrom.PaymentOrders) == 0 {
log.Info().Msgf("No payment orders to download in directory %s", directory)
return nil
}
for _, order := range paymentOrderResponse.Winstrom.PaymentOrders {
orderID := order.ID
orderURL := fmt.Sprintf("%s/prikaz-k-uhrade/%s/stazeni?dat-splat-z-hlavicky=false", config.URL, orderID)
req, err := http.NewRequest("GET", orderURL, nil)
if err != nil {
return err
}
req.Header.Add("Authorization", "Basic "+encodedAuth)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
fileName := fmt.Sprintf("%s-%s.kpc", time.Now().Format("20060102150405"), orderID)
var filePath string
if runtime.GOOS == "windows" {
filePath = filepath.Join(directory+"\\kpc", fileName)
err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
if err != nil {
return err
}
} else {
filePath = filepath.Join(directory+"/kpc", fileName)
err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
if err != nil {
return err
}
}
outFile, err := os.Create(filePath)
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, resp.Body)
if err != nil {
return err
}
log.Info().Msgf("Successfully downloaded payment order %s to %s", orderID, filePath)
} else {
log.Warn().Msgf("Failed to download payment order %s, status code: %d", orderID, resp.StatusCode)
}
}
return nil
}
func processDirectories(directories []string, paymentOrderDirs []string) {
for _, dir := range directories {
configPath := filepath.Join(dir, "config.yaml")
config, err := loadConfig(configPath)
if err != nil {
log.Warn().Msgf("Skipping directory %s: %v", dir, err)
continue
}
log.Info().Msgf("Starting processing for directory %s.", dir)
err = processFiles(dir, config)
if err != nil {
log.Error().Msgf("Error processing directory %s: %v", dir, err)
} else {
log.Info().Msgf("Processing completed successfully for directory %s.", dir)
}
}
for _, dir := range paymentOrderDirs {
configPath := filepath.Join(dir, "config.yaml")
config, err := loadConfig(configPath)
if err != nil {
log.Warn().Msgf("Skipping payment order directory %s: %v", dir, err)
continue
}
log.Info().Msgf("Starting processing of payment orders for directory %s.", dir)
err = processPaymentOrders(dir, config)
if err != nil {
log.Error().Msgf("Error processing payment order directory %s: %v", dir, err)
} else {
log.Info().Msgf("Processing of payment orders completed successfully for directory %s.", dir)
}
}
}
func getDirectories() ([]string, []string) {
centralConfigPath := filepath.Join(filepath.Dir(os.Args[0]), "central_config.yaml")
centralConfig, err := loadCentralConfig(centralConfigPath)
if err == nil {
log.Info().Msg("Using central config for directories.")
return centralConfig.Directories, centralConfig.PaymentOrderDirectories
}
log.Error().Msgf("Loading config error: %v", err)
log.Info().Msg("Using environment variables for directories.")
var directories, paymentOrderDirs []string
for i := 1; ; i++ {
dir := os.Getenv(fmt.Sprintf("DIR_%d", i))
if dir == "" {
break
}
directories = append(directories, dir)
}
for i := 1; ; i++ {
dir := os.Getenv(fmt.Sprintf("PAYMENT_ORDER_DIR_%d", i))
if dir == "" {
break
}
paymentOrderDirs = append(paymentOrderDirs, dir)
}
return directories, paymentOrderDirs
}
func main() {
centralConfigPath := filepath.Join(filepath.Dir(os.Args[0]), "central_config.yaml")
centralConfig, err := loadCentralConfig(centralConfigPath)
var logFile *os.File
if err == nil && centralConfig.LogToFile {
logFile, err = os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Printf("Failed to open log file: %v", err)
return
}
defer logFile.Close()
multi := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, logFile)
log.Logger = zerolog.New(multi).With().Timestamp().Logger()
} else {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Timestamp().Logger()
}
zerolog.TimeFieldFormat = time.RFC3339
log.Info().Msg("Starting initial processing of directories.")
directories, paymentOrderDirs := getDirectories()
processDirectories(directories, paymentOrderDirs)
log.Info().Msg("Starting ticker for scheduled processing of directories.")
ticker := time.NewTicker(30 * time.Minute)
defer ticker.Stop()
for range ticker.C {
log.Info().Msg("Starting scheduled processing of directories.")
processDirectories(directories, paymentOrderDirs)
}
}