Beispiel #1
0
            public async Task <Result> Handle(Contract request, CancellationToken cancellationToken)
            {
                string config = _configuration[$"EcommerceIntegration:Active"];

                if (config == null || config != "True")
                {
                    return(Result.Ok("Acesso Negado"));
                }

                if (request.id <= 0)
                {
                    return(Result.Ok("Acesso Negado"));
                }

                EcommerceResponse response = await GetEcommerceOrder(request.id, cancellationToken);

                if (response == null)
                {
                    return(Result.Ok("Pedido não existe"));
                }

                OrderItem order = response.order;

                if (String.IsNullOrEmpty(order.billing_address.cpf) &&
                    String.IsNullOrEmpty(order.billing_address.cnpj))
                {
                    await CreateErrorLog(
                        "order-no-cpf-cnpj",
                        JsonConvert.SerializeObject(order),
                        cancellationToken
                        );

                    return(Result.Ok("CPF/CNPJ não informado"));
                }

                if (String.IsNullOrEmpty(order.billing_address.email))
                {
                    await CreateErrorLog(
                        "order-no-email",
                        JsonConvert.SerializeObject(order),
                        cancellationToken
                        );

                    return(Result.Ok("E-mail do usuário não informado"));
                }

                if (order.status == "refunded")
                {
                    // TODO FAZER TRATAMENTO
                    return(Result.Ok());
                }

                if (order.status == "processing")
                {
                    if (order.line_items == null || order.line_items.Count == 0)
                    {
                        await CreateErrorLog(
                            "order-has-no-products",
                            JsonConvert.SerializeObject(order),
                            cancellationToken
                            );

                        return(Result.Ok("Produto não encontrado"));
                    }

                    var itemsIds = order.line_items.Select(li => li.product_id);

                    var newModules = await GetModuleByEcommerceId(itemsIds, cancellationToken);

                    var newEvents = await GetEventByEcommerceId(itemsIds, cancellationToken);

                    var newTracks = await GetTrackByEcommerceId(itemsIds, cancellationToken);

                    if (newModules.Count == 0 && newEvents.Count == 0 && newTracks.Count == 0)
                    {
                        await CreateErrorLog(
                            "product-not-found-by-ids",
                            JsonConvert.SerializeObject(order),
                            cancellationToken
                            );

                        return(Result.Ok("Produto(s) não encontrado(s)"));
                    }

                    string cpfCnpj = order.billing_address.persontype == "F" ?
                                     order.billing_address.cpf :
                                     order.billing_address.cnpj;

                    /// Alterada a validação da existência de usuário ao recomendar aluno
                    /// vindo do eCommerce: anteriormente a validação era feita pelo CPF.
                    User user = await _db.UserCollection.AsQueryable()
                                .Where(x => x.Email.ToLower() == order.billing_address.email.ToLower())
                                .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                    if (user == null)
                    {
                        string userRole = "Student";

                        foreach (var track in newTracks)
                        {
                            var product = track.EcommerceProducts
                                          .FirstOrDefault(e => itemsIds.Contains(e.EcommerceId));

                            var usersCount = product == null || product.UsersAmount < 1 ? 1 : product.UsersAmount;

                            if (usersCount > 1) // Fluxo de Gestor
                            {
                                userRole = "BusinessManager";
                                break;
                            }
                        }

                        User newUser = await CreateNewUser(order, cpfCnpj, userRole, cancellationToken);

                        string password = Guid.NewGuid().ToString("d").Substring(1, 6);

                        var result = await _userManager.CreateAsync(newUser, password);

                        if (!result.Succeeded)
                        {
                            await CreateErrorLog(
                                "user-creation",
                                JsonConvert.SerializeObject(result.Errors),
                                cancellationToken
                                );

                            return(Result.Ok("Erro ao criar usuário"));
                        }

                        user = newUser;
                        user.EmailVerified = true;

                        await SendEmail(user, password, cancellationToken);
                    }

                    if (order.customer.id > 0)
                    {
                        user.EcommerceId = order.customer.id;
                    }

                    user = VerifyUserCollections(user);

                    foreach (var mod in newModules)
                    {
                        var find = user.ModulesInfo.FirstOrDefault(x => x.Id == mod.Id);
                        if (find == null)
                        {
                            var userProgress = User.UserProgress.Create(
                                mod.Id, 0, 0, mod.Title, mod.ValidFor
                                ).Data;

                            user.ModulesInfo.Add(userProgress);
                        }
                    }

                    foreach (var ev in newEvents)
                    {
                        var find = user.EventsInfo.FirstOrDefault(x => x.Id == ev.Id);
                        if (find == null)
                        {
                            var userProgress = User.UserProgress.Create(
                                ev.Id, 0, 0, ev.Title, null
                                ).Data;

                            user.EventsInfo.Add(userProgress);
                        }
                    }

                    foreach (var track in newTracks)
                    {
                        var product = track.EcommerceProducts
                                      .FirstOrDefault(e => itemsIds.Contains(e.EcommerceId));

                        var usersCount = product == null || product.UsersAmount < 1 ? 1 : product.UsersAmount;

                        var find = user.TracksInfo.FirstOrDefault(x => x.Id == track.Id);
                        if (find == null)
                        {
                            var userProgress = User.UserProgress.Create(
                                track.Id, 0, 0, track.Title, track.ValidFor
                                ).Data;

                            user.TracksInfo.Add(userProgress);
                        }

                        if (usersCount > 1) // Fluxo de Gestor
                        {
                            int currentCount = 0;
                            var newUsers     = new List <NewUser>();

                            while (currentCount < usersCount)
                            {
                                currentCount++;

                                User newUser = await CreateNewUserByManager(currentCount, user, track, cancellationToken);

                                string password = Guid.NewGuid().ToString("d").Substring(1, 6);

                                var result = await _userManager.CreateAsync(newUser, password);

                                if (!result.Succeeded)
                                {
                                    await CreateErrorLog(
                                        "user-creation",
                                        JsonConvert.SerializeObject(result.Errors),
                                        cancellationToken
                                        );

                                    return(Result.Ok("Erro ao criar usuários para gestor: usuario" + currentCount));
                                }

                                newUsers.Add(
                                    new NewUser(newUser.UserName, password)
                                    );
                            }

                            await SendManagerEmail(user, track, newUsers, cancellationToken);
                        }
                    }

                    await SavePurchaseHistory(user.Id, newModules, newEvents, newTracks, cancellationToken);

                    await _db.UserCollection.ReplaceOneAsync(
                        t => t.Id == user.Id, user,
                        cancellationToken : cancellationToken
                        );
                }

                return(Result.Ok());
            }
Beispiel #2
0
            public async Task <Result <List <UserItemExport> > > Handle(Contract request, CancellationToken cancellationToken)
            {
                //if (request.UserRole == "Student")
                //    return Result.Fail<List<UserItem>>("Acesso Negado");

                var userItems          = new List <UserItemExport>();
                var currentTransaction = new TransactionItem();
                var currentProduct     = new EcommerceResponse();

                //int i = 0;
                //int k = 0;

                var emailsNaoEncontrados = new List <string>();

                string[] emails = new string[] { "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**"
                                                 , "*****@*****.**" };

                try
                {
                    for (int i = 0; i < emails.Length; i++)
                    {
                        var dbStudents = await _db.UserCollection
                                         .AsQueryable()
                                         .Where(x => x.Email.ToLower() == emails[i].ToLower())
                                         .FirstOrDefaultAsync(cancellationToken: cancellationToken);

                        if (dbStudents == null)
                        {
                            emailsNaoEncontrados.Add(emails[i]);
                            continue;
                        }

                        if (dbStudents.ModulesInfo != null)
                        {
                            for (var k = 0; k < dbStudents.ModulesInfo.Count; k++)
                            {
                                userItems.Add(new UserItemExport
                                {
                                    Email = dbStudents.Email,
                                    Curso = dbStudents.ModulesInfo[k].Name
                                });
                            }
                        }
                        if (dbStudents.TracksInfo != null)
                        {
                            for (var k = 0; k < dbStudents.TracksInfo.Count; k++)
                            {
                                userItems.Add(new UserItemExport
                                {
                                    Email = dbStudents.Email,
                                    Curso = dbStudents.TracksInfo[k].Name
                                });
                            }
                        }
                    }

                    //var transactions = new List<TransactionItem>();
                    //var response = await PagarMe.GetTransactions(_configuration);

                    //if (response.StatusCode == HttpStatusCode.OK)
                    //{
                    //    var content = await response.Content.ReadAsStringAsync();
                    //    //var parsed = JObject.Parse(content);
                    //    transactions = JsonConvert.DeserializeObject<List<TransactionItem>>(
                    //        content
                    //    );
                    //}
                    //else
                    //{
                    //    string content = await response.Content.ReadAsStringAsync();
                    //    //await CreateErrorLog("transaction-not-found", content, cancellationToken);
                    //}

                    //for (i = 0; i < transactions.Count; i++)
                    //{
                    //    currentTransaction = transactions[i];
                    //    var orderResp = await Woocommerce.GetOrderById(transactions[i].metadata.order_number, _configuration);
                    //    var product = new EcommerceResponse();

                    //    if (orderResp.StatusCode == HttpStatusCode.OK)
                    //    {
                    //        var content = await orderResp.Content.ReadAsStringAsync();
                    //        //var parsed = JObject.Parse(content);
                    //        product = JsonConvert.DeserializeObject<EcommerceResponse>(
                    //            content
                    //        );

                    //        currentProduct = product;
                    //    }
                    //    //else
                    //    //{
                    //    //    continue;
                    //    //    //string content = await response.Content.ReadAsStringAsync();
                    //    //    //await CreateErrorLog("transaction-not-found", content, cancellationToken);
                    //    //}

                    //    userItems.Add(new UserItemExport
                    //    {
                    //        aluno_nome = transactions[i].customer != null ? transactions[i].customer.name : "",
                    //        matricula_data = transactions[i].formated_date_created,
                    //        plapagamento_id = transactions[i].payment_method,
                    //        turma_data_inicio = transactions[i].formated_date_created,
                    //        curso_nome = product.order != null ? product.order.line_items[0].name : ""
                    //    });



                    //var dbStudents = await _db.UserCollection
                    //    .AsQueryable()
                    //    .Where(x => (x.ModulesInfo != null && x.ModulesInfo.Count > 0)
                    //        || (x.TracksInfo != null && x.TracksInfo.Count > 0))
                    //    .ToListAsync(cancellationToken: cancellationToken);

                    //for (i = 0; i < dbStudents.Count; i++)
                    //{
                    //    if (dbStudents[i].ModulesInfo != null)
                    //    {
                    //        for (k = 0; k < dbStudents[i].ModulesInfo.Count; k++)
                    //        {
                    //            userItems.Add(new UserItemExport
                    //            {
                    //                aluno_nome = dbStudents[i].Name,
                    //                matricula_data = dbStudents[i].ModulesInfo[k].CreatedAt != null ?
                    //                                    dbStudents[i].ModulesInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") :
                    //                                    dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"),
                    //                turma_data_inicio = dbStudents[i].ModulesInfo[k].CreatedAt != null ?
                    //                                    dbStudents[i].ModulesInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") :
                    //                                    dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"),
                    //                plapagamento_id = "X",
                    //                curso_nome = dbStudents[i].ModulesInfo[k].Name
                    //            });
                    //        }
                    //    }
                    //    if (dbStudents[i].TracksInfo != null)
                    //    {
                    //        for (k = 0; k < dbStudents[i].TracksInfo.Count; k++)
                    //        {
                    //            userItems.Add(new UserItemExport
                    //            {
                    //                aluno_nome = dbStudents[i].Name,
                    //                matricula_data = dbStudents[i].TracksInfo[k].CreatedAt != null ?
                    //                                    dbStudents[i].TracksInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") :
                    //                                    dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"),
                    //                turma_data_inicio = dbStudents[i].TracksInfo[k].CreatedAt != null ?
                    //                                    dbStudents[i].TracksInfo[k].CreatedAt.Value.ToString("dd/MM/yyyy") :
                    //                                    dbStudents[i].CreatedAt.ToString("dd/MM/yyyy"),
                    //                plapagamento_id = "X",
                    //                curso_nome = dbStudents[i].TracksInfo[k].Name
                    //            });
                    //        }
                    //    }
                    //}

                    //var dbEvents = await _db.EventCollection
                    //    .AsQueryable()
                    //    .Where(x => eventsIds.Contains(x.Id))
                    //    .Select(x => new RelationalItem
                    //    {
                    //        Id = x.Id,
                    //        Name = x.Title
                    //    })
                    //    .ToListAsync(cancellationToken: cancellationToken);
                    //}
                    var emailsString = string.Join(";", emailsNaoEncontrados);
                    return(Result.Ok(userItems.ToList()));
                }
                catch (Exception ex)
                {
                    //var iError = i;
                    //var kError = k;
                    //var errorTransaction = currentTransaction;
                    //var errorProduct = currentProduct;
                    return(Result.Fail <List <UserItemExport> >("Acesso Negado"));
                }
            }