-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
425 lines (376 loc) · 10.8 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package main
import (
"bufio"
"bytes"
"encoding/csv"
"flag"
"fmt"
"github.com/cheggaaa/pb/v3"
"github.com/clarketm/json"
"github.com/google/uuid"
"github.com/nleeper/goment"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
)
const ExbicoLeadApiUrl = "https://app.exbico.ru/api/leads/supplier/v1/credit-lead"
const FileWithLeadsName = "leads.csv"
const MaxThreadsCount = 10
var apiUrl string
var debugMode bool
var leadFilePath string
var outputFileName string
var threads int
var token string
func main() {
if threads > MaxThreadsCount {
log.Fatal(fmt.Sprintf("Количество потоков должно быть не больше %d.", MaxThreadsCount))
}
records, err := readData(leadFilePath)
if err != nil {
if debugMode {
log.Println(err)
}
log.Fatal("Файл с лидами имеет неправильный формат. Он должен быть в формате csv с разделителем `,`")
}
fileLinesCount, err := calcCsvFileLinesCount(leadFilePath)
bar := pb.StartNew(fileLinesCount)
setOutputFileName()
writeHeadLineIntoOutputFile()
jobs := new(sync.Map)
results := new(sync.Map)
wg := new(sync.WaitGroup)
for _, record := range records {
addLeadToMap(record, jobs)
}
fmt.Println("Отправка данных...")
maxHashMapLengthForWorker := len(records) / threads
chunkedHashMap := make(map[string]recordProcessingElement)
jobs.Range(func(k, v interface{}) bool {
element := v.(recordProcessingElement)
chunkedHashMap[fmt.Sprintf("%s", k)] = element
if len(chunkedHashMap) == maxHashMapLengthForWorker {
clonedHashMap := make(map[string]recordProcessingElement)
for key, value := range chunkedHashMap {
clonedHashMap[key] = value
delete(chunkedHashMap, key)
}
wg.Add(1)
go worker(clonedHashMap, token, results, wg, bar)
}
return true
})
if len(chunkedHashMap) > 0 {
wg.Add(1)
go worker(chunkedHashMap, token, results, wg, bar)
}
wg.Wait()
bar.Finish()
writeResults(fileLinesCount, results)
fileLinesCount, err = calcCsvFileLinesCount(outputFileName)
exitProgram()
}
func addLeadToMap(record []string, jobs *sync.Map) {
var uuidString uuid.UUID
uuidString, _ = uuid.NewRandom()
lead := prepareLead(record)
recordProcessingElement := recordProcessingElement{
Record: record,
Lead: lead,
}
jobs.Store(uuidString, recordProcessingElement)
}
func worker(hashMap map[string]recordProcessingElement, token string, results *sync.Map, wg *sync.WaitGroup, bar *pb.ProgressBar) {
defer wg.Done()
for key, recordProcessingElement := range hashMap {
if debugMode {
leadJson, _ := json.Marshal(recordProcessingElement.Lead)
fmt.Println(string(leadJson))
}
status, response := sendLead(recordProcessingElement.Lead, token)
asyncResult := recordProcessingResult{
Record: recordProcessingElement.Record,
Lead: recordProcessingElement.Lead,
Status: status,
Data: response.Data,
Message: response.Message,
}
results.Store(key, asyncResult)
bar.Increment()
}
}
func writeResults(fileLinesCount int, results *sync.Map) {
fmt.Println("Сохранение результата...")
bar := pb.StartNew(fileLinesCount)
results.Range(func(k, v interface{}) bool {
recordProcessingResult := v.(recordProcessingResult)
leadStatus := recordProcessingResult.Data.LeadStatus
rejectReason := recordProcessingResult.Data.RejectReason
leadId := recordProcessingResult.Data.LeadId
var leadIdString string
if leadId > 0 {
leadIdString = strconv.Itoa(recordProcessingResult.Data.LeadId)
}
err := writeResultCsv(
recordProcessingResult.Record,
translateResponseStatus(recordProcessingResult.Status),
translateLeadStatus(leadStatus),
translateRejectionReason(rejectReason),
leadIdString,
recordProcessingResult.Message,
)
if err != nil {
if debugMode {
log.Println(err)
}
}
bar.Increment()
return true
})
bar.Finish()
fmt.Println("Результат сохранён в файл " + outputFileName)
}
func translateResponseStatus(status string) string {
dict := map[string]string{
"success": "Успех",
"fail": "Ошибка данных",
"error": "Ошибка сервера",
}
return applyTranslation(dict, status)
}
func translateLeadStatus(leadStatus string) string {
dict := map[string]string{
"inProgress": "Принят",
"rejected": "Не принят",
}
return applyTranslation(dict, leadStatus)
}
func translateRejectionReason(rejectionReason string) string {
dict := map[string]string{
"isDouble": "Дубль",
}
return applyTranslation(dict, rejectionReason)
}
func applyTranslation(dictMap map[string]string, valueToTranslate string) string {
result := valueToTranslate
value, exists := dictMap[valueToTranslate]
if exists {
result = value
}
return result
}
func writeHeadLineIntoOutputFile() {
headLine := []string{"Фамилия", "Имя", "Отчество", "Дата рождения", "Возраст", "Телефон", "E-mail", "Сумма кредита", "Срок кредита", "Регион", "Город", "Серия паспорта", "Номер паспорта", "Дата выдачи паспорта"}
err := writeResultCsv(headLine, "Результат отправки", "Лид принят", "Причина отбраковки лида", "ID лида", "Дополнительная информация по приёму лида")
if err != nil {
if debugMode {
log.Println(err)
}
}
}
func setOutputFileName() {
if outputFileName == "" {
outputFileName = fmt.Sprintf("result_%s.csv", time.Now().Format("2006-01-02_15_04_05"))
}
}
func writeResultCsv(record []string, leadSendingResult string, leadStatus string, rejectionReason string, leadId string, leadErrorsString string) error {
file, err := os.OpenFile(outputFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
checkError("Cannot create file", err)
record = append(record, leadSendingResult, leadStatus, rejectionReason, leadId, leadErrorsString)
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Fatal(err)
}
}(file)
writer := csv.NewWriter(file)
defer writer.Flush()
err = writer.Write(record)
if err != nil {
return err
}
return nil
}
func checkError(message string, err error) {
if err != nil {
log.Fatal(message, err)
}
}
func prepareLead(record []string) Lead {
var lead = Lead{}
lead.Client.LastName = record[0]
lead.Client.FirstName = record[1]
lead.Client.Patronymic = record[2]
if record[3] != "" {
lead.Client.BirthDate = formatDate(record[3])
}
if record[4] != "" {
age, _ := strconv.Atoi(record[4])
lead.Client.Age = age
}
lead.Client.Phone = record[5]
lead.Client.Email = record[6]
lead.Product.TypeId = "consumer"
amount, _ := strconv.Atoi(record[7])
lead.Product.Amount = amount
lead.Product.Term = record[8]
lead.Location.Name.Region = record[9]
lead.Location.Name.City = record[10]
lead.Passport.Series = record[11]
lead.Passport.Number = record[12]
if record[13] != "" {
lead.Passport.IssueDate = formatDate(record[13])
}
return lead
}
func init() {
initFlags()
initToken()
}
func initToken() {
if token == "" {
tokenFromFile, err := getToken()
if err != nil {
log.Fatal(err)
}
token = tokenFromFile
}
if len(token) != 32 {
log.Fatal("Токен должен содержать ровно 32 символа (в файле token.txt)")
}
}
func initFlags() {
apiUrlPointer := flag.String("apiUrl", ExbicoLeadApiUrl, "url of Exbico Lead Api")
debugModePointer := flag.Bool("debug", false, "enable debug mode")
threadsPointer := flag.Int("threads", 2, fmt.Sprintf("number of parallel threads (max=%d)", MaxThreadsCount))
leadFilePathPointer := flag.String("leadFilePath", FileWithLeadsName, "path to csv-file with leads")
tokenPointer := flag.String("token", "", "token to Exbico Leads API")
flag.Parse()
apiUrl = *apiUrlPointer
debugMode = *debugModePointer
threads = *threadsPointer
leadFilePath = *leadFilePathPointer
token = *tokenPointer
}
func formatDate(date string) string {
var t *goment.Goment
t, _ = goment.New(date)
if t.ToUnix() < 0 {
t, _ = goment.New(date, "DD.MM.YYYY")
}
return t.Format("YYYY-MM-DD")
}
func sendLead(lead Lead, token string) (string, LeadSendingResponse) {
leadJson, _ := json.Marshal(lead)
req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(leadJson))
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Tool-Version", "v1")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Fatal(err)
}
}(resp.Body)
body, _ := ioutil.ReadAll(resp.Body)
if debugMode {
fmt.Println("request Url:", req.URL)
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", string(body))
}
return parseResponseBody(body, resp.StatusCode)
}
func parseResponseBody(body []byte, statusCode int) (string, LeadSendingResponse) {
response := LeadSendingResponse{}
if statusCode == 200 {
err := json.Unmarshal(body, &response)
if err != nil && debugMode {
fmt.Println(err)
}
} else {
response.Status = "error"
}
return response.Status, response
}
func readData(fileName string) ([][]string, error) {
f, err := os.Open(fileName)
if err != nil {
return [][]string{}, err
}
defer func(f *os.File) {
err := f.Close()
if err != nil {
log.Fatal(err)
}
}(f)
r := csv.NewReader(f)
// skip first line
firstLineRows, err := r.Read()
checkFileEncoding(firstLineRows)
if err != nil {
return [][]string{}, err
}
records, err := r.ReadAll()
if err != nil {
return [][]string{}, err
}
return records, nil
}
func checkFileEncoding(rows []string) {
if rows[0] != "Фамилия" {
log.Fatal("В файле leads.csv указана неверная кодировка. " +
"Необходимо преобразовать файл в кодировку UTF-8 без BOM.")
}
}
func getToken() (string, error) {
tokenFile, err := os.Open("token.txt")
if err != nil {
log.Fatal(err)
}
var token string
scanner := bufio.NewScanner(tokenFile)
for scanner.Scan() {
token = scanner.Text()
}
return token, err
}
func calcCsvFileLinesCount(fileName string) (int, error) {
r, err := os.Open(fileName)
if err != nil {
log.Fatal(err)
}
defer func(f *os.File) {
err := f.Close()
if err != nil {
log.Fatal(err)
}
}(r)
buf := make([]byte, 32*1024)
count := 0
lineSep := []byte{'\n'}
for {
c, err := r.Read(buf)
count += bytes.Count(buf[:c], lineSep)
switch {
case err == io.EOF:
return count, nil
case err != nil:
return count, err
}
}
}
func exitProgram() {
fmt.Println("Нажмите клавишу Enter для завершения работы программы...")
_, _ = fmt.Scanln()
}