Пример #1
0
 public SelectAdherentViewModel(AdherentStolon activeAdherent, Stolon stolon, List <string> adherentsMails, bool addHasProducer)
 {
     base.ActiveAdherentStolon = activeAdherent;
     AdherentsMails            = adherentsMails;
     Stolon         = stolon;
     AddHasProducer = addHasProducer;
 }
Пример #2
0
 public AdherentsViewModel(AdherentStolon activeAdherentStolon, Stolon stolon, List <Sympathizer> sympathizers, List <AdherentStolon> adherentsStolon)
 {
     AdherentsStolonViewModel = new AdherentsStolonViewModel(activeAdherentStolon, stolon, adherentsStolon);
     ActiveAdherentStolon     = activeAdherentStolon;
     SympathizersViewModel    = new SympathizersViewModel(activeAdherentStolon, stolon, sympathizers);
     Stolon = stolon;
 }
Пример #3
0
        /// <summary>
        /// PaySympathiserSubscription
        /// </summary>
        /// <param name="id">Sympathizer ID</param>
        /// <returns></returns>
        public IActionResult PaySympathiserSubscription(Guid id)
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            Transaction transaction   = new Transaction();
            Sympathizer sympathizer   = _context.Sympathizers.FirstOrDefault(x => x.Id == id);
            Stolon      currentStolon = GetCurrentStolon();

            sympathizer.SubscriptionPaid = true;
            transaction.Amount           = currentStolon.SympathizerSubscription;
            //Add a transaction
            transaction.Stolon           = currentStolon;
            transaction.AddedAutomaticly = true;
            transaction.Date             = DateTime.Now;
            transaction.Type             = Transaction.TransactionType.Inbound;
            transaction.Category         = Transaction.TransactionCategory.Subscription;
            transaction.Description      = "Paiement de la cotisation du sympathisant : " + sympathizer.Name + " " + sympathizer.Surname;
            _context.Transactions.Add(transaction);
            //Save
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
        // GET: Bills
        public IActionResult Index()
        {
            Stolon stolon             = GetCurrentStolon();
            var    adherentStolon     = GetActiveAdherentStolon();
            VmWeekBasketManagement vm = new VmWeekBasketManagement(adherentStolon);

            vm.Stolon        = GetCurrentStolon();
            vm.ConsumerBills = _context.ConsumerBills
                               .Include(x => x.AdherentStolon)
                               .Include(x => x.AdherentStolon.Adherent)
                               .Include(x => x.AdherentStolon.Stolon)
                               .Where(x => x.State == BillState.Pending && x.AdherentStolon.StolonId == stolon.Id)
                               .OrderBy(x => x.AdherentStolon.Adherent.Id)
                               .AsNoTracking()
                               .ToList();
            vm.ProducerBills = _context.ProducerBills
                               .Include(x => x.AdherentStolon)
                               .Include(x => x.AdherentStolon.Adherent)
                               .Include(x => x.AdherentStolon.Stolon)
                               .Where(x => x.State != BillState.Paid && x.AdherentStolon.StolonId == stolon.Id)
                               .OrderBy(x => x.AdherentStolon.Adherent.Id)
                               .AsNoTracking()
                               .ToList();
            vm.StolonsBills    = _context.StolonsBills.Include(x => x.Stolon).Where(x => x.StolonId == stolon.Id).ToList();
            vm.WeekStolonsBill = vm.StolonsBills.FirstOrDefault(x => x.BillNumber.EndsWith(DateTime.Now.Year + "_" + DateTime.Now.GetIso8601WeekOfYear()));
            return(View(vm));
        }
Пример #5
0
 public AdherentViewModel(AdherentStolon activeAdherentStolon, Adherent adherent, Stolon stolon, AdherentEdition edition)
 {
     Adherent             = adherent;
     OriginalEmail        = adherent.Email;
     ActiveAdherentStolon = activeAdherentStolon;
     Edition = edition;
     Stolon  = stolon;
 }
Пример #6
0
 /// <summary>
 /// Add a new transaction at current date
 /// </summary>
 /// <param name="type"></param>
 /// <param name="category"></param>
 /// <param name="amount"></param>
 /// <param name="description"></param>
 /// <param name="addedAutomaticly"></param>
 public Transaction(Stolon stolon, TransactionType type, TransactionCategory category, decimal amount, string description, bool addedAutomaticly = true)
 {
     Stolon           = stolon;
     AddedAutomaticly = addedAutomaticly;
     Date             = DateTime.Now;
     Type             = type;
     Category         = category;
     Amount           = amount;
     Description      = description;
 }
Пример #7
0
        private static List <Stolon> CreateStolons(ApplicationDbContext context)
        {
            if (context.Stolons.Any())
            {
                return(context.Stolons.ToList());
            }
            List <Stolon> stolons = new List <Stolon>();
            Stolon        stolon  = new Stolon();

            stolon.State           = Stolon.StolonState.Open;
            stolon.IsModeSimulated = true;
            stolon.CreationDate    = DateTime.Now;


            stolon.Label              = "Stolon de Privas";
            stolon.AboutText          = "Le Stolon de Privas est une association loi 1901";
            stolon.JoinUsText         = "Pour nous rejoindre contacter nous ! Ou venez nous rendre visite";
            stolon.Address            = "07000 PRIVAS";
            stolon.PhoneNumber        = "06 64 86 66 93";
            stolon.ContactMailAddress = "*****@*****.**";

            stolon.DeliveryAndStockUpdateDayStartDate = DayOfWeek.Wednesday;
            stolon.DeliveryAndStockUpdateDayStartDateHourStartDate   = 12;
            stolon.DeliveryAndStockUpdateDayStartDateMinuteStartDate = 00;
            stolon.OrderDayStartDate    = DayOfWeek.Sunday;
            stolon.OrderHourStartDate   = 16;
            stolon.OrderMinuteStartDate = 00;

            stolon.BasketPickUpStartDay    = DayOfWeek.Thursday;
            stolon.BasketPickUpStartHour   = 17;
            stolon.BasketPickUpStartMinute = 30;
            stolon.BasketPickEndUpDay      = DayOfWeek.Thursday;
            stolon.BasketPickUpEndHour     = 19;
            stolon.BasketPickUpEndMinute   = 30;

            stolon.UseSubscipstion        = true;
            stolon.SubscriptionStartMonth = Stolon.Month.September;

            stolon.OrderDeliveryMessage = "Votre panier est disponible jeudi de 17h30 à 19h au : 10 place de l'hotel de ville, 07000 Privas";

            stolon.UseProducersFee = true;
            stolon.ProducersFee    = 5;

            stolon.UseSympathizer          = true;
            stolon.SympathizerSubscription = 2;
            stolon.ConsumerSubscription    = 10;
            stolon.ProducerSubscription    = 20;
            stolon.GoodPlan = true;

            context.Add(stolon);
            context.SaveChanges();

            stolons.Add(stolon);
            return(stolons);
        }
Пример #8
0
        // GET: Consumers/Create
        public virtual IActionResult CreateAdherent(AdherentEdition edition, Guid?stolonId = null)
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            Stolon stolon = stolonId == null?GetCurrentStolon() : _context.Stolons.First(x => x.Id == stolonId);

            return(View(new AdherentViewModel(GetActiveAdherentStolon(), new Adherent(), stolon, edition)));
        }
Пример #9
0
        public IActionResult Index(Guid?id = null)
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            Stolon stolon = id == null?GetCurrentStolon() : _context.Stolons.First(x => x.Id == id);

            AdherentsViewModel adherentsViewModel = new AdherentsViewModel(GetActiveAdherentStolon(), stolon, _context.Sympathizers.Where(x => x.StolonId == stolon.Id).ToList(), _context.AdherentStolons.Include(x => x.Stolon).Include(x => x.Adherent).Where(x => x.StolonId == stolon.Id).ToList());

            return(View(adherentsViewModel));
        }
Пример #10
0
        public IActionResult Index()
        {
            Stolon stolon    = GetCurrentStolon();
            var    producers = _context.AdherentStolons
                               .Include(x => x.Adherent)
                               .Where(x => x.IsProducer && x.StolonId == stolon.Id)
                               .AsNoTracking()
                               .ToList();

            int totalProducts = _context.ProductsStocks.Include(x => x.Product).Include(x => x.AdherentStolon).Count(x => x.AdherentStolon.StolonId == stolon.Id && !x.Product.IsArchive);

            return(View(new PublicProducersViewModel(producers, totalProducts)));
        }
Пример #11
0
        // GET: Transactions
        public IActionResult Index()
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            Stolon             stolon       = GetCurrentStolon();
            List <Transaction> transactions = _context.Transactions.Include(x => x.Stolon).Where(x => x.StolonId == stolon.Id).ToList();

            transactions.OfType <AdherentTransaction>().ToList().ForEach(transac => transac.Adherent = _context.Adherents.FirstOrDefault(adherent => adherent.Id == transac.AdherentId));
            return(View(new TransactionsViewModel(GetActiveAdherentStolon(), stolon, transactions)));
        }
Пример #12
0
        public IActionResult SwitchMode(Guid id)
        {
            if (!Authorized(Role.Admin))
            {
                return(Unauthorized());
            }

            Stolon stolon = _context.Stolons.FirstOrDefault(x => x.Id == id);

            stolon.SimulationMode = stolon.GetMode() == Stolon.Modes.DeliveryAndStockUpdate ? Stolon.Modes.Order : Stolon.Modes.DeliveryAndStockUpdate;
            _context.Update(stolon);
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #13
0
        // GET: News/Details/5
        public IActionResult SendToAllUser(MailMessage mailMessage, Stolon stolon)
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            List <IAdherent> users = new List <IAdherent>();

            users.AddRange(_context.Sympathizers.Where(x => x.StolonId == stolon.Id && x.ReceivedInformationsEmail).ToList());
            users.AddRange(_context.Adherents.Include(x => x.AdherentStolons).Where(x => x.AdherentStolons.Any(consStol => consStol.StolonId == stolon.Id)).ToList());
            //On peut envoyer deux fois � un producteur qui est un consommateur
            users.AddRange(_context.Adherents.Include(x => x.AdherentStolons).Where(x => x.AdherentStolons.Any(consStol => consStol.StolonId == stolon.Id)).ToList());
            return(View("Report", SendMail(users.Distinct(), mailMessage)));
        }
Пример #14
0
        public IActionResult ValidatedBasket()
        {
            Stolon stolon         = GetCurrentStolon();
            var    adherentStolon = GetActiveAdherentStolon();

            if (adherentStolon == null)
            {
                return(null);
            }
            ValidatedWeekBasket        validatedWeekBasket        = _context.ValidatedWeekBaskets.Include(x => x.AdherentStolon).Include(x => x.AdherentStolon.Adherent).Include(x => x.BillEntries).FirstOrDefault(x => x.AdherentStolon.Id == adherentStolon.Id);
            ValidationSummaryViewModel validationSummaryViewModel = new ValidationSummaryViewModel(GetActiveAdherentStolon(), validatedWeekBasket, new List <BillEntry>())
            {
                Total = GetBasketPrice(validatedWeekBasket)
            };

            return(View("ValidatedBasket", validationSummaryViewModel));
        }
Пример #15
0
        public virtual PartialViewResult _PartialAddAdherent(AdherentEdition edition, Guid?stolonId = null)
        {
            Stolon stolon = stolonId == null?GetCurrentStolon() : _context.Stolons.First(x => x.Id == stolonId);

            List <string> emails;

            if (edition == AdherentEdition.Producer)
            {
                emails = _context.Adherents.Include(x => x.AdherentStolons).Where(x => x.AdherentStolons.Any(prod => prod.IsProducer)).Select(x => x.Email).ToList();
            }
            else
            {
                emails = _context.Adherents.Select(x => x.Email).ToList();
            }
            _context.AdherentStolons.Include(x => x.Adherent).Where(x => x.StolonId == stolon.Id).ToList().ForEach(x => emails.Remove(x.Adherent.Email));
            return(PartialView(new SelectAdherentViewModel(GetActiveAdherentStolon(), stolon, emails, edition == AdherentEdition.Producer)));
        }
Пример #16
0
        public News(Stolon stolon) : this()
        {
            var day = stolon.BasketPickEndUpDay - DateTime.Now.DayOfWeek;

            if (day < 0)
            {
                day = 7 + day;
            }
            var hours   = stolon.BasketPickUpEndHour - DateTime.Now.Hour;
            var minutes = stolon.BasketPickUpEndMinute - DateTime.Now.Minute;

            var publishEnd = DateTime.Now;

            publishEnd = publishEnd.AddDays(day);
            publishEnd = publishEnd.AddHours(hours);
            publishEnd = publishEnd.AddMinutes(minutes);
            PublishEnd = publishEnd;
        }
Пример #17
0
        public virtual async Task <IActionResult> Create(AdherentEdition edition, AdherentViewModel vmAdherent, IFormFile uploadFile)
        {
            if (!Authorized(Role.Volunteer))
            {
                return(Unauthorized());
            }

            if (ModelState.IsValid)
            {
                Stolon stolon = _context.Stolons.FirstOrDefault(x => x.Id == vmAdherent.Stolon.Id);
                #region Creating Consumer
                //Setting value for creation
                UploadAndSetAvatar(vmAdherent.Adherent, uploadFile);

                vmAdherent.Adherent.Name = vmAdherent.Adherent.Name.ToUpper();
                AdherentStolon adherentStolon = new AdherentStolon(vmAdherent.Adherent, stolon, true);
                adherentStolon.RegistrationDate = DateTime.Now;
                adherentStolon.LocalId          = _context.AdherentStolons.Where(x => x.StolonId == stolon.Id).Max(x => x.LocalId) + 1;
                adherentStolon.IsProducer       = edition == AdherentEdition.Producer;
                _context.Adherents.Add(vmAdherent.Adherent);
                _context.AdherentStolons.Add(adherentStolon);
                #endregion Creating Consumer

                #region Creating linked application data
                var appUser = new ApplicationUser {
                    UserName = vmAdherent.Adherent.Email, Email = vmAdherent.Adherent.Email
                };
                appUser.User = vmAdherent.Adherent;

                var result = await _userManager.CreateAsync(appUser, vmAdherent.Adherent.Email);

                #endregion Creating linked application data
                //
                //
                _context.SaveChanges();
                //Send confirmation mail
                string confirmationViewName = edition == AdherentEdition.Consumer ? "AdherentConfirmationMail" : "ProducerConfirmationMail";
                Services.AuthMessageSender.SendEmail(stolon.Label, vmAdherent.Adherent.Email, vmAdherent.Adherent.Name, "Creation de votre compte", base.RenderPartialViewToString(confirmationViewName, adherentStolon));

                return(RedirectToAction("Index"));
            }
            return(View(vmAdherent));
        }
Пример #18
0
        public IActionResult StolonContact(Guid id)
        {
            Stolon stolon = _context.Stolons.FirstOrDefault(x => x.Id == id);
            Dictionary <AdherentStolon, List <Product> > prods = new Dictionary <AdherentStolon, List <Product> >();

            var producers = _context.AdherentStolons
                            .Include(x => x.Adherent)
                            .Include(x => x.Adherent.Products)
                            .ThenInclude(x => x.Familly)
                            .ThenInclude(x => x.Type)
                            .Where(x => x.IsProducer && x.StolonId == stolon.Id)
                            .AsNoTracking()
                            .ToList();


            int totalProducts = _context.ProductsStocks.Include(x => x.Product).Include(x => x.AdherentStolon).Count(x => x.AdherentStolon.StolonId == stolon.Id && !x.Product.IsArchive);


            return(View(new StolonContactViewModel(stolon, producers, totalProducts, User.Identity.IsAuthenticated?GetActiveAdherentStolon():null)));
        }
Пример #19
0
        private static void TriggerOrderMode(Stolon stolon, ApplicationDbContext dbContext)
        {
            foreach (ProductStockStolon productStock in dbContext.ProductsStocks.Include(x => x.AdherentStolon).Include(x => x.Product).Where(x => x.AdherentStolon.StolonId == stolon.Id).ToList())
            {
                if (productStock.State == ProductState.Stock)
                {
                    productStock.State = ProductState.Disabled;
                }
            }
            dbContext.SaveChanges();
            //Send email to all adherent that have subscribe to product by mail
            string htmlMessage = "Bonjour, les commandes sont ouverte chez " + stolon.Label + ". Vous pouvez dès maintenant et jusqu'à " + stolon.DeliveryAndStockUpdateDayStartDate.ToFrench() + " " + stolon.DeliveryAndStockUpdateDayStartDateHourStartDate + ":" + stolon.DeliveryAndStockUpdateDayStartDateMinuteStartDate + " commander vos produits sur " + Configurations.Application.StolonsUrl;

            //TODO générer un jolie message avec la liste des produits
            foreach (var adherentStolon in dbContext.AdherentStolons.Include(x => x.Adherent).Where(x => x.StolonId == stolon.Id && x.Adherent.ReceivedProductListByEmail).AsNoTracking())
            {
                AuthMessageSender.SendEmail(stolon.Label,
                                            adherentStolon.Adherent.Email,
                                            adherentStolon.Adherent.Name + " " + adherentStolon.Adherent.Surname,
                                            "Commande ouverte chez " + stolon.Label,
                                            htmlMessage);
            }
        }
Пример #20
0
        public IActionResult GoToStolon(string stolonName)
        {
            if (!String.IsNullOrWhiteSpace(stolonName))
            {
                Stolon stolon = _context.Stolons.FirstOrDefault(x => x.Label == stolonName || x.ShortLabel == stolonName || x.Id.ToString() == stolonName);
                if (stolon != null)
                {
                    if (!User.Identity.IsAuthenticated)
                    {
                        return(RedirectToAction(nameof(StolonContact), "Home", new { id = stolon.Id }));
                    }
                    else
                    {
                        var adherentStolon = GetActiveAdherentStolon();
                        if (adherentStolon.StolonId != stolon.Id)
                        {
                            _context.AdherentStolons.FirstOrDefault(x => x.AdherentId == adherentStolon.AdherentId && x.StolonId == stolon.Id)?.SetHasActiveStolon(_context);
                        }
                    }
                }
            }

            return(RedirectToAction(nameof(Index)));
        }
Пример #21
0
        public StolonContactViewModel(Stolon stolon, List <AdherentStolon> producers, int totalProducts, AdherentStolon activeAdherentStolon = null)
        {
            ActiveAdherentStolon = activeAdherentStolon;
            Stolon        = stolon;
            Producers     = producers;
            TotalProducts = totalProducts;

            foreach (var producer in producers)
            {
                foreach (var product in producer.Adherent.Products)
                {
                    Products.Add(product);
                    if (!AvailableProductFamillyAndType.Keys.Any(x => x.Id == product.Familly.Type.Id))
                    {
                        AvailableProductFamillyAndType.Add(product.Familly.Type, new List <ProductFamilly>());
                    }

                    if (!AvailableProductFamillyAndType[product.Familly.Type].Any(x => x.Id == product.Familly.Id))
                    {
                        AvailableProductFamillyAndType[product.Familly.Type].Add(product.Familly);
                    }
                }
            }
        }
Пример #22
0
 public SympathizersViewModel(AdherentStolon activeAdherentStolon, Stolon stolon, List <Sympathizer> sympathizers)
 {
     Sympathizers         = sympathizers;
     ActiveAdherentStolon = activeAdherentStolon;
     Stolon = stolon;
 }
Пример #23
0
        private static StolonsBill GenerateBill(Stolon stolon, List <ConsumerBill> consumersBills, ApplicationDbContext dbContext)
        {
            StringBuilder builder    = new StringBuilder();
            string        billNumber = stolon.ShortLabel + "_" + DateTime.Now.Year + "_" + DateTime.Now.GetIso8601WeekOfYear();
            StolonsBill   bill       = new StolonsBill(billNumber)
            {
                Stolon       = stolon,
                Amount       = 0,
                ProducersFee = stolon.ProducersFee,
                Consumers    = consumersBills.Count
            };

            if (!consumersBills.Any())
            {
                builder.AppendLine("Rien cette semaine !");
            }
            else
            {
                builder.AppendLine("<h1>Commandes numéro : " + billNumber + "</h1>");
                builder.AppendLine("<p>Année : " + DateTime.Now.Year);
                builder.AppendLine("<br>Semaine : " + DateTime.Now.GetIso8601WeekOfYear());
                builder.AppendLine("<br><b>Nombre de panier : " + consumersBills.Count + "</b></p>");
                builder.AppendLine("<p>Adhérents ayant un panier : <small><br>");
                consumersBills.OrderBy(x => x.AdherentStolon.LocalId)
                .ForEach(x => builder.AppendLine("<a href=\"#" + x.AdherentStolon.LocalId + "\">" + x.AdherentStolon.GetNumberSurnameName() + "</a><br>"));
                builder.AppendLine("</small></p>");

                builder.AppendLine("<div style=\"page-break-after:always\"></div>");
                int count = 0;
                foreach (var consumerBill in consumersBills.OrderBy(x => x.AdherentStolon.LocalId))
                {
                    count++;
                    builder.AppendLine("<h1 id=\"" + consumerBill.AdherentStolon.LocalId + "\">Adhérent : " + consumerBill.AdherentStolon.LocalId + " / " + consumerBill.AdherentStolon.Adherent.Surname + " / " + consumerBill.AdherentStolon.Adherent.Name + "</h1>");
                    builder.AppendLine("<p>Facture : " + consumerBill.BillNumber + "</p>");
                    builder.AppendLine("<p>Téléphone : " + consumerBill.AdherentStolon.Adherent.PhoneNumber + "</p>");
                    builder.AppendLine("<p>Total à régler : " + consumerBill.TotalPrice.ToString("0.00") + " €</p>");

                    //Create list of bill entry by product
                    var billEntryByProducer = consumerBill.BillEntries.GroupBy(x => x.ProducerBill);

                    builder.AppendLine("<h2>Commande par producteur</h2>");

                    builder.AppendLine("<table class=\"table\">");
                    builder.AppendLine("<tr>");
                    builder.AppendLine("<th>Producteur</th>");
                    builder.AppendLine("<th>Produit</th>");
                    builder.AppendLine("<th>Quantité</th>");
                    builder.AppendLine("</tr>");

                    foreach (var producerBillsEntry in billEntryByProducer.OrderBy(x => x.Key.AdherentStolon.Adherent.CompanyName))
                    {
                        builder.AppendLine("<tr>");
                        builder.AppendLine("<td colspan=\"3\" style=\"border-top:1px solid;\">" + "<b>" + producerBillsEntry.Key.AdherentStolon.Adherent.CompanyName + "</b>" + "</td>");
                        builder.AppendLine("</tr>");
                        foreach (var billEntry in producerBillsEntry.OrderBy(x => x.ProductStock.Product.Name))
                        {
                            builder.AppendLine("<tr>");
                            builder.AppendLine("<td></td>");
                            builder.AppendLine("<td>" + billEntry.ProductStock.Product.Name + "</td>");
                            builder.AppendLine("<td>" + billEntry.QuantityString + "</td>");
                            builder.AppendLine("</tr>");
                        }
                    }
                    builder.AppendLine("</table>");
                    if (count != consumersBills.Count)
                    {
                        builder.AppendLine("<div style=\"page-break-after:always\"></div>");
                    }
                }


                /*
                 * foreach (ValidatedWeekBasket tempWeekBasket in consumerWeekBaskets.OrderBy(x => x.AdherentStolon.LocalId))
                 * {
                 * ValidatedWeekBasket weekBasket = dbContext.ValidatedWeekBaskets.Include(x => x.BillEntries).First(x => x.Id == tempWeekBasket.Id);
                 * weekBasket.BillEntries.ForEach(x => x = dbContext.BillEntrys.First(b => b.Id == x.Id));
                 * bill.Amount += weekBasket.TotalPrice;
                 * //
                 * builder.AppendLine("<h1>Adhérent : " + weekBasket.AdherentStolon.LocalId + " / " + weekBasket.Adherent.Surname + " / " + weekBasket.Adherent.Name + "</h1>");
                 * builder.AppendLine("<p>Facture : " + billNumber + "_" + weekBasket.Consumer.Id + "</p>");
                 * builder.AppendLine("<p>Téléphone : " + weekBasket.Consumer.PhoneNumber + "</p>");
                 * builder.AppendLine("<p>Total à régler : " + weekBasket.TotalPrice.ToString("0.00") + " €</p>");
                 *
                 *
                 * //Create list of bill entry by product
                 * Dictionary<Adherent, List<BillEntry>> producersProducts = new Dictionary<Adherent, List<BillEntry>>();
                 * foreach (var billEntryConsumer in weekBasket.BillEntries)
                 * {
                 * var billEntry = dbContext.BillEntrys.Include(x => x.Product).ThenInclude(x => x.Producer).First(x => x.Id == billEntryConsumer.Id);
                 * if (!producersProducts.ContainsKey(billEntry.Product.Producer))
                 * {
                 * producersProducts.Add(billEntry.Product.Producer, new List<BillEntry>());
                 * }
                 * producersProducts[billEntry.Product.Producer].Add(billEntry);
                 * }
                 * List<int> rowsTotal = new List<int>();
                 * // - Add products by producer
                 * builder.AppendLine("<h2>Commande par producteur</h2>");
                 *
                 * builder.AppendLine("<table class=\"table\">");
                 * builder.AppendLine("<tr>");
                 * builder.AppendLine("<th>Producteur</th>");
                 * builder.AppendLine("<th>Produit</th>");
                 * builder.AppendLine("<th>Quantité</th>");
                 * builder.AppendLine("</tr>");
                 *
                 * foreach (var producer in producersProducts.Keys.OrderBy(x => x.Id))
                 * {
                 * builder.AppendLine("<tr>");
                 * builder.AppendLine("<td colspan=\"3\" style=\"border-top:1px solid;\">" + "<b>" + producer.CompanyName + "</b>" + "</td>");
                 * builder.AppendLine("</tr>");
                 * foreach (var billEntry in producersProducts[producer].OrderBy(x => x.Product.Name))
                 * {
                 * builder.AppendLine("<tr>");
                 * builder.AppendLine("<td></td>");
                 * builder.AppendLine("<td>" + billEntry.Product.Name + "</td>");
                 * builder.AppendLine("<td>" + billEntry.QuantityString + "</td>");
                 * builder.AppendLine("</tr>");
                 *
                 * }
                 * }
                 * builder.AppendLine("</table>");
                 * builder.AppendLine("<divstyle=\"page-break-after:always;\">");
                 * }
                 */
            }
            builder.AddBootstrap();
            builder.AddFooterAndHeaderRemoval();
            bill.HtmlBillContent = builder.ToString();
            //TODO envisager de créer les HtmlBillContent via des cshtml plutot que comme ca

            return(bill);
        }
Пример #24
0
        private static void TriggerDeliveryAndStockUpdateMode(Stolon stolon, ApplicationDbContext dbContext)
        {
            //Consumer (create bills)
            List <ValidatedWeekBasket> consumerWeekBaskets = dbContext.ValidatedWeekBaskets
                                                             .Include(x => x.BillEntries)
                                                             .Include(x => x.AdherentStolon)
                                                             .Include(x => x.AdherentStolon.Stolon)
                                                             .Include(x => x.AdherentStolon.Adherent)
                                                             .Where(x => x.AdherentStolon.StolonId == stolon.Id)
                                                             .ToList();

            foreach (var weekBasket in consumerWeekBaskets)
            {
                //Remove TempWeekBasket and linked billEntry
                var tempWeekBasketToRemove = dbContext.TempsWeekBaskets.FirstOrDefault(x => x.AdherentStolonId == weekBasket.AdherentStolon.Id);
                if (tempWeekBasketToRemove == null)
                {
                    continue;
                }
                var linkedBillEntriesToRemove = dbContext.BillEntrys.Where(x => x.TempWeekBasketId == tempWeekBasketToRemove.Id).ToList();
                dbContext.RemoveRange(linkedBillEntriesToRemove);
                dbContext.SaveChanges();
                dbContext.Remove(tempWeekBasketToRemove);
                dbContext.SaveChanges();
                //Creates new bill entryes
                List <BillEntry> billEntries = new List <BillEntry>();
                foreach (var oldBillEntry in weekBasket.BillEntries.ToList())
                {
                    BillEntry newBillEntry = oldBillEntry.Clone();
                    billEntries.Add(newBillEntry);
                    dbContext.Remove(oldBillEntry);
                    dbContext.Add(newBillEntry);
                    dbContext.SaveChanges();
                }
                dbContext.Remove(weekBasket);
                dbContext.SaveChanges();

                //Generate bill for consumer
                ConsumerBill consumerBill = CreateBill <ConsumerBill>(weekBasket.AdherentStolon, billEntries);
                consumerBill.HtmlBillContent = GenerateHtmlBillContent(consumerBill, dbContext);
                dbContext.Add(consumerBill);
                dbContext.SaveChanges();
            }

            List <ProducerBill> producerBills = new List <ProducerBill>();
            List <ConsumerBill> consumerBills = dbContext.ConsumerBills
                                                .Include(x => x.BillEntries)
                                                .ThenInclude(x => x.ProductStock)
                                                .ThenInclude(x => x.Product)
                                                .Include(x => x.AdherentStolon)
                                                .Include(x => x.AdherentStolon.Adherent)
                                                .Include(x => x.AdherentStolon.Stolon)
                                                .Where(x => x.AdherentStolon.Stolon.Id == stolon.Id && x.EditionDate.GetIso8601WeekOfYear() == DateTime.Now.GetIso8601WeekOfYear() && x.EditionDate.Year == DateTime.Now.Year)
                                                .ToList();

            //Producer (creates bills)
            foreach (var producer in dbContext.AdherentStolons.Include(x => x.Adherent).Include(x => x.Stolon).Where(x => x.StolonId == stolon.Id && x.IsProducer).ToList())
            {
                List <BillEntry> billEntries = new List <BillEntry>();
                foreach (var consumerBill in consumerBills)
                {
                    foreach (var billEntry in consumerBill.BillEntries.Where(billEntry => billEntry.ProductStock.Product.ProducerId == producer.AdherentId))
                    {
                        billEntries.Add(billEntry);
                    }
                }
                //Generate bill for producer
                ProducerBill bill = CreateBill <ProducerBill>(producer, billEntries);
                bill.HtmlBillContent  = GenerateHtmlBillContent(bill, dbContext);
                bill.HtmlOrderContent = GenerateHtmlOrderContent(bill, dbContext);
                producerBills.Add(bill);
                if (billEntries.Any())
                {
                    dbContext.Add(bill);
                    dbContext.SaveChanges();
                }
            }

            //Stolons
            StolonsBill stolonsBill = GenerateBill(stolon, consumerBills, dbContext);

            stolonsBill.Producers = producerBills.Count;
            if (dbContext.StolonsBills.Any(x => x.BillNumber == stolonsBill.BillNumber))
            {
                StolonsBill tempBill = dbContext.StolonsBills.FirstOrDefault(x => x.BillNumber == stolonsBill.BillNumber);
                tempBill.Amount          = stolonsBill.Amount;
                tempBill.EditionDate     = stolonsBill.EditionDate;
                tempBill.HtmlBillContent = stolonsBill.HtmlBillContent;
                tempBill.ProducersFee    = stolonsBill.ProducersFee;
            }
            else
            {
                dbContext.Add(stolonsBill);
            }

            dbContext.SaveChanges();
            //Move stolon's products to stock
            foreach (ProductStockStolon productStock in dbContext.ProductsStocks.Include(x => x.AdherentStolon).Include(x => x.Product).Where(x => x.AdherentStolon.StolonId == stolon.Id).ToList())
            {
                if (productStock.State == ProductState.Enabled && productStock.Product.StockManagement == StockType.Week)
                {
                    productStock.State          = ProductState.Stock;
                    productStock.RemainingStock = productStock.WeekStock;
                }
            }
            //

            dbContext.SaveChanges();
            //For stolons
            try
            {
                GeneratePDF(stolonsBill.HtmlBillContent, stolonsBill.GetStolonBillFilePath());
            }
            catch (Exception exept)
            {
                AuthMessageSender.SendEmail(stolon.Label,
                                            Configurations.Application.ContactMailAddress,
                                            "Stolons",
                                            "Erreur lors de la génération de la facture Stolons",
                                            "Message d'erreur : " + exept.Message);
            }

            // => Producer, send mails
            foreach (var bill in producerBills)
            {
                Task.Factory.StartNew(() => { GenerateOrderPdfAndSendEmail(bill); });
            }

            //Bills (save bills and send mails to user)
            foreach (var bill in consumerBills)
            {
                Task.Factory.StartNew(() => { GenerateOrderPdfAndSendEmail(bill); });
            }
        }
Пример #25
0
 public TransactionsViewModel(AdherentStolon activeAdherentStolon, Stolon stolon, List <Transaction> transactions)
 {
     ActiveAdherentStolon = activeAdherentStolon;
     Stolon       = stolon;
     Transactions = transactions;
 }
Пример #26
0
 public SympathizerViewModel(AdherentStolon activeAdherentStolon, Sympathizer sympathizer, Stolon stolon = null)
 {
     Sympathizer          = sympathizer;
     ActiveAdherentStolon = activeAdherentStolon;
     Stolon = stolon == null ? Sympathizer.Stolon : stolon;
 }
Пример #27
0
        public IActionResult ValidateBasket(string basketId)
        {
            var    adherentStolon = GetActiveAdherentStolon();
            Stolon stolon         = GetCurrentStolon();

            if (stolon.GetMode() == Stolon.Modes.DeliveryAndStockUpdate)
            {
                return(Redirect("Index"));
            }
            //TempWeekBasket tempWeekBasket = _context.TempsWeekBaskets.Include(x => x.BillEntries).Include(x => x.AdherentStolon).AsNoTracking().FirstOrDefault(x => x.Id.ToString() == basketId);
            //tempWeekBasket.RetrieveProducts(_context);
            ValidatedWeekBasket validatedWeekBasket = _context.ValidatedWeekBaskets.Include(x => x.AdherentStolon).ThenInclude(x => x.Adherent).Include(x => x.BillEntries).FirstOrDefault(x => x.AdherentStolonId == adherentStolon.Id);

            if (validatedWeekBasket == null)
            {
                //First validation of the week
                validatedWeekBasket = new ValidatedWeekBasket
                {
                    BillEntries    = new List <BillEntry>(),
                    AdherentStolon = adherentStolon
                };
                _context.Add(validatedWeekBasket);
                _context.SaveChanges();
            }
            else
            {
                validatedWeekBasket.RetrieveProducts(_context);
            }
            TempWeekBasket tempWeekBasket = _context.TempsWeekBaskets.Include(x => x.BillEntries).Include(x => x.AdherentStolon).FirstOrDefault(x => x.Id.ToString() == basketId);

            tempWeekBasket.RetrieveProducts(_context);
            //TODO LOCK to prevent multi insert at this moment ?
            if (tempWeekBasket.BillEntries.Any())
            {
                List <BillEntry> rejectedEntries = new List <BillEntry>();
                //Sauvegarde des produits déja validés
                List <BillEntry> previousBillEntries = validatedWeekBasket.BillEntries;
                //On met le panier validé dans le même état que le temporaire
                validatedWeekBasket.BillEntries = new List <BillEntry>();
                foreach (BillEntry billEntry in tempWeekBasket.BillEntries.ToList())
                {
                    validatedWeekBasket.BillEntries.Add(billEntry.Clone());
                }

                //Gestion de la suppression et du changement de quantité sur des billEntry existantes
                foreach (BillEntry prevEntry in previousBillEntries)
                {
                    BillEntry          newEntry     = validatedWeekBasket.BillEntries.FirstOrDefault(x => x.ProductStockId == prevEntry.ProductStockId);
                    ProductStockStolon productStock = _context.ProductsStocks.Include(x => x.Product).Include(x => x.AdherentStolon).Single(x => x.Id == prevEntry.ProductStockId);

                    if (newEntry == null)
                    {
                        //produit supprimé du panier
                        UpdateProductStock(productStock, prevEntry.Quantity);
                    }
                    else
                    {
                        int     qtyDiff   = newEntry.Quantity - prevEntry.Quantity;
                        decimal stepStock = productStock.RemainingStock;
                        if (productStock.Product.Type != Product.SellType.Piece)
                        {
                            //Actual remaining stock in terms of quantity step Kg/L for weight type products
                            stepStock = (productStock.RemainingStock / productStock.Product.QuantityStep) * 1000.0M;
                        }
                        if (stepStock < qtyDiff && productStock.Product.StockManagement != Product.StockType.Unlimited)
                        {
                            //Stock insuffisant, on supprime la nouvelle ligne et on garde l'ancienne
                            validatedWeekBasket.BillEntries.Remove(newEntry);
                            validatedWeekBasket.BillEntries.Add(prevEntry);
                            rejectedEntries.Add(newEntry);
                        }
                        else
                        {
                            UpdateProductStock(productStock, -qtyDiff);
                            //On supprime la bill entry précédente ( ancienne bill entry)
                            _context.BillEntrys.Remove(prevEntry);
                        }
                    }
                }

                //Gestion de l'ajout de produits
                foreach (BillEntry newEntry in validatedWeekBasket.BillEntries.ToList())
                {
                    BillEntry prevEntry = previousBillEntries.FirstOrDefault(x => x.ProductStockId == newEntry.ProductStockId);

                    if (prevEntry == null)
                    {
                        //Nouveau produit
                        ProductStockStolon productStock = _context.ProductsStocks.Include(x => x.Product).Include(x => x.AdherentStolon).Single(x => x.Id == newEntry.ProductStockId);

                        decimal stepStock = productStock.RemainingStock;
                        if (productStock.Product.Type != Product.SellType.Piece)
                        {
                            stepStock = (productStock.RemainingStock / productStock.Product.QuantityStep) * 1000.0M;
                        }
                        if (newEntry.Quantity <= stepStock || productStock.Product.StockManagement == Product.StockType.Unlimited)
                        {
                            //product.RemainingStock -= newEntry.Quantity;
                            UpdateProductStock(productStock, -newEntry.Quantity);
                        }
                        else
                        {
                            validatedWeekBasket.BillEntries.Remove(newEntry);
                            rejectedEntries.Add(newEntry);
                        }
                    }
                }

                _context.SaveChanges();
                //On supprime toute les BillEntry du tempWeekBasket
                _context.BillEntrys.RemoveRange(_context.BillEntrys.Where(x => x.TempWeekBasketId == tempWeekBasket.Id).ToList());
                _context.SaveChanges();
                //On met le panier temporaire dans le même état que le validé
                foreach (BillEntry entry in validatedWeekBasket.BillEntries)
                {
                    tempWeekBasket.BillEntries.Add(entry.Clone());
                }
                tempWeekBasket.Validated = true;

                _context.SaveChanges();
                //END LOCK TODO

                //Recuperation du detail produit pour utilisation dans la Vue
                validatedWeekBasket.RetrieveProducts(_context);

                //Send email to user
                string subject;
                if (rejectedEntries.Count == 0)
                {
                    subject = "Validation de votre panier de la semaine";
                }
                else
                {
                    subject = "Validation partielle de votre panier de la semaine";
                }
                ValidationSummaryViewModel validationSummaryViewModel = new ValidationSummaryViewModel(adherentStolon, validatedWeekBasket, rejectedEntries)
                {
                    Total = GetBasketPrice(validatedWeekBasket)
                };
                Services.AuthMessageSender.SendEmail(adherentStolon.Stolon.Label, validatedWeekBasket.AdherentStolon.Adherent.Email, validatedWeekBasket.AdherentStolon.Adherent.Name, subject, base.RenderPartialViewToString("Templates/ValidatedBasketTemplate", validationSummaryViewModel));
                //Return view
                return(View("ValidatedBasket", validationSummaryViewModel));
            }
            else
            {
                //On annule tout le contenu du panier
                foreach (BillEntry entry in validatedWeekBasket.BillEntries)
                {
                    ProductStockStolon productStock = _context.ProductsStocks.Include(x => x.Product).Include(x => x.AdherentStolon).Single(x => x.Id == entry.ProductStockId);
                    UpdateProductStock(productStock, entry.Quantity);
                    //entry.Product.RemainingStock += entry.Quantity;
                }
                _context.Remove(tempWeekBasket);
                _context.Remove(validatedWeekBasket);
                _context.SaveChanges();

                //Il ne commande rien du tout
                //On lui signale
                Services.AuthMessageSender.SendEmail(stolon.Label, validatedWeekBasket.AdherentStolon.Adherent.Email, validatedWeekBasket.AdherentStolon.Adherent.Name, "Panier de la semaine annulé", base.RenderPartialViewToString("Templates/ValidatedBasketTemplate", null));
            }
            return(View("ValidatedBasket"));
        }
Пример #28
0
 public AdherentTransaction(Adherent adherent, Stolon stolon, TransactionType type, TransactionCategory category, decimal amount, string description, bool addedAutomaticly = true) :
     base(stolon, type, category, amount, description, addedAutomaticly)
 {
     Adherent = adherent;
 }
Пример #29
0
        public virtual PartialViewResult _PartialCreateAdherent(AdherentEdition edition, Guid?stolonId = null)
        {
            Stolon stolon = stolonId == null?GetCurrentStolon() : _context.Stolons.First(x => x.Id == stolonId);

            return(PartialView(new AdherentViewModel(GetActiveAdherentStolon(), new Adherent(), stolon, edition)));
        }
Пример #30
0
 public StolonViewModel(AdherentStolon activeAdherentStolon, Stolon stolon)
 {
     base.ActiveAdherentStolon = activeAdherentStolon;
     Stolon = stolon;
 }