Exemplo n.º 1
0
        public IActionResult Index([FromForm] DonationViewModel model)
        {
            ViewBag.Title = "Przekazano dary";
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            if (IsModelValid(model, out _errors))
            {
                var list = new List <string>();
                foreach (var item in model.CategoriesList)
                {
                    if (item.IsChecked == true)
                    {
                        list.Add(item.CategoryId);
                    }
                }
                if (User.Identity.IsAuthenticated)
                {
                    string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
                    model.User = _userManager.FindByIdAsync(userId).Result;
                }

                _donationService.Create(model, list);
                return(View("confirmation"));
            }
            _errors.ForEach(e => ModelState.AddModelError("", e));
            return(View(model));
        }
        public List <DonationViewModel> GetDonations(int donorId)
        {
            var results = new List <DonationViewModel>();

            List <DbParameter> parameters = new List <DbParameter>
            {
                new SqlParameter("donorId", donorId)
            };

            using (IDataReader reader = ExecuteReader("GetDonations", DbCommandType.StoredProcedure, parameters))
            {
                while (reader.Read())
                {
                    DonationViewModel donation = new DonationViewModel
                    {
                        expenseId = (int)reader["expenseId"],

                        expenseName = (string)reader["expenseName"],

                        beneficiaryId = (int)reader["beneficiaryId"],

                        beneficiaryName = (string)reader["beneficiaryName"],

                        donationTime = (DateTime)reader["donationTime"],

                        donationAmt = (int)reader["donationAmt"]
                    };

                    results.Add(donation);
                }
            }

            return(results);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Donate(DonationViewModel viewModel)
        {
            // checking modelState Errors
            var errors = ModelState
                         .Where(x => x.Value.Errors.Count > 0)
                         .Select(x => new { x.Key, x.Value.Errors })
                         .ToArray();

            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }


            var categories     = viewModel.CheckBoxItems.Where(x => x.IsChecked).ToList();
            var categoriesList = new List <DonationCategory>();

            foreach (var category in categories)
            {
                categoriesList.Add(new DonationCategory {
                    CategoryId = category.id, DonationId = viewModel.Id
                });
            }

            //Handle for registered and logged user
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                ModelState.AddModelError("", "Błąd w tworzenia darowizny");
                return(View(viewModel));
            }


            var donation = new Donation()
            {
                PhoneNumber   = viewModel.PhoneNumber,
                City          = viewModel.City,
                Street        = viewModel.Street,
                ZipCode       = viewModel.ZipCode,
                Quantity      = viewModel.Quantity,
                PickUpDate    = viewModel.PickUpDate,
                PickUpTime    = viewModel.PickUpTime,
                PickUpComment = viewModel.PickUpComment,
                Categories    = categoriesList,
                Institution   = await _institutionService.GetAsync(viewModel.Institution.Id),
                User          = await _userManager.GetUserAsync(User)
            };

            var result = await _donationService.CreateAsync(donation);

            if (result == false)
            {
                ModelState.AddModelError("", "Błąd w tworzenia darowizny");
                return(View(viewModel));
            }


            return(RedirectToAction("Confirmation"));
        }
Exemplo n.º 4
0
        public DonationModel Add(DonationViewModel donationView)
        {
            DonationModel donation           = null;
            var           institutionService = new InstitutionService(Context);
            var           categoryService    = new CategoryService(Context);

            try
            {
                List <CategoryModel> categories = new List <CategoryModel>();
                foreach (string id in donationView.CategoriesIds)
                {
                    if (id != "false")
                    {
                        categories.Add(categoryService.GetOne(Int32.Parse(id)));
                    }
                }
                donation = new DonationModel()
                {
                    Quantity      = donationView.Quantity,
                    Institution   = institutionService.GetOne(donationView.InstitutionId),
                    Categories    = categories,
                    Street        = donationView.Street,
                    City          = donationView.City,
                    ZipCode       = donationView.ZipCode,
                    PickUpTime    = donationView.PickUpTime,
                    PickUpComment = donationView.PickUpComment,
                    Phone         = donationView.Phone
                };
                Context.Donations.Add(donation);
                Context.SaveChanges();
            }
            catch (Exception ex) { Console.WriteLine(ex.Message + "\n" + ex.InnerException); }
            return(donation);
        }
Exemplo n.º 5
0
        public bool Create(DonationViewModel donation, List <string> categoriesId)
        {
            var model = new Donation();

            model.Institution      = _institutionService.Get(donation.InstitutionId.ToString());
            model.PickUpTime       = donation.PickUpDateOn.AddHours(donation.PickUpTimeOn.Hour).AddMinutes(donation.PickUpTimeOn.Hour);
            model.DonationId       = Guid.NewGuid().ToString();
            model.City             = donation.City;
            model.DonationQuantity = donation.DonationQuantity;
            model.PhoneNumber      = donation.PhoneNumber;
            model.Street           = donation.Street;
            model.ZipCode          = donation.ZipCode;
            model.PickUpComment    = donation.PickUpComment;
            model.User             = donation.User;

            _context.Donations.Add(model);
            _context.SaveChanges();
            var donationsCategory = new List <DonationCategory>();

            foreach (var item in categoriesId)
            {
                donationsCategory.Add(new DonationCategory()
                {
                    CategoryId = item, DonationId = model.DonationId, Id = Guid.NewGuid().ToString()
                });
            }
            _context.AddRange(donationsCategory);
            return(_context.SaveChanges() > 0);
        }
Exemplo n.º 6
0
        public void Create(DonationViewModel model)
        {
            try
            {
                var sql = @"SET IDENTITY_INSERT donation ON
                        INSERT INTO donation( id, parent_id, elec_code, senator_id, amount, representative_name,
                                             postal_code, address, occupation_id, receipt_no)
	                    VALUES (@id, @parent_id, @elec_code, @senator_id, @amount, @representative_name,
                                             @postal_code, @address, @occupation_id, @receipt_no)";
                using (var conn = _dbConnection.CreateConnection())
                {
                    var res = conn.Execute(sql, new
                    {
                        id                  = model.id,
                        parent_id           = model.parent_id,
                        elec_code           = model.elec_code,
                        senator_id          = model.senator_id,
                        amount              = model.amount,
                        representative_name = model.representative_name,
                        postal_code         = model.postal_code,
                        address             = model.address,
                        occupation_id       = model.occupation_id,
                        receipt_no          = model.receipt_no
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Update([FromRoute] long donationId, [FromBody] DonationViewModel viewModel)
        {
            var query  = new UpdateDonationCommand(donationId, viewModel);
            var result = await mediator.Send(query);

            return(Ok(result));
        }
Exemplo n.º 8
0
 public IActionResult Index()
 {
     ViewBag.Title = "Przekaż dary";
     try
     {
         var listCategory        = _categoryService.GetAll();
         var listInstitution     = _institutionService.GetAll();
         DonationViewModel model = new DonationViewModel();
         model.CategoriesList = new List <CategoryViewModel>();
         foreach (var item in listCategory)
         {
             model.CategoriesList.Add(new CategoryViewModel()
             {
                 CategoryId = item.CategoryId, CategoryName = item.CategoryName
             });
         }
         model.InstitutionsList = new List <InstitutionViewModel>();
         foreach (var item in listInstitution)
         {
             model.InstitutionsList.Add(new InstitutionViewModel()
             {
                 InstitutionId = item.InstitutionId, InstitutionTitle = item.InstitutionTitle, Description = item.Description
             });
         }
         return(View(model));
     }
     catch (Exception e)
     {
         throw;
     }
 }
Exemplo n.º 9
0
 public IActionResult Campaign()
 {
     try
     {
         var agent = Request.Headers["User-Agent"];
         Console.WriteLine(agent.ToString());
         ViewBag.Browser = agent.ToString();
         var model = new DonationViewModel()
         {
             DonationCycles = GetDonationCycles
         };
         return(View(model));
     }
     catch (Exception ex)
     {
         log = new EventLog()
         {
             EventId = (int)LoggingEvents.GET_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source
         };
         _loggerService.SaveEventLogAsync(log);
         return(RedirectToAction("Error", "Error500", new ErrorViewModel()
         {
             Error = ex.Message
         }));
     }
 }
        public ActionResult Donation()
        {
            string strCampaignId = Request.QueryString["campaignId"];


            if (String.IsNullOrEmpty(strCampaignId))
            {
                return(RespondResult(false, "参数无效。"));
            }

            Guid campaignId = Guid.Parse(strCampaignId);

            //递增活动页面PV
            _campaignManager.PageVisit(campaignId);

            DonationViewModel model = new DonationViewModel();

            model.CampaignBundle = _campaignManager.Donation.GetDonationBundle(campaignId);

            if (model.CampaignBundle == null || model.CampaignBundle.Empty)
            {
                //重定向到错误页面
                return(new RedirectResult(String.Format(
                                              "~/Home/ErrorView/?message={0}", "td8")));
            }


            model.JsApiConfig = DomainContext.GetJsApiConfig(HttpContext.Request.Url.ToString());
            model.JsApiConfig.JsApiList.Add("onMenuShareTimeline");
            model.JsApiConfig.JsApiList.Add("onMenuShareAppMessage");
            return(View(model));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Description,ReleasedDate,Category,NeedIds")] DonationViewModel donation)
        {
            if (id != donation.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(donation);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DonationExists(donation.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }

            return(View(donation));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> Create(DonationViewModel donationViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(donationViewModel));
            }

            Donation donation = new Donation
            {
                Amount   = donationViewModel.Amount,
                Type     = (DonationType)donationViewModel.DonationType,
                Date     = donationViewModel.Date,
                Member   = await _memberRepository.GetMember(donationViewModel.MemberId),
                MemberId = donationViewModel.MemberId
            };

            try
            {
                await _donationRepository.CreateEntity(donation);

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                InitializeDonation();
                return(View(DonationVM));
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Edit(Guid id, DonationViewModel donationViewModel)
        {
            if (id != donationViewModel.Id)
            {
                return(NotFound());
            }

            if (!ModelState.IsValid)
            {
                return(View(donationViewModel));
            }

            Donation donation = await _donationRepository.GetDonation(id);

            donation.Amount = donationViewModel.Amount;
            donation.Date   = donationViewModel.Date;
            donation.Member = await _memberRepository.GetMember(donationViewModel.MemberId);

            donation.MemberId = donationViewModel.MemberId;
            donation.Type     = (DonationType)donationViewModel.Type;

            try
            {
                await _donationRepository.UpdateEntity(donation);

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                /* DonationVM = new DonationViewModel(donation); */
                InitializeDonation();
                return(View(DonationVM));
            }
        }
Exemplo n.º 14
0
 public DonationController(IDonationRepository donationRepository, IMemberRepository memberRepository, IMapper mapper)
 {
     _donationRepository = donationRepository;
     _memberRepository   = memberRepository;
     _mapper             = mapper;
     DonationVM          = new DonationViewModel();
 }
Exemplo n.º 15
0
            private static List <DonationViewModel> PopulateDonation(MyHLShoppingCartView request)
            {
                List <DonationViewModel> result;

                if (request.DonationAmount > 0)
                {
                    result = new List <DonationViewModel>();
                    DonationViewModel donation;

                    if (request.OnBehalfDonationAmount > 0)
                    {
                        donation             = new DonationViewModel();
                        donation.Amount      = request.OnBehalfDonationAmount;
                        donation.Name        = request.OnBehalfDonationName;
                        donation.PhoneNumber = request.OnBehalfDonationContact;
                        donation.Type        = "OnBehalf";
                        result.Add(donation);
                    }

                    if (request.SelfDonationAmount > 0)
                    {
                        donation        = new DonationViewModel();
                        donation.Amount = request.SelfDonationAmount;
                        donation.Name   = request.SelfDonationMemberId;
                        donation.Type   = "Self";
                        result.Add(donation);
                    }

                    return(result);
                }
                return(null);
            }
        public ActionResult CreateDonation(DonationViewModel donationViewModel)
        {
            try
            {
                var userId = User.Identity.GetUserId();
                var user   = unitOfWork.UserRepository.Get(x => x.Id == userId).FirstOrDefault();

                Donation donation = new Donation()
                {
                    Amount       = 0,
                    BloodBank_Id = donationViewModel.BloodBank_Id,
                    DenialReason = "",
                    RhType       = user.RhType ?? RhType.X,
                    User_Id      = user.Id,
                    BloodType    = user.BloodType ?? BloodType.X,
                    Succesfull   = Stage.Pending
                };
                unitOfWork.DonationRepository.Insert(donation);
                unitOfWork.Save();

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                return(Content("Error"));
            }
        }
        public HttpResponseMessage Put(HttpRequestMessage request, DonationViewModel controPanelVM)
        {
            return(CreateHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                if (!ModelState.IsValid)
                {
                    response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
                else
                {
                    var DonationDb = _donationService.GetById(controPanelVM.ID);
                    DonationDb.UpdateDonation(controPanelVM);
                    DonationDb.UpdateDate = DateTime.Now;
                    DonationDb.UpdateBy = User.Identity.Name;
                    _donationService.Update(DonationDb);
                    _donationService.Save();

                    var responseData = Mapper.Map <Donation, DonationViewModel>(DonationDb);
                    response = request.CreateResponse(HttpStatusCode.Created, responseData);
                }
                return response;
            }));
        }
Exemplo n.º 18
0
        // GET: Donations/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var donation = await _context.Donation.FindAsync(id);

            if (donation == null)
            {
                return(NotFound());
            }

            List <Need> allNeeds       = _context.Needs.ToList();
            var         selectAllNeeds = allNeeds.Select(x => new SelectListItem()
            {
                Text = x.Description, Value = x.Id.ToString(), Selected = true
            });

            ViewData["needs"] = new MultiSelectList(selectAllNeeds, "Value", "Text");

            var viewModel = new DonationViewModel();

            viewModel.Id          = donation.Id;
            viewModel.Description = donation.Description;
            viewModel.Category    = donation.Category;
            viewModel.Owner       = _userManager.GetUserAsync(User).Result;

            viewModel.NeedIds = new List <int>();
            return(View(viewModel));
        }
Exemplo n.º 19
0
        public IActionResult Index()
        {
            var model = new DonationViewModel(_donationService.DonationOptions)
            {
                DonationCycles = GetDonationCycles
            };

            return(View(model));
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Create([FromBody] DonationViewModel viewModel)
        {
            var command = new CreateDonationCommand(viewModel);
            var result  = await mediator.Send(command);

            var locationUri = uriService.GetDonationUri(ApiRoutes.Donations.Get, result.DonationId.ToString());

            return(CreatedAtAction("CreateDonation", result));
        }
Exemplo n.º 21
0
        public IActionResult Add([FromForm] DonationViewModel donationView)
        {
            Service.Add(donationView);
            return(View("Confirmation"));

            // alternatywne podejscie:
            // zbierasz dane za pomoca ajaxa i zamiast przesylas modelu do widoku
            // ajax za pomoca inputow przesyla dane
        }
Exemplo n.º 22
0
 public IActionResult Donate(DonationViewModel model)
 {
     if (ModelState.IsValid)
     {
         var pesapalUrl = PostDonationToPesaPal(model);
         TempData["PesapalUrl"] = pesapalUrl;
         return(RedirectToAction("Confirm"));
     }
     return(View());
 }
Exemplo n.º 23
0
        public ActionResult CreateDonation(int?personId, int?organizationId)
        {
            var model = new DonationViewModel
            {
                PersonId       = personId,
                OrganizationId = organizationId
            };

            ViewBag.FundList = FinancialHelper.GetFundList();
            return(PartialView(model));
        }
Exemplo n.º 24
0
        // GET: DONATIONs
        public ActionResult Index(string searchString, string sortOrder, string dateMade, string dateRecieved, int?page)
        {
            int count      = 0;
            int pageSize   = 10;
            int pageNumber = (page ?? 1);

            ViewBag.CurrentSort = sortOrder;

            if (searchString == null)
            {
                ViewBag.DonationSortParam = String.IsNullOrEmpty(sortOrder) ? "donationID_desc" : "";
                ViewBag.DateSortParam     = sortOrder == "DateGiftRecieved" ? "dateRecieved_desc" : "DateGiftRecieved";

                var donations = from DONATION d in dnRepo.GetDonations()
                                select d;

                count = donations.Count();
                //used to remove features for non-admin users.
                string userId = User.Identity.GetUserId();
                var    user   = data.AspNetUsers.FirstOrDefault(p => p.Id == userId);
                ViewBag.role = user.NewRole;

                DonationViewModel dvm = new DonationViewModel();
                //dvm.Donations = donations.Take(count).ToPagedList(pageNumber, pageSize);

                switch (sortOrder)
                {
                case "donationID_desc":
                    donations = donations.OrderByDescending(d => d.DONOR.FName);
                    break;

                case "DateGiftRecieved":
                    donations = donations.OrderBy(d => d.DateRecieved);
                    break;

                case "dateRecieved_desc":
                    donations = donations.OrderByDescending(d => d.DateRecieved);
                    break;

                default:
                    donations = donations.OrderBy(d => d.DONOR.FName);
                    break;
                }
                return(View(donations.Take(count).ToPagedList(pageNumber, pageSize)));
            }
            else
            {
                IEnumerable <DONATION> donation = (IEnumerable <DONATION>)dnRepo.FindBy(searchString);
                count = donation.Count();

                return(View(donation.Take(count).ToPagedList(pageNumber, pageSize)));
            }
        }
Exemplo n.º 25
0
        // GET: Donation/Details/5
        public async Task <IActionResult> Details(Guid id)
        {
            Donation donation = await _donationRepository.GetDonation(id);

            if (donation == null)
            {
                return(NotFound());
            }

            DonationVM = new DonationViewModel(donation);
            return(View(DonationVM));
        }
Exemplo n.º 26
0
        public void IndexPost_InvalidForm_RedirectsToActionIndex()
        {
            // mock usermanager?
            var donationViewModel = new DonationViewModel()
            {
                Amount    = -50000,
                EventType = "Other"
            };
            var actionResult = _controller.Index(donationViewModel) as RedirectToActionResult;

            Assert.Equal("Result", actionResult?.ActionName); // idk why but this should go to "Index" (following example code here so, not questioning it)
        }
        // GET: Donation
        public ActionResult Index()
        {
            DonationViewModel model = new DonationViewModel();

            model.Receipts = donationService.TotalDonation();

            model.TotalDonation = donationService.TotalDonation();

            model.ThisMonthsDonation = donationService.TotalDonationThisMonth();

            model.ThisQuartersDonation = donationService.TotalDonationThisQuarter();

            model.ThisYearsDonation = donationService.TotalDonationThisYear();

            int count = 1;

            //donation by month for 2016
            //this should be pulled from an external resource
            string[] months = { "Fake", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            while (count < 13)
            {
                model.MonthlyDonation.Add(new MonthlyDonation {
                    Year = DateTime.Now.Year, Month = months[count], Donation = donationService.TotalDonationByMonth(DateTime.Now.Year, count)
                });
                count++;
            }


            //donation by quarter for 2016
            count = 1;
            while (count < 5)
            {
                model.QuarterlyDonation.Add(new QuarterlyDonation {
                    Year = DateTime.Now.Year, Quarter = count, Donation = donationService.TotalDonationByQuarter(2016, count)
                });
                count++;
            }

            //donation per annum for 2012 to 2016
            int year    = DateTime.Now.Year - 4;
            int endYear = DateTime.Now.Year;

            while (year <= endYear)
            {
                model.AnnualDonation.Add(new AnnualDonation {
                    Year = year, Donation = donationService.TotalDonationByYear(year)
                });
                year++;
            }


            return(View(model));
        }
Exemplo n.º 28
0
        public void IndexPost_ValidForm_RedirectsToActionResult()
        {
            // mock usermanager?
            _appVariableRepository.Setup(m => m.GetBy("TaxRate")).Returns(_dummyContext.TaxRate); // not needed (taxrate not shown)
            var donationViewModel = new DonationViewModel()
            {
                Amount    = 50000,
                EventType = "Other"
            };
            var actionResult = _controller.Index(donationViewModel) as RedirectToActionResult;

            Assert.Equal("Result", actionResult?.ActionName);
        }
Exemplo n.º 29
0
        public IActionResult Create(DonationViewModel donationViewModel)
        {
            _donationService.MakeDonationAsync(donationViewModel);

            if (_domainNotificationService.HasErrors)
            {
                AddDomainErrors();
                return(View(donationViewModel));
            }

            AddNotificationOfSuccessfulTransaction("Donation successful!<p>Thank you for supporting our cause :)</p>");
            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 30
0
        public ActionResult CreateDonation([Bind(Include = "Id,DonationDate,Amount,Fund,Designation,CheckNumber,PersonId,OrganizationId")] DonationViewModel model)
        {
            if (ModelState.IsValid)
            {
                var donation = model.MapToDonation();
                Database.Donations.Add(donation);
                Database.SaveChanges();
                return(ReturnToSender(model.PersonId, model.OrganizationId));
            }

            ViewBag.FundList = FinancialHelper.GetFundList();
            return(View(model));
        }