Ejemplo n.º 1
0
        public PopulateSubsidyBillingResult Step4(Step4Command command)
        {
            if (command.Period == default)
            {
                throw new Exception("Missing parameter: Period");
            }

            if (command.Period.Day != 1 || command.Period.Hour != 0 || command.Period.Minute != 0 || command.Period.Second != 0)
            {
                throw new Exception("Period must be midnight on the first day of the month.");
            }

            var startedAt = DateTime.Now;

            using (var conn = NewConnection())
            {
                conn.Open();

                var step4 = new BillingDataProcessStep4Subsidy(new Step4Config {
                    Connection = conn, Context = "ProcessRepository.Step4", Period = command.Period, ClientID = command.ClientID
                });

                PopulateSubsidyBillingResult result;

                switch (command.Command)
                {
                case "subsidy":
                    result = step4.PopulateSubsidyBilling();
                    break;

                case "distribution":
                    step4.DistributeSubsidyMoneyEvenly();
                    result = new PopulateSubsidyBillingResult(startedAt)
                    {
                        Command       = "distribution",
                        Period        = command.Period,
                        ClientID      = command.ClientID,
                        RowsExtracted = 0,
                        RowsDeleted   = 0,
                        RowsLoaded    = 0
                    };
                    break;

                default:
                    throw new Exception($"Unknown command: {command.Command}");
                }

                conn.Close();

                return(result);
            }
        }
Ejemplo n.º 2
0
        public UpdateClientBillingResult UpdateClientBilling(UpdateClientBillingCommand command)
        {
            if (command.Period == default)
            {
                throw new Exception("Missing parameter: Period");
            }

            if (command.Period.Day != 1)
            {
                throw new Exception("Period must be the first day of the month.");
            }

            using (var conn = NewConnection())
            {
                conn.Open();

                DateTime now = DateTime.Now;

                DateTime sd = command.Period;
                DateTime ed = command.Period.AddMonths(1);

                var toolDataClean = new WriteToolDataCleanProcess(new WriteToolDataCleanConfig {
                    Connection = conn, Context = "ProcessRepository.UpdateClientBilling", StartDate = sd, EndDate = ed, ClientID = command.ClientID
                });
                var toolData = new WriteToolDataProcess(WriteToolDataConfig.Create(conn, "ProcessRepository.UpdateClientBilling", sd, command.ClientID, 0, Cost.GetToolCosts(sd, 0)));

                var roomDataClean = new WriteRoomDataCleanProcess(new WriteRoomDataCleanConfig {
                    Connection = conn, Context = "ProcessRepository.UpdateClientBilling", StartDate = sd, EndDate = ed, ClientID = command.ClientID
                });
                var roomData = new WriteRoomDataProcess(new WriteRoomDataConfig {
                    Connection = conn, Context = "ProcessRepository.UpdateClientBilling", Period = sd, ClientID = command.ClientID, RoomID = 0
                });

                var pr1 = toolDataClean.Start();
                var pr2 = roomDataClean.Start();

                var pr3 = toolData.Start();
                var pr4 = roomData.Start();

                bool temp = DateTime.Now.FirstOfMonth() == command.Period;

                var step1 = new BillingDataProcessStep1(new Step1Config {
                    Connection = conn, Context = "ProcessRepository.UpdateClientBilling", Period = command.Period, Now = now, ClientID = command.ClientID, IsTemp = temp
                });

                var pr5 = step1.PopulateToolBilling();
                var pr6 = step1.PopulateRoomBilling();

                PopulateSubsidyBillingResult pr7 = null;

                if (!temp)
                {
                    var step4 = new BillingDataProcessStep4Subsidy(new Step4Config {
                        Connection = conn, Context = "ProcessRepository.UpdateClientBilling", Period = command.Period, ClientID = command.ClientID
                    });
                    pr7 = step4.PopulateSubsidyBilling();
                }

                var result = new UpdateClientBillingResult
                {
                    WriteToolDataCleanProcessResult     = pr1,
                    WriteRoomDataCleanProcessResult     = pr2,
                    WriteToolDataProcessResult          = pr3,
                    WriteRoomDataProcessResult          = pr4,
                    PopulateToolBillingProcessResult    = pr5,
                    PopulateRoomBillingProcessResult    = pr6,
                    PopulateSubsidyBillingProcessResult = pr7
                };

                conn.Close();

                return(result);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            HttpContextBase ctx = new HttpContextWrapper(context);

            ctx.Response.ContentType = "application/json";

            string command = ctx.Request["Command"];

            int clientId = Utility.ConvertTo(ctx.Request["ClientID"], 0);

            DateTime period;

            object result;

            if (command == "update-billing")
            {
                period = Convert.ToDateTime(ctx.Request["Period"]);

                Provider.Billing.Process.UpdateBilling(new UpdateBillingArgs
                {
                    BillingCategory = BillingCategory.Tool | BillingCategory.Room,
                    ClientID        = clientId,
                    Periods         = new[] { period }
                });

                result = new { Error = false, Message = "ok" };
            }
            else if (command == "reservation-history-billing-update")
            {
                bool            error                    = false;
                string          msg                      = "OK!";
                DataCleanResult dataCleanResult          = null;
                DataResult      dataResult               = null;
                Step1Result     step1Result              = null;
                PopulateSubsidyBillingResult step4Result = null;

                bool isTemp;

                try
                {
                    period = Convert.ToDateTime(ctx.Request["Period"]);

                    isTemp = Utility.IsCurrentPeriod(period);

                    dataCleanResult = Provider.Billing.Process.DataClean(new DataCleanCommand
                    {
                        BillingCategory = BillingCategory.Tool | BillingCategory.Room,
                        ClientID        = clientId,
                        StartDate       = period,
                        EndDate         = period.AddMonths(1)
                    });

                    dataResult = Provider.Billing.Process.Data(new DataCommand
                    {
                        BillingCategory = BillingCategory.Tool | BillingCategory.Room,
                        ClientID        = clientId,
                        Period          = period,
                        Record          = 0
                    });

                    step1Result = Provider.Billing.Process.Step1(new Step1Command
                    {
                        BillingCategory = BillingCategory.Tool | BillingCategory.Room,
                        ClientID        = clientId,
                        Period          = period,
                        Record          = 0,
                        Delete          = true,
                        IsTemp          = isTemp
                    });

                    // [2022-01-06 jg] Adding subsidy calculation, not sure why this wasn't already being done. Definitely need to recalculate in case account is changed from
                    //      internal to external or vice versa.

                    step4Result = Provider.Billing.Process.Step4(new Step4Command
                    {
                        ClientID = clientId,
                        Period   = period,
                        Command  = "subsidy"
                    });

                    // [2022-01-06 jg] This error check does not work for staff because repair reservations exist in ToolDataClean
                    //      but are not added to ToolData (and subsequently ToolBilling), so ToolDataClean rows loaded
                    //      can be greater than ToolData rows loaded. So now it will be skipped if the client is staff.

                    var c = Provider.Data.Client.GetClient(clientId);
                    if (!c.HasPriv(ClientPrivilege.Staff))
                    {
                        var toolDataRowsLoaded      = dataResult.WriteToolDataProcessResult.RowsLoaded;
                        var toolDataCleanRowsLoaded = dataCleanResult.WriteToolDataCleanProcessResult.RowsLoaded;
                        var step1RowsLoaded         = step1Result.PopulateToolBillingProcessResult.RowsLoaded;

                        string errmsg = string.Empty;

                        if (toolDataRowsLoaded < toolDataCleanRowsLoaded)
                        {
                            errmsg += $" Tool data row count ({toolDataRowsLoaded}) is less than tool data clean row count ({toolDataCleanRowsLoaded}).";
                        }

                        if (step1RowsLoaded < toolDataRowsLoaded)
                        {
                            errmsg += $" Step1 row count ({step1RowsLoaded}) is less than tool data row count ({toolDataRowsLoaded}).";
                        }

                        var errorCheck =
                            toolDataRowsLoaded >= toolDataCleanRowsLoaded &&
                            step1RowsLoaded >= toolDataRowsLoaded;

                        if (!errorCheck)
                        {
                            throw new Exception($"A problem occurred when trying to update billing data. {errmsg} Period: {period:yyyy-MM-dd:HH:mm:ss}, ClientID: {clientId}, Rows Loaded: DataClean = {dataCleanResult.WriteToolDataCleanProcessResult.RowsLoaded}, Data = {dataResult.WriteToolDataProcessResult.RowsLoaded}, Step1 = {step1Result.PopulateToolBillingProcessResult.RowsLoaded}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    error = true;
                    msg   = ex.Message;
                    SendEmail.SendDebugEmail(clientId, "LNF.Web.Scheduler.Handlers.ReservationHandler.ProcessRequest", $"[DEBUG:{DateTime.Now:yyyy-MM-dd HH:mm:ss}] An error occurred while updating billing from the Reservation History page.", msg);
                }

                result = new { Error = error, Message = msg, DataCleanResult = dataCleanResult, DataResult = dataResult, Step1Result = step1Result, Step4Result = step4Result };
            }
            else if (command == "get-clients-for-reservation-history")
            {
                bool     isok = clientId > 0;
                DateTime sd, ed;

                if (string.IsNullOrEmpty(ctx.Request.Form["StartDate"]))
                {
                    sd = Reservations.MinReservationBeginDate;
                }
                else
                {
                    isok &= DateTime.TryParse(ctx.Request.Form["StartDate"], out sd);
                }

                if (string.IsNullOrEmpty(ctx.Request.Form["EndDate"]))
                {
                    ed = Reservations.MaxReservationEndDate;
                }
                else
                {
                    isok &= DateTime.TryParse(ctx.Request.Form["EndDate"], out ed);
                }

                IEnumerable <ReservationHistoryClient> clients = null;

                if (isok)
                {
                    clients = ReservationHistoryUtility.Create(Provider).SelectReservationHistoryClients(sd, ed, clientId);
                    result  = new { Error = false, Message = "OK", Clients = clients };
                }
                else
                {
                    result = new { Error = true, Message = "One or more parameters are invalid.", Clients = clients };
                }
            }
            else if (int.TryParse(ctx.Request["ReservationID"], out int reservationId))
            {
                switch (command)
                {
                case "start-reservation":
                    clientId = ctx.CurrentUser(Provider).ClientID;
                    result   = ReservationHandlerUtility.Start(ctx, Provider, reservationId, clientId);
                    break;

                case "get-reservation":
                    result = ReservationHandlerUtility.GetReservation(ctx, Provider, reservationId);
                    break;

                case "save-reservation-history":
                    string notes       = ctx.Request["Notes"];
                    double forgivenPct = Utility.ConvertTo(ctx.Request["ForgivenPct"], 0D);
                    int    accountId   = Utility.ConvertTo(ctx.Request["AccountId"], 0);
                    bool   emailClient = Utility.ConvertTo(ctx.Request["EmailClient"], false);

                    double chargeMultiplier = 1.00 - (forgivenPct / 100.0);

                    clientId = ctx.CurrentUser(Provider).ClientID;

                    var model = new ReservationHistoryUpdate()
                    {
                        ReservationID    = reservationId,
                        AccountID        = accountId,
                        ChargeMultiplier = chargeMultiplier,
                        Notes            = notes,
                        EmailClient      = emailClient,
                        ClientID         = clientId
                    };

                    bool   updateResult = Provider.Scheduler.Reservation.UpdateReservationHistory(model);
                    string msg          = updateResult ? "OK" : "An error occurred.";
                    result = new
                    {
                        Error   = !updateResult,
                        Message = msg
                    };

                    break;

                case "test":
                    result = new { Error = false, Message = "ok" };
                    break;

                case "":
                    throw new Exception("Missing parameter: command");

                default:
                    throw new Exception("Invalid command: " + command);
                }
            }
            else
            {
                throw new Exception("Missing parameter: command");
            }

            ctx.Response.Write(JsonConvert.SerializeObject(result));
        }