-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.go
1641 lines (1262 loc) · 36.5 KB
/
functions.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package helpers
import (
"bytes"
"compress/gzip"
"compress/zlib"
"context"
"crypto/rand"
"database/sql"
"encoding/csv"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
math_rand "math/rand"
"net/http"
"net/mail"
"os"
"os/exec"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/araddon/dateparse"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/fatih/structs"
models "github.com/oluwapaso/hd_models"
"golang.org/x/crypto/bcrypt"
"golang.org/x/net/html"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"golang.org/x/text/message"
"mvdan.cc/xurls/v2"
)
const APP_NAME = "Hauling Desk"
const BASE_URL = "https://local.haulingdesk.com" //https://haulingdesk.com
const CRM_URL = "https://yaimalamela.com" //http://local.muvcars.com //https://crm.haulingdesk.com //https://yaimalamela.com
const API_URL = "http://rqeejaczw2.execute-api.us-east-1.amazonaws.com/HaulingDeskGoAPI" //http://local.muvcars.com/api/v1/router
const DEVELOPERS_LINK = "https://main.d3bzogxvbyj700.amplifyapp.com/"
const EMAIL_TRACKER_LINK = BASE_URL + "/track-open-rates.php"
const EMAIL_CLICK_TRACKER_LINK = BASE_URL + "/track-click-rates.php"
const YYYY_MM_DD__HHMMSS string = "2006-01-02 15:04:05"
const YYYY_MM_DD string = "2006-01-02"
const HH_MM_SS string = "15:04:05"
const MM_DD_YYYY string = "01-02-2006"
const DD_MM_YYYY string = "02-01-2006"
const MM_DD_YYYY__gi_A string = "01-02-2006 3:4 PM"
const F_d_Y string = "January 02, 2006"
const AUTOMATED_EMAIL_LOGO = "https://cronetic.com/crm/img/powered-by-v2.png"
const COMP_ADDRESS = "7807 W Loop 1604 N San Antonio, TX 78254"
const SHIPPERS_PORTAL_URL = "https://shippers.hauling-desk.com" //https://shippers.hauling-desk.com //https://shippers.haulingdesk.com
const CARRIERS_PORTAL_URL = "https://carriers.hauling-desk.com" //https://carriers.hauling-desk.com //https://carriers.haulingdesk.com
const HD_SENDGRID_KEY = "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"
const HD_NOTIFICATIONS_EMAIL = "[email protected]"
const SUPPORT_EMAIL = "[email protected]"
const SUPPORT_PHONE = "+2348062744512"
const ACCOUNTS_EMAIL = "[email protected]"
const GIT_TOKEN = "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"
const LOGO_BUCKETS = "hauling-desk-logos"
const AGENTS_DP_BUCKETS = "hauling-desk-agents-dp"
const DEAL_FILES_BUCKETS = "hauling-desk-deal-files"
const CONTACTS_FILES_BUCKETS = "hauling-desk-contacts-files"
const CSV_FILES_BUCKETS = "hauling-csv-files"
const TWILIO_ACCOUNT_SID = "AC9c7d25d759ec866710c2b38245c54893"
const TWILIO_AUTH_TOKEN = "d3f7c21920ca9635a2ec7ee157088997"
const TWILIO_TWIML_SID = "APd7fda7e62f8312c6db3cf71ea3c470f1"
const TWILIO_CALL_PER_MIN = 1 //Twilio: $0.0040/Min = 250 min in $1 => HD $1 = 125 Min
const TWILIO_SMS_PER_PAGE = 2 //Twilio: $0.0079/Page = 126 pages in $1 => HD $1 = 63 Pages
const IP_ADDRESS = "209.182.198.166" //yailamela(209.182.198.166)
const CPANEL_HOME_DIRECTORY = "/home/profe160" //yailamela(/home/profe160)
const CPANEL_FULL_PATH = "../" //yailamela(/home2/profe160/public_html/crm) //../ (Local)
const LEAD_PIPING_SCRIPT = "/home/profe160/public_html/cron_jobs/cron_forwarder.php"
const WEBMAIL_PIPING_SCRIPT = "/home/profe160/public_html/cron_jobs/incoming_email_parser.php"
const CPANEL_USERNAME = "profe160" //yailamela(profe160)
const CPANEL_PASSWORD = "7i(&V)+BO)G+" //yailamela(7i(&V)+BO)G+)
const EMAIL_DOMAIN = "yaimalamela.com"
const XML_API_PORT = "2083"
func HandlePanic(via string) {
if r := recover(); r != nil {
fmt.Printf("\nRecovered from %s \npanic: %v", via, r)
//fmt.Printf("\nRecovered from %s \npanic: %v \nstack trace: %s", via, r, string(debug.Stack()))
}
}
func ParseInt(val interface{}) int {
intVal, _ := strconv.Atoi(fmt.Sprint(val))
return intVal
}
func NumWithDot(value interface{}) string {
pattern := regexp.MustCompile(`[^0-9.]`)
return pattern.ReplaceAllString(fmt.Sprint(value), "")
}
func MappStructToScannedFields(rows *sql.Rows, columns []string) (map[string]interface{}, error) {
values := make([]interface{}, len(columns))
pointers := make([]interface{}, len(columns))
for i, _ := range values {
pointers[i] = &values[i]
}
resultMap := make(map[string]interface{})
err := rows.Scan(pointers...)
if err != nil {
return resultMap, err
}
for i, val := range values {
resultMap[columns[i]] = val
}
return resultMap, nil
}
func ReadCsvFile(filePath string) [][]string {
f, err := os.Open(filePath)
if err != nil {
log.Fatal("Unable to read input file "+filePath, err)
}
defer f.Close()
csvReader := csv.NewReader(f)
records, err := csvReader.ReadAll()
if err != nil {
log.Fatal("Unable to parse file as CSV for "+filePath, err)
}
return records
}
func ReadCSVFromUrl(url string) ([][]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
csvReader := csv.NewReader(resp.Body)
//csvReader.Comma = ';'
csvReader.LazyQuotes = true
data, err := csvReader.ReadAll()
if err != nil {
return nil, err
}
return data, nil
}
func ParseToDatetime(value string) string {
layout, _ := dateparse.ParseFormat(value)
date, _ := time.Parse(layout, value)
ret_date := date.Format(YYYY_MM_DD__HHMMSS)
return fmt.Sprint(ret_date)
}
func ParseToDate(value string) string {
layout, _ := dateparse.ParseFormat(value)
date, _ := time.Parse(layout, value)
ret_date := date.Format(YYYY_MM_DD)
return fmt.Sprint(ret_date)
}
func GetDateLayout(date string) string {
var delimeter string
if strings.Contains(date, "/") {
delimeter = "/"
} else if strings.Contains(date, "-") {
delimeter = "-"
} else {
return ""
}
//date = strings.ReplaceAll(date, "/", "-")
splitSpace := strings.Split(date, " ")
val := strings.Split(splitSpace[0], delimeter)
if len(val) < 1 {
return ""
}
var (
format string
)
mm_dd_ptrn := regexp.MustCompile(`[0-9]{2}` + delimeter + `[0-9]{2}` + delimeter + `[0-9]{4}`)
mm_dd_indices := mm_dd_ptrn.FindAllStringIndex(date, 1)
mm_dd_found := len(mm_dd_indices)
if mm_dd_found > 0 {
val_1 := ParseInt(val[0]) //first value
if val_1 <= 12 {
//mm-dd-yyyy
format = "01" + delimeter + "02" + delimeter + "2006"
} else {
//dd-mm-yyyy
format = "02" + delimeter + "01" + delimeter + "2006"
}
}
yy_mm_dd_ptrn := regexp.MustCompile(`[0-9]{4}` + delimeter + `[0-9]{2}` + delimeter + `[0-9]{2}`)
yy_mm_dd_indices := yy_mm_dd_ptrn.FindAllStringIndex(date, 1)
yy_mm_dd_found := len(yy_mm_dd_indices)
if yy_mm_dd_found > 0 {
val_2 := ParseInt(val[1]) //second value
if val_2 <= 12 {
//yyyy-mm-dd
format = "2006" + delimeter + "01" + delimeter + "02"
} else {
//yyyy-dd-mm
format = "2006" + delimeter + "02" + delimeter + "01"
}
}
//Time part
if len(splitSpace) > 1 {
hh_mm_ss_ptrn := regexp.MustCompile(`[0-9]{2}:[0-9]{2}:[0-9]{2}`)
hh_mm_ss_indices := hh_mm_ss_ptrn.FindAllStringIndex(date, 1)
hh_mm_ss_found := len(hh_mm_ss_indices)
if hh_mm_ss_found > 0 {
format += " 15:04:05"
}
}
return format
}
func ParseDateToFormat(value string, format string, layout string) string {
date, _ := time.Parse(layout, value)
ret_date := date.Format(format)
return fmt.Sprint(ret_date)
}
func Parse_Date_To_A_Format(value, format string) string {
layout, _ := dateparse.ParseFormat(value)
date, _ := time.Parse(layout, value)
ret_date := date.Format(format)
return fmt.Sprint(ret_date)
}
func Date(format string) string {
date_format := YYYY_MM_DD__HHMMSS
if format == "YYYY-MM-DD H:i:s" {
date_format = YYYY_MM_DD__HHMMSS
} else if format == "YYYY-MM-DD" {
date_format = YYYY_MM_DD
} else if format == "H:i:s" {
date_format = HH_MM_SS
} else if format == "F d, Y" {
date_format = "January 02, 2006"
} else if format == "M DD, YY" {
date_format = "Jan 02, 2006"
} else if format == "MM-DD-YYYY" {
date_format = "01-02-2006"
} else if format == "YYYY" {
date_format = "2006"
} else if format == "MM" {
date_format = "01"
} else if format == "DD" {
date_format = "02"
}
date := time.Now().Format(date_format)
return fmt.Sprint(date)
}
func DateInLoc(format string, loc *time.Location) string {
date_format := YYYY_MM_DD__HHMMSS
if format == "YYYY-MM-DD H:i:s" {
date_format = YYYY_MM_DD__HHMMSS
} else if format == "YYYY-MM-DD" {
date_format = YYYY_MM_DD
} else if format == "H:i:s" {
date_format = HH_MM_SS
} else if format == "F d, Y" {
date_format = "January 02, 2006"
} else if format == "M DD, YY" {
date_format = "Jan 02, 2006"
} else if format == "MM-DD-YYYY" {
date_format = "01-02-2006"
} else if format == "YYYY" {
date_format = "2006"
} else if format == "MM" {
date_format = "01"
} else if format == "DD" {
date_format = "02"
}
date := time.Now().In(loc).Format(date_format)
return fmt.Sprint(date)
}
func GetSpecificDate(format string, offset int) string {
date_format := YYYY_MM_DD__HHMMSS
if format == "YYYY-MM-DD H:i:s" {
date_format = YYYY_MM_DD__HHMMSS
} else if format == "YYYY-MM-DD" {
date_format = YYYY_MM_DD
} else if format == "MM-DD-YYYY" {
date_format = "01-02-2006"
}
date := time.Now().AddDate(0, 0, offset).Format(date_format)
return fmt.Sprint(date)
}
func GetSpecificDateInLoc(format string, offset int, loc *time.Location) string {
date_format := YYYY_MM_DD__HHMMSS
if format == "YYYY-MM-DD H:i:s" {
date_format = YYYY_MM_DD__HHMMSS
} else if format == "YYYY-MM-DD" {
date_format = YYYY_MM_DD
} else if format == "MM-DD-YYYY" {
date_format = "01-02-2006"
}
date := time.Now().In(loc).AddDate(0, 0, offset).Format(date_format)
return fmt.Sprint(date)
}
func GetDateOffsetInLoc(format string, offset int, loc *time.Location, date time.Time) string {
date_format := YYYY_MM_DD__HHMMSS
if format == "YYYY-MM-DD H:i:s" {
date_format = YYYY_MM_DD__HHMMSS
} else if format == "YYYY-MM-DD" {
date_format = YYYY_MM_DD
} else if format == "MM-DD-YYYY" {
date_format = "01-02-2006"
}
new_date := date.In(loc).AddDate(0, 0, offset).Format(date_format)
return new_date
}
func StringToTime(value string) int64 {
layout, _ := dateparse.ParseFormat(value)
date, _ := time.Parse(layout, value)
timestamp := date.Unix()
return timestamp
}
func Ucwords(input string) string {
caser := cases.Title(language.English)
return caser.String(strings.ToLower(input))
}
func RemoveNoneNumerics(value string) string {
none_numeric := regexp.MustCompile(`[^0-9]+`)
return none_numeric.ReplaceAllString(value, "")
}
func RemoveNoneAlphabets(value string) string {
alphabets := regexp.MustCompile(`[^A-Za-z]+`)
return alphabets.ReplaceAllString(value, "")
}
func PregReplace(value, pattern, replace_with string) string {
none_numeric := regexp.MustCompile(pattern)
return none_numeric.ReplaceAllString(value, replace_with)
}
func PregMatch(value, pattern string) string {
// Compile the regular expression
re := regexp.MustCompile(pattern)
// Find the match in the input string
match := re.FindStringSubmatch(value)
// Check if there is a match
if len(match) > 0 {
return match[0]
} else {
return ""
}
}
func GetTextBetween(input, start, end string) (string, error) {
// Create the regular expression pattern
pattern := fmt.Sprintf("%s(.*?)%s", regexp.QuoteMeta(start), regexp.QuoteMeta(end))
// Compile the regular expression
re := regexp.MustCompile(pattern)
// Find the match in the input string
match := re.FindStringSubmatch(input)
if len(match) >= 2 {
// Return the text between the start and end strings
return match[1], nil
}
// Return an error if no match is found
return "", fmt.Errorf("no match found between '%s' and '%s'", start, end)
}
func UsaPhoneNumber(value string) string {
number := RemoveNoneNumerics(value)
sn := strings.Split(number, "")
var (
part_1 string
part_2 string
part_3 string
)
for i, val := range sn {
if i <= 2 {
part_1 += val
}
if i > 2 && i <= 5 {
part_2 += val
}
if i > 5 && i <= 9 {
part_3 += val
}
}
return fmt.Sprintf("(%s) %s-%s", part_1, part_2, part_3)
}
func LastNumOfCharacters(val string, length int) string {
var result string
if len(val) >= length {
result = val[len(val)-length:]
} else {
result = val
}
return result
}
func UnformattedPhoneNumber(number string) string {
clean := RemoveNoneNumerics(number)
phn_number := LastNumOfCharacters(clean, 10)
return fmt.Sprint(phn_number)
}
func ParsePhoneForSMS(number string) string {
number = UnformattedPhoneNumber(number)
if number != "" {
number = "1" + number
}
return number
}
func ParseVehicles(vehicles string) []models.Vehicles {
/** Returns array **/
var parsed_vehicles []models.Vehicles
if vehicles != "" {
eploded_vehicles := strings.Split(vehicles, ",")
vehicle_id := 1
for _, veh := range eploded_vehicles {
veh = strings.TrimSpace(veh)
var vehicleLine models.Vehicles
if veh != "" {
eachVeh := strings.Split(veh, " ")
vehicle_year := strings.TrimSpace(eachVeh[0])
vehicle_make := strings.TrimSpace(eachVeh[1])
yr_mk := vehicle_year + " " + vehicle_make
vehicle_model := strings.TrimSpace(strings.ReplaceAll(veh, yr_mk, ""))
vehicleLine.Vehicle_id = ParseInt(vehicle_id)
vehicleLine.Year = ParseInt(vehicle_year)
vehicleLine.Make = Ucwords(vehicle_make)
vehicleLine.Model = Ucwords(vehicle_model)
vehicleLine.Full_vehicle = fmt.Sprintf("%d %s %s", ParseInt(vehicle_year), Ucwords(vehicle_make), Ucwords(vehicle_model))
vehicle_id++
parsed_vehicles = append(parsed_vehicles, vehicleLine)
}
}
return parsed_vehicles
} else {
return parsed_vehicles
}
}
func SubStr(str string, start, end int) string {
return strings.TrimSpace(str[start:end])
}
func RemoveMultipleSpace(value string) string {
space := regexp.MustCompile(`!\s+!`)
result := space.ReplaceAllString(value, " ")
result = strings.TrimSpace(result)
return result
}
func ParseStateCityZip(value string) string {
var (
zipCode string = ""
state string = ""
city string = ""
)
if value != "" {
zip_ptrn := regexp.MustCompile(`[0-9]{6}|[0-9]{5}`)
zip_indices := zip_ptrn.FindAllStringIndex(value, 1)
zipFound := len(zip_indices)
if zipFound > 0 {
zip_start := zip_indices[0][0]
zip_end := zip_indices[0][1]
zipCode = SubStr(value, zip_start, zip_end)
}
state_ptrn := regexp.MustCompile(`\s[A-Za-z]{2}\s|\s[A-Za-z]{2},|,[A-Za-z]{2},|,[A-Za-z]{2}\s,|,[A-Za-z]{2}\s|,\s[A-Za-z]{2}$|,[A-Za-z]{2}$`)
state_indices := state_ptrn.FindAllStringIndex(value, 1)
stateFound := len(state_indices)
if stateFound > 0 {
state_start := state_indices[0][0]
state_end := state_indices[0][1]
state = SubStr(value, state_start, state_end)
state = strings.ReplaceAll(state, ",", "")
state = RemoveMultipleSpace(state)
}
city = strings.ReplaceAll(value, zipCode, "")
city = strings.ReplaceAll(city, state, "")
city = strings.ReplaceAll(city, ",", "")
city = RemoveMultipleSpace(city)
}
return fmt.Sprintf("%s, %s, %d", Ucwords(city), strings.ToUpper(state), ParseInt(zipCode))
}
// map[string]map[string]interface{}
// func ArrayColumn(input []models.Agents, columnKey string) []interface{} {
// var columns []interface{}
// columns = make([]interface{}, 0, len(input))
// for _, val := range input {
// mappedAgnts := structs.Map(val)
// fmt.Printf("\nValue: %v - Key: %s", mappedAgnts[columnKey], columnKey)
// if v, ok := mappedAgnts[columnKey]; ok {
// columns = append(columns, v)
// }
// }
// return columns
// }
type ArrColInterface interface {
models.Agents | models.LeadSource | models.MappedImportStatus | models.MappedLeadSource | models.ImportDealHeader | models.Vehicles |
models.Issues
}
func ArrayColumn[T ArrColInterface](input []T, columnKey string) []interface{} {
var columns []interface{}
columns = make([]interface{}, 0, len(input))
for _, val := range input {
to_map := structs.Map(val)
if v, ok := to_map[columnKey]; ok {
columns = append(columns, v)
}
}
return columns
}
func ArraySearch(needle interface{}, hystack interface{}) (index int) {
index = -1
switch reflect.TypeOf(hystack).Kind() {
case reflect.Slice:
s := reflect.ValueOf(hystack)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(needle, s.Index(i).Interface()) == true {
index = i
return
}
}
}
return
}
func GetArrayKeyIndex[T ArrColInterface](value interface{}, array *[]T, column string) int {
index := ArraySearch(value, ArrayColumn(*array, column))
return index
}
func ValidateEmailAddress(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
func GenerateSecureToken(length int) string {
b := make([]byte, length)
if _, err := rand.Read(b); err != nil {
return ""
}
return hex.EncodeToString(b)
}
func StringWithCharset(length int, charset string, seededRand *math_rand.Rand) string {
math_rand.Seed(time.Now().UnixNano())
seededRand = math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}
func RandomChars(length int) string {
seededRand := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
const charset = "ABCDKLM028983NOEF2661982GHIJ8272PQTUV128882WXYRSZA89283BCD484EFGHI033JKLMNOPQRSTUVWXYZ0123456789"
return StringWithCharset(length, charset, seededRand)
}
func RandomInts(length int) string {
seededRand := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
const charset = "92-391729812-8387378309833-97209-37923-38-182273877-9238732-9281292391" +
"20423636838-9309893323-7376389347-467849474"
return StringWithCharset(length, charset, seededRand)
}
func ParseCSVField(row map[string]string, key string, dataHeaders []models.ImportDealHeader) string {
var isSkipped string = "true"
var isMatched string = "false"
var fieldVal string = ""
header_index := GetArrayKeyIndex(key, &dataHeaders, "Id")
if header_index > -1 {
isSkipped = dataHeaders[header_index].Skip
isMatched = dataHeaders[header_index].Matched
}
if isSkipped == "false" && isMatched == "true" {
fieldVal = row[key]
}
return strings.TrimSpace(fieldVal)
}
func GzInflate(val []byte) string {
reader := bytes.NewReader(val)
gzreader, e1 := gzip.NewReader(reader)
if e1 != nil {
fmt.Println(e1) // Maybe panic here, depends on your error handling.
}
fmt.Println(gzreader)
output, e2 := io.ReadAll(gzreader)
if e2 != nil {
fmt.Println(e2)
}
return string(output)
}
func ReadGzip(content []byte) error {
var buf *bytes.Buffer = bytes.NewBuffer(content)
fmt.Printf(fmt.Sprint(buf))
gRead, err := zlib.NewReader(buf)
if err != nil {
return err
}
if t, err := io.Copy(os.Stdout, gRead); err != nil {
fmt.Println(t)
return err
}
if err := gRead.Close(); err != nil {
return err
}
return nil
}
func Json_encode(data interface{}) (string, error) {
jsons, err := json.Marshal(data)
return string(jsons), err
}
func Json_decode(data string) (map[string]interface{}, error) {
dat := map[string]interface{}{}
err := json.Unmarshal([]byte(data), &dat)
return dat, err
}
func Json_encode_decode(data interface{}) (map[string]interface{}, error) {
jsons, err := json.Marshal(data)
if err != nil {
return nil, err
}
dat := map[string]interface{}{}
err = json.Unmarshal(jsons, &dat)
return dat, err
}
func Json_decode_array(data string) []interface{} {
jsonArray := []interface{}{}
json.Unmarshal([]byte(data), &jsonArray)
return jsonArray
}
func String_To_Array(data string) ([]interface{}, error) {
dat := []interface{}{}
err := json.Unmarshal([]byte(data), &dat)
return dat, err
}
func Array_To_String(array []interface{}, delimeter string) string {
result := ""
for _, arr := range array {
result += fmt.Sprint(arr) + "" + delimeter
}
result = strings.TrimRight(result, delimeter)
return result
}
func IsJSON(s string) bool {
var js interface{}
return json.Unmarshal([]byte(s), &js) == nil
}
func IsArray(val interface{}) bool {
_, ok := val.([]interface{})
if !ok {
return false
}
return true
}
func ScanMultiRow(columns []string, rows *sql.Rows) ([]interface{}, error) {
count := len(columns)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for i := range columns {
valuePtrs[i] = &values[i] //set to memory address of values
}
err := rows.Scan(valuePtrs...)
return values, err
}
func ColValue(scanned_val []interface{}, index int) string {
val := scanned_val[index]
b, ok := val.([]byte)
var value interface{}
if ok {
value = string(b)
} else {
value = val
}
output := fmt.Sprint(value)
if output == "<nil>" {
output = ""
}
return output
}
func JsonColValue(scanned_val []interface{}, index int) interface{} {
val := scanned_val[index]
b, ok := val.([]byte)
var value interface{}
if ok {
value = string(b)
} else {
value = val
}
output := fmt.Sprint(value)
if output == "<nil>" {
output = ""
}
var json_output map[string]interface{}
if output != "" {
json_output, _ = Json_decode(output)
}
return json_output
}
func JsonArrayColValue(scanned_val []interface{}, index int) interface{} {
val := scanned_val[index]
b, ok := val.([]byte)
var value interface{}
if ok {
value = string(b)
} else {
value = val
}
output := fmt.Sprint(value)
if output == "<nil>" {
output = ""
}
var json_output []interface{}
if output != "" {
json_output = Json_decode_array(output)
}
return json_output
}
func ValToEmptyJson(val string) string {
if val == "" {
val = "{}"
}
return val
}
func ArrayColValue(scanned_val []interface{}, index int) interface{} {
val := scanned_val[index]
b, ok := val.([]byte)
var value interface{}
if ok {
value = string(b)
} else {
value = val
}
output := fmt.Sprint(value)
if output == "<nil>" {
output = ""
}
var json_output []interface{}
if output != "" {
json_output, _ = String_To_Array(output)
}
return json_output
}
func BuildSingleSelectColumns(fields []interface{}, model_fields string) string {
var fieldVal string
var query_fields string
for _, column := range fields {
if column != "" && column != "*" {
/** OrdersField is inside table_columns.go **/
column := strings.TrimSpace(fmt.Sprint(column))
exploded_orders_fld := strings.Split(string(model_fields), ",")
if In_array(column, exploded_orders_fld) {
fieldVal += column + ","
}
}
}
field_val := ArrayUnique(strings.Split(fieldVal, ","))
for _, val := range field_val {
if val != "" && val != "*" {
query_fields += val + ","
}
}
query_fields = strings.TrimRight(query_fields, ",")
return query_fields
}
func MultiTableSelCols(joiner, columns string) string {
var output string
split := strings.Split(columns, ",")
for _, val := range split {
val = strings.TrimSpace(val)
if val != "" {
output += joiner + "." + val + ","
}
}
output = strings.TrimRight(output, ",")
return output
}
func In_array(needle interface{}, hystack interface{}) bool {
switch key := needle.(type) {
case string:
for _, item := range hystack.([]string) {
if key == item {
return true
}
}
case int:
for _, item := range hystack.([]int) {
if key == item {
return true
}
}
case int64:
for _, item := range hystack.([]int64) {
if key == item {
return true
}
}
default:
return false