-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
303 lines (256 loc) · 9.88 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
package main
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/schollz/progressbar/v3"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
// Struct para el salón
type Salon struct {
ID *string `bson:"_id"`
Nombre *string `bson:"nombre,omitempty"`
Pais *string `bson:"pais,omitempty"`
Terminal *int `bson:"terminal,omitempty"`
// private Long tarifaIngresoSinConvenio;
// private List<IpEquipo> lstIpEquipo;
// private List<BancoSalon> bancos;
}
// Struct para el usuario
type User struct {
ID *string `bson:"_id"`
Username *string `bson:"username,omitempty"`
Password *string `bson:"password,omitempty"`
FirstName *string `bson:"firstName,omitempty"`
LastName *string `bson:"lastName,omitempty"`
AccountNonExpired *bool `bson:"accountNonExpired,omitempty"`
AccountNonLocked *bool `bson:"accountNonLocked,omitempty"`
CredentialsNonExpired *bool `bson:"credentialsNonExpired,omitempty"`
Enabled *bool `bson:"enabled,omitempty"`
Authorities []Authority `bson:"authorities,omitempty"`
}
// Struct para la autoridad del usuario
type Authority struct {
Name string `bson:"name,omitempty"`
}
// Struct para el cliente
type Cliente struct {
Ref string `bson:"$ref,omitempty"`
ID int64 `bson:"$id"`
}
// Struct para el banco
type Banco struct {
Ref string `bson:"$ref,omitempty"`
ID string `bson:"$id"`
}
// Struct para el medio de pago
type MedioPago struct {
Ref string `bson:"$ref,omitempty"`
ID string `bson:"$id"`
}
type Benefit struct {
Code string `bson:"code,omitempty"`
Description string `bson:"description,omitempty"`
Currency string `bson:"currency,omitempty"`
Quantity int32 `bson:"quantity,omitempty"`
Value int32 `bson:"value,omitempty"`
AvailableByDay int32 `bson:"availableByDay,omitempty"`
Used int32 `bson:"used,omitempty"`
}
type Reversa struct {
FechaReversa time.Time `bson:"fechaReversa,omitempty"`
Usuario string `bson:"usuario,omitempty"`
ResponseBanco string `bson:"responseBanco,omitempty"`
}
// Struct para el checkin
type Checkin struct {
ID *string `bson:"_id"`
CantidadAcompanantes *int `bson:"cantidadAcompanantes,omitempty"`
Firma *string `bson:"firma,omitempty"`
FechaIngreso time.Time `bson:"fechaIngreso,omitempty"`
Sincronizado *bool `bson:"sincronizado,omitempty"`
IdCierreServer *string `bson:"idCierreServer,omitempty"`
CodigoAutorizacionBanco *string `bson:"codigoAutorizacionBanco,omitempty"`
CodigoAutorizacionTbk *string `bson:"codigoAutorizacionTbk,omitempty"`
TotalPagadoTbk *int64 `bson:"totalPagadoTbk,omitempty"`
TotalVoucherConvenio *int64 `bson:"totalVoucherConvenio,omitempty"`
CantidadAcoPagadoTbk *int `bson:"cantidadAcoPagadoTbk,omitempty"`
CantidadAcoEnConvenio *int `bson:"cantidadAcoEnConvenio,omitempty"`
NumeroTarjeta *string `bson:"numeroTarjeta,omitempty"`
Turno *string `bson:"turno,omitempty"`
IdSkyNumber *string `bson:"idSkyNumber,omitempty"`
NumeroReserva *string `bson:"numeroReserva,omitempty"`
NumeroVuelo *string `bson:"numeroVuelo,omitempty"`
NombreAcompanante *string `bson:"nombreAcompanante,omitempty"`
ApellidoAcompanante *string `bson:"apellidoAcompanante,omitempty"`
CodigoPax *string `bson:"codigoPax,omitempty"`
IngresoEspecial *bool `bson:"ingresoEspecial,omitempty"`
SincronizadoBancoChile *bool `bson:"sincronizadoBancoChile,omitempty"`
ResponseBancoChile string `bson:"responseBancoChile,omitempty"`
Reversa Reversa `bson:"reversa,omitempty"`
ServicioBChile *bool `bson:"servicioBChile,omitempty"`
ReCheckin *bool `bson:"reCheckin,omitempty"`
TitularAmount *int64 `bson:"titularAmount,omitempty"`
ItauAccessExchange *bool `bson:"itauAccessExchange,omitempty"`
ItauAccessExchangeOffline *bool `bson:"itauAccessExchangeOffline,omitempty"`
Transaction *int64 `bson:"transaction,omitempty"`
PudahuelTransactionMessage *string `bson:"pudahuelTransactionMessage,omitempty"`
// Deprecated fields
BancoChileCuposLibres *int `bson:"bancoChileCuposLibres,omitempty"`
BancoChileCuposPremium *int `bson:"bancoChileCuposPremium,omitempty"`
BancoChileCuposPromocionales *int `bson:"bancoChileCuposPromocionales,omitempty"`
BancoChileCuposIngresoReducido *int `bson:"bancoChileCuposIngresoReducido,omitempty"`
MontoConvenio *int64 `bson:"montoConvenio,omitempty"`
MontoSinConvenio *int64 `bson:"montoSinConvenio,omitempty"`
FalabellaRegister *bool `bson:"falabellaRegister,omitempty"`
FalabellaRegisterOffline *bool `bson:"falabellaRegisterOffline,omitempty"`
AccessMode string `bson:"accessMode,omitempty"`
Salon Salon `bson:"salon,omitempty"`
User User `bson:"user,omitempty"`
Cliente Cliente `bson:"cliente,omitempty"`
Banco Banco `bson:"banco,omitempty"`
MedioPago MedioPago `bson:"medioPago,omitempty"`
// CheckinRel Checkin `bson:"checkinRel,omitempty"`
// Integrations
// Integration string `bson:"integration,omitempty"`
// Benefits []Benefit `bson:"benefits,omitempty"`
}
// Struct para el cierre
type Cierre struct {
ID string `bson:"_id"`
Envio time.Time `bson:"envio,omitempty"`
Recepcion time.Time `bson:"recepcion,omitempty"`
Salon Salon `bson:"salon,omitempty"`
LstCheckins []Checkin `bson:"lstCheckins,omitempty"`
Checkins []string `bson:"checkins,omitempty"`
Origin *string `bson:"origin,omitempty"`
Class string `bson:"_class,omitempty"`
}
var wg sync.WaitGroup
func main() {
// Set logger
logFile, err := os.OpenFile("error.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
if err != nil {
log.Fatalln(err)
}
log.SetOutput(logFile)
// Conexión a MongoDB
user := Getenv("USER", "")
pass := Getenv("PASS", "")
host := Getenv("HOST", "localhost")
port := Getenv("PORT", "27017")
cs := fmt.Sprintf("mongodb://%s:%s", host, port)
if user != "" && pass != "" {
cs = fmt.Sprintf("mongodb://%s:%s@%s:%s", user, pass, host, port)
}
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(cs))
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.TODO())
// Verificamos la conexión
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
log.Fatal(err)
}
fmt.Println("Conectado a MongoDB")
// Selección de la base de datos y colecciones
db := client.Database("server_svip")
cierreCollection := db.Collection("cierre")
checkinCollection := db.Collection("checkins")
count := countDocs(cierreCollection)
// Procesar todos los cierres
cursor, err := cierreCollection.Find(context.TODO(), bson.D{})
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.TODO())
// Contador para las goroutines
const numGoroutines = 20
semaphore := make(chan struct{}, numGoroutines)
bar := progressbar.Default(count)
for cursor.Next(context.TODO()) {
var cierre Cierre
if err := cursor.Decode(&cierre); err == nil {
// log.Fatal(err)
// Utilizamos una goroutine para cada cierre
semaphore <- struct{}{} // Bloquea cuando alcanzamos el límite de goroutines
wg.Add(1)
go func(cierre Cierre) {
defer wg.Done()
defer func() { <-semaphore }() // Libera la goroutine al finalizar
processCierre(cierreCollection, checkinCollection, cierre)
}(cierre)
}
bar.Add(1)
}
wg.Wait() // Esperar que todas las goroutines finalicen
fmt.Println("Proceso completado")
}
func Getenv(key, defaultValue string) string {
value, defined := os.LookupEnv(key)
if !defined {
return defaultValue
}
return value
}
func countDocs(collectionCierre *mongo.Collection) int64 {
startTime := time.Now() // cronómetro
opts := options.Count().SetHint("_id_")
p := message.NewPrinter(language.Spanish)
log.Println("Contando los documentos a procesar")
count, err := collectionCierre.CountDocuments(context.TODO(), bson.D{}, opts)
if err != nil {
log.Fatal(err)
}
elapsedTime := time.Since(startTime)
log.Printf("Tiempo total de contéo: %s. Total de documentos a procesar: %s\n",
elapsedTime, p.Sprint(count))
return count
}
// Función para procesar cada cierre
func processCierre(cierreCollection, checkinCollection *mongo.Collection, cierre Cierre) {
// log.Printf("Procesando cierre: %s", cierre.ID)
var checkinIDs []string
// Mover checkins a la colección correspondiente y generar referencias
for _, checkin := range cierre.LstCheckins {
year := checkin.FechaIngreso.Year()
collectionName := fmt.Sprintf("checkins_%d", year)
checkin.Salon = cierre.Salon
// Insertar el checkin en la colección correspondiente
_, err := checkinCollection.Database().Collection(collectionName).InsertOne(context.TODO(), checkin)
if err != nil {
log.Printf("Error insertando checkin %s: %v", *checkin.ID, err)
continue
}
checkinIDs = append(checkinIDs, *checkin.ID)
// log.Printf("Checkin %s movido a la colección %s", checkin.ID, collectionName)
}
// Actualizar el cierre con las referencias a los checkins
year := cierre.Envio.Year()
collectionName := fmt.Sprintf("cierres_%d", year)
_, err := cierreCollection.Database().Collection(collectionName).InsertOne(
context.TODO(),
bson.M{
"_id": cierre.ID,
"checkins": checkinIDs,
"envio": cierre.Envio,
"recepcion": cierre.Recepcion,
"salon": cierre.Salon,
"origin": cierre.Origin,
"_class": cierre.Class,
},
)
if err != nil {
log.Printf("Error actualizando cierre %s: %v", cierre.ID, err)
} else {
// log.Printf("Cierre %s actualizado con referencias a los checkins", cierre.ID)
}
}