protected void Page_Load(object sender, EventArgs e) { // Get account int financialAccountId = Int32.Parse(Request.QueryString["FinancialAccountId"]); _account = FinancialAccount.FromIdentity(financialAccountId); int year = DateTime.Today.Year; if (!_authority.HasPermission(Permission.CanDoBudget, _account.OrganizationId, -1, Authorization.Flag.ExactOrganization)) { throw new UnauthorizedAccessException("Access Denied"); } this.ComboOwner.Authority = _authority; if (!Page.IsPostBack) { // Populate all data this.LabelBudgetYear.Text = year.ToString(); this.LabelAccount.Text = _account.Name; this.LabelOrganization.Text = _account.Organization.Name; this.TextBudget.Text = _account.GetBudget(year).ToString(CultureInfo.InvariantCulture); if (_account.Owner != null) { this.ComboOwner.Text = _account.Owner.Name + " (#" + _account.Owner.Identity.ToString() + ")"; } } // Page.Title = "Editing Budget: " + _account.Name + ", " + year.ToString(); }
/// <summary> /// Handles the Click event of the btnEdit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnEdit_Click(object sender, EventArgs e) { FinancialAccountService service = new FinancialAccountService(new RockContext()); FinancialAccount account = service.Get(hfAccountId.ValueAsInt()); ShowEditDetails(account); }
public static BudgetRemainder[] GetRemainingBudgets() { Dictionary <int, bool> accountLookup = GetAttestationRights(); if (accountLookup.Count == 0) { return(new BudgetRemainder[0]); } Organization organization = FinancialAccount.FromIdentity(accountLookup.Keys.First()).Organization; List <BudgetRemainder> result = new List <BudgetRemainder>(); int currentYear = DateTime.UtcNow.Year; foreach (int accountId in accountLookup.Keys) { FinancialAccount account = FinancialAccount.FromIdentity(accountId); Int64 remaining = account.GetBudgetCentsRemaining(currentYear); result.Add(new BudgetRemainder { AccountId = accountId, Remaining = remaining / 100.0 }); } return(result.ToArray()); }
/// <summary> /// Handles the Click event of the btnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnCancel_Click(object sender, EventArgs e) { if (hfAccountId.Value.Equals("0")) { int?parentAccountId = PageParameter("ParentAccountId").AsIntegerOrNull(); if (parentAccountId.HasValue) { // Cancelling on Add, and we know the parentGroupID, so we are probably in treeview mode, so navigate to the current page var qryParams = new Dictionary <string, string>(); if (parentAccountId != 0) { qryParams["AccountId"] = parentAccountId.ToString(); } qryParams["ExpandedIds"] = PageParameter("ExpandedIds"); NavigateToPage(RockPage.Guid, qryParams); } else { // Cancelling on Add. Return to Grid NavigateToPage(RockPage.Guid, null); } } else { // Cancelling on Edit. Return to Details FinancialAccountService service = new FinancialAccountService(new RockContext()); FinancialAccount account = service.Get(hfAccountId.ValueAsInt()); ShowReadonlyDetails(account); } }
private FinancialAccounts GetRootLevelResultAccounts() { Organization org = this.CurrentOrganization; if (org == null && Page.IsPostBack) { // If we're being called from Page_Init to create controls just to catch events, then this.CurrentOrganization won't be set. // We need to create it temporarily from a hidden field: org = Organization.FromIdentity(Int32.Parse(Request["ctl00$PlaceHolderMain$HiddenInitOrganizationId"])); } FinancialAccount yearlyResult = org.FinancialAccounts.CostsYearlyResult; FinancialAccounts allAccounts = FinancialAccounts.ForOrganization(org, FinancialAccountType.Result); // Select root accounts FinancialAccounts accounts = new FinancialAccounts(); foreach (FinancialAccount account in allAccounts) { if (account.ParentFinancialAccountId == 0 && account.Identity != yearlyResult.Identity) { accounts.Add(account); } } return(accounts); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="accountId">The account identifier.</param> public void ShowDetail(int accountId) { FinancialAccount account = null; bool editAllowed = UserCanEdit; if (!accountId.Equals(0)) { account = new FinancialAccountService(new RockContext()).Get(accountId); editAllowed = editAllowed || account.IsAuthorized(Authorization.EDIT, CurrentPerson); pdAuditDetails.SetEntity(account, ResolveRockUrl("~")); } if (account == null) { account = new FinancialAccount { Id = 0, IsActive = true }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } hfAccountId.Value = account.Id.ToString(); nbEditModeMessage.Text = string.Empty; if (editAllowed) { ShowEditDetails(account); } else { nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialAccount.FriendlyTypeName); ShowReadonlyDetails(account); } }
private static FinancialAccount CreateFinancialAccount( Guid guid, string name, string key, int?parentAccountId = null) { var account = _accountService.GetByGuids(new List <Guid> { guid }).FirstOrDefault(); if (null == account) { account = new FinancialAccount { Guid = guid, IsTaxDeductible = true, IsActive = true, IsPublic = true, Name = name, ForeignKey = key }; if (parentAccountId.HasValue) { account.ParentAccountId = parentAccountId.Value; } _accountService.Add(account); _rockContext.SaveChanges(true); } return(account); }
public static bool SetAccountParent(int accountId, int parentAccountId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (account.ParentFinancialAccountId == parentAccountId) { // no change return(true); } if (!PrepareAccountChange(account, authData, true)) { return(false); } FinancialAccount newParent = null; // to cover the root account case (reparenting to root) if (parentAccountId > 0) // the group parent IDs are -1 ... -4 { newParent = FinancialAccount.FromIdentity(parentAccountId); if (newParent.OrganizationId != authData.CurrentOrganization.Identity) { throw new ArgumentException("Parent account mismatches with organization identity"); } } account.Parent = newParent; return(true); }
protected void Page_Load (object sender, EventArgs e) { // Get account int financialAccountId = Int32.Parse(Request.QueryString["FinancialAccountId"]); _account = FinancialAccount.FromIdentity(financialAccountId); int year = DateTime.Today.Year; if (!_authority.HasPermission(Permission.CanDoBudget, _account.OrganizationId, -1, Authorization.Flag.ExactOrganization)) { throw new UnauthorizedAccessException("Access Denied"); } this.ComboOwner.Authority = _authority; if (!Page.IsPostBack) { // Populate all data this.LabelBudgetYear.Text = year.ToString(); this.LabelAccount.Text = _account.Name; this.LabelOrganization.Text = _account.Organization.Name; this.TextBudget.Text = _account.GetBudget(year).ToString(CultureInfo.InvariantCulture); if (_account.Owner != null) { this.ComboOwner.Text = _account.Owner.Name + " (#" + _account.Owner.Identity.ToString() + ")"; } } // Page.Title = "Editing Budget: " + _account.Name + ", " + year.ToString(); }
protected void ButtonAdd_Click(object sender, EventArgs e) { if (!_authority.HasPermission(Permission.CanDoEconomyTransactions, _transaction.OrganizationId, -1, Authorization.Flag.ExactOrganization)) { ScriptManager.RegisterStartupScript(this, Page.GetType(), "getlost", "alert ('You do not have access to change financial records.');", true); return; } int accountId = Int32.Parse(this.DropAccounts.SelectedValue); if (accountId == 0) { ScriptManager.RegisterStartupScript(this, Page.GetType(), "getlost", "alert ('Please select an account.');", true); return; } FinancialAccount account = FinancialAccount.FromIdentity(accountId); string amountString = this.TextAmount.Text; Double amount = Double.Parse(amountString, new CultureInfo("sv-SE")); // Register new row in transaction GetTransaction().AddRow(account, amount, _currentUser); PopulateGrid(); this.GridTransactionRows.Rebind(); this.TextAmount.Text = (-GetTransaction().Rows.AmountTotal).ToString("N2", new CultureInfo("sv-SE")); }
protected void Page_Load (object sender, EventArgs e) { // Get account int financialAccountId = Int32.Parse(Request.QueryString["FinancialAccountId"]); _account = FinancialAccount.FromIdentity(financialAccountId); int year = DateTime.Today.Year; if (!_authority.HasPermission(Permission.CanDoEconomyTransactions, _account.OrganizationId, -1, Authorization.Flag.ExactOrganization)) { throw new UnauthorizedAccessException("Access Denied"); } if (!Page.IsPostBack) { // Populate all data this.LabelAccount.Text = _account.Name; this.LabelOrganization.Text = _account.Organization.Name; this.TextTransactionTag.Text = _account.BankTransactionTag; if (_account.AssignedGeography != null) { this.DropGeographies.SelectedGeography = _account.AssignedGeography; } } // Page.Title = "Editing Budget: " + _account.Name + ", " + year.ToString(); }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="account">The account.</param> private void ShowEditDetails(FinancialAccount account) { if (account.Id == 0) { lActionTitle.Text = ActionTitle.Add(FinancialAccount.FriendlyTypeName).FormatAsHtmlTitle(); } else { lActionTitle.Text = account.Name.FormatAsHtmlTitle(); } hlInactive.Visible = !account.IsActive; SetEditMode(true); LoadDropDowns(); tbName.Text = account.Name; cbIsActive.Checked = account.IsActive; tbDescription.Text = account.Description; apParentAccount.SetValue(account.ParentAccount); ddlAccountType.SetValue(account.AccountTypeValueId); tbPublicName.Text = account.PublicName; cpCampus.SelectedCampusId = account.CampusId; tbGLCode.Text = account.GlCode; cbIsTaxDeductible.Checked = account.IsTaxDeductible; dtpStartDate.SelectedDate = account.StartDate; dtpEndDate.SelectedDate = account.EndDate; }
public void CreateExpandCollapseButton(GridItem item, string columnUniqueName) { if (item is GridDataItem) { FinancialAccount account = (FinancialAccount)item.DataItem; if (item.FindControl("MyExpandCollapseButton") == null) { Button button = new Button(); button.Click += new EventHandler(button_Click); button.CommandName = "ExpandCollapse"; button.CssClass = (item.Expanded) ? "rgCollapse" : "rgExpand"; button.ID = "MyExpandCollapseButton"; if (item.OwnerTableView.HierarchyLoadMode == GridChildLoadMode.Client) { string script = String.Format(@"$find(""{0}"")._toggleExpand(this, event); ToggleLineMode('{1}'); return false;", item.Parent.Parent.ClientID, account.Identity); button.OnClientClick = script; } int level = item.ItemIndexHierarchical.Split(':').Length; if (level > 1) { button.Style["margin-left"] = level * 10 + "px"; } TableCell cell = ((GridDataItem)item)[columnUniqueName]; cell.Controls.Add(button); cell.Controls.Add(new LiteralControl(" ")); cell.Controls.Add(new LiteralControl(((GridDataItem)item).GetDataKeyValue(columnUniqueName).ToString())); } } }
/// <summary> /// Returns a list of the ancestor FinancialAccounts of the specified FinancialAccount. /// If the ParentFinancialAccount property of the FinancialAccount is not populated, it is assumed to be a top-level node. /// </summary> /// <param name="financialAccount">The financial account.</param> /// <param name="ancestorFinancialAccountIds">The ancestor financial account ids.</param> /// <returns></returns> private List <int> GetFinancialAccountAncestorsIdList(FinancialAccount financialAccount, List <int> ancestorFinancialAccountIds = null) { if (ancestorFinancialAccountIds == null) { ancestorFinancialAccountIds = new List <int>(); } if (financialAccount == null) { return(ancestorFinancialAccountIds); } // If we have encountered this node previously in our tree walk, there is a recursive loop in the tree. if (ancestorFinancialAccountIds.Contains(financialAccount.Id)) { return(ancestorFinancialAccountIds); } // Create or add this node to the history stack for this tree walk. ancestorFinancialAccountIds.Insert(0, financialAccount.Id); ancestorFinancialAccountIds = this.GetFinancialAccountAncestorsIdList(financialAccount.ParentAccount, ancestorFinancialAccountIds); return(ancestorFinancialAccountIds); }
protected void DropYear_SelectedIndexChanged(object sender, EventArgs e) { int year = Int32.Parse(this.DropYear.SelectedValue); if (year < 2000) { return; } FinancialAccounts balanceAccounts = FinancialAccounts.ForOrganization(CurrentOrganization, FinancialAccountType.Balance); FinancialAccounts resultAccounts = FinancialAccounts.ForOrganization(CurrentOrganization, FinancialAccountType.Result); FinancialAccount ownCapital = CurrentOrganization.FinancialAccounts.DebtsEquity; FinancialAccount resultAsNoted = CurrentOrganization.FinancialAccounts.CostsYearlyResult; FinancialAccounts balancesWithoutCapital = FinancialAccounts.ForOrganization(CurrentOrganization, FinancialAccountType.Balance); balancesWithoutCapital.Remove(ownCapital); FinancialAccounts resultAccountsWithoutNotedResult = FinancialAccounts.ForOrganization(CurrentOrganization, FinancialAccountType.Result); resultAccountsWithoutNotedResult.Remove(CurrentOrganization.FinancialAccounts.CostsYearlyResult); Currency currency = CurrentOrganization.DefaultCountry.Currency; this.LabelResultsAll.Text = String.Format("{0} {1:N2}", currency.Code, resultAccounts.GetDeltaCents(new DateTime(year, 1, 1), new DateTime(year + 1, 1, 1)) / 100.0); this.LabelResultsNoted.Text = String.Format("{0} {1:N2}", currency.Code, resultAsNoted.GetDeltaCents(new DateTime(year, 1, 1), new DateTime(year + 1, 1, 1)) / 100.0); this.LabelEoyBalance.Text = String.Format("{0} {1:N2}", currency.Code, balanceAccounts.GetDeltaCents(new DateTime(1900, 1, 1), new DateTime(year + 1, 1, 1)) / 100.0); Int64 endOfLastYearCapital = ownCapital.GetDeltaCents(new DateTime(1900, 1, 1), new DateTime(year, 1, 1)); Int64 endOfSelectedYearCapital = ownCapital.GetDeltaCents(new DateTime(1900, 1, 1), new DateTime(year + 1, 1, 1)); this.LabelEolyOwnCapital.Text = String.Format("{0} {1:N2}", currency.Code, endOfLastYearCapital / 100.0); this.LabelEocyOwnCapital.Text = String.Format("{0} {1:N2}", currency.Code, endOfSelectedYearCapital / 100.0); this.LabelOwnCapitalDiff.Text = String.Format("{0} {1:N2}", currency.Code, (endOfSelectedYearCapital - endOfLastYearCapital) / 100.0); this.LabelOwnCapitalDelta.Text = String.Format("{0} {1:N2}", currency.Code, ownCapital.GetDeltaCents(new DateTime(year, 1, 1), new DateTime(year + 1, 1, 1)) / 100.0); }
/// <summary> /// Sets the value. /// </summary> /// <param name="account">The account.</param> public void SetValue(FinancialAccount account) { if (account != null) { ItemId = account.Id.ToString(); List <int> parentAccountIds = new List <int>(); var parentAccount = account.ParentAccount; while (parentAccount != null) { if (parentAccountIds.Contains(parentAccount.Id)) { // infinite recursion break; } parentAccountIds.Insert(0, parentAccount.Id); parentAccount = parentAccount.ParentAccount; } InitialItemParentIds = parentAccountIds.AsDelimited(","); ItemName = account.PublicName; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="account">The account.</param> private void ShowReadonlyDetails(FinancialAccount account) { SetEditMode(false); hfAccountId.SetValue(account.Id); lActionTitle.Text = account.Name.FormatAsHtmlTitle(); hlInactive.Visible = !account.IsActive; lAccountDescription.Text = account.Description; DescriptionList leftDescription = new DescriptionList(); leftDescription.Add("Public Name", account.PublicName); leftDescription.Add("Campus", account.Campus != null ? account.Campus.Name : string.Empty); leftDescription.Add("GLCode", account.GlCode); leftDescription.Add("Is Tax Deductible", account.IsTaxDeductible); lLeftDetails.Text = leftDescription.Html; var followingsFromDatabase = GetAccountParticipantStateFromDatabase().OrderBy(a => a.PersonFullName).ToList(); var accountParticipantsHtml = followingsFromDatabase.Select(a => $"{a.PersonFullName} ({a.PurposeKeyDescription})").ToList().AsDelimited("<br>\n"); DescriptionList rightDescription = new DescriptionList(); rightDescription.Add("Account Participants", accountParticipantsHtml); lRightDetails.Text = rightDescription.Html; account.LoadAttributes(); Helper.AddDisplayControls(account, Helper.GetAttributeCategories(account, true, false), phAttributesView, null, false); }
public static void InitializeProcessing(string guid, string accountIdString) { // Start an async thread that does all the work, then return AuthenticationData authData = GetAuthenticationDataAndCulture(); int accountId = Int32.Parse(accountIdString); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (account.Organization.Identity != authData.CurrentOrganization.Identity || !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write))) { throw new UnauthorizedAccessException(); } Thread initThread = new Thread(ProcessUploadThread); ProcessThreadArguments args = new ProcessThreadArguments { Guid = guid, Organization = authData.CurrentOrganization, Account = account }; initThread.Start(args); }
/// <summary> /// Creates the corepro customer and account. /// </summary> public void CreateCustomer() { if (_bankService.HasFinancialAccount()) { return; } var familyMember = _familyService.GetMember(); // Creates the corepro customer var customer = _coreproService.CreateCustomer(familyMember); // Creates the corepro account var accountId = _coreproService.CreateAccount(customer.CustomerId.Value, familyMember.Firstname); // Creates the new finance account var financialAccount = new FinancialAccount { CustomerID = customer.CustomerId.Value, AccountID = accountId, FamilyMemberID = _currentUserService.MemberID, }; Repository.Insert(financialAccount); }
public static void SetChequeStatusToCancelled(FinancialAccount financialAccount, DateTime today) { var loanAccount = financialAccount.LoanAccount; var application = financialAccount.Agreement.Application; var chequesAssoc = Context.ChequeApplicationAssocs.Where(entity => entity.ApplicationId == application.Id).ToList(); foreach (var cheque in chequesAssoc) { var check = cheque.Cheque; var currentChequeStatus = check.CurrentStatus; currentChequeStatus.IsActive = false; ChequeStatu newChequeStatus = CreateCancelledChequeStatus(check, today); var payment = check.Payment; //var receipt = payment.Receipt; var receipt = Context.ReceiptPaymentAssocs.FirstOrDefault(entity => entity.PaymentId == payment.Id).Receipt; var receiptCurrentStatus = receipt.CurrentStatus; receiptCurrentStatus.IsActive = false; ReceiptStatu newReceiptStatus = CreateCancelledReceiptStatus(receipt, today); } }
// GET: FinancialAccounts/Delete/5 public PartialViewResult Delete(int?id) { var userId = User.Identity.GetUserId(); var householdId = db.Users.Find(userId).HouseholdId; if (id == null) { return(PartialView("Reroute")); } FinancialAccount financialAccount = db.Accounts.Find(id); if (financialAccount == null) { return(PartialView("Reroute")); } if (financialAccount.AccountHolderUserId == userId) { return(PartialView(financialAccount)); } var NotYourAccount = "Sorry. You can only delete your own accounts."; TempData["NotYourAccountmessage"] = NotYourAccount; return(PartialView("Reroute")); }
public static OutboundComm CreateNotificationAttestationNeeded(FinancialAccount budget, Person concernedPerson, string supplier, double amountRequested, string purpose, NotificationResource notification) { NotificationPayload payload = new NotificationPayload(notification.ToString()); payload.Strings[NotificationString.CurrencyCode] = budget.Organization.Currency.Code; payload.Strings[NotificationString.OrganizationName] = budget.Organization.Name; payload.Strings[NotificationString.BudgetAmountFloat] = amountRequested.ToString(CultureInfo.InvariantCulture); payload.Strings[NotificationString.RequestPurpose] = purpose; payload.Strings[NotificationString.Description] = purpose; payload.Strings[NotificationString.Supplier] = supplier; payload.Strings[NotificationString.BudgetName] = budget.Name; payload.Strings[NotificationString.ConcernedPersonName] = concernedPerson.Canonical; OutboundComm comm = OutboundComm.Create(null, null, budget.Organization, CommResolverClass.Unknown, null, CommTransmitterClass.CommsTransmitterMail, new PayloadEnvelope(payload).ToXml(), OutboundCommPriority.Low); if (budget.OwnerPersonId == 0) { comm.AddRecipient(Person.FromIdentity(1)); // Add admin - not good, should be org admins // HACK // TODO } else { comm.AddRecipient(budget.Owner); } comm.Resolved = true; return(comm); }
public static void BalanceTransactionManually(int transactionId, int accountId) { if (transactionId == 0 || accountId == 0) { return; } AuthenticationData authData = GetAuthenticationDataAndCulture(); if ( !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails))) { throw new UnauthorizedAccessException(); } FinancialTransaction transaction = FinancialTransaction.FromIdentity(transactionId); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (transaction.OrganizationId != authData.CurrentOrganization.Identity || account.OrganizationId != authData.CurrentOrganization.Identity) { throw new UnauthorizedAccessException(); } transaction.AddRow(account, -transaction.Rows.AmountCentsTotal, authData.CurrentUser); }
private void PopulateControls() { Parleys parleys = Parleys.ForOwner(_currentUser); this.DropParleys.Items.Clear(); foreach (Parley parley in parleys) { this.DropParleys.Items.Add(new ListItem(parley.Name + " / " + parley.Organization.Name, parley.Identity.ToString())); } bool selectedParley = false; string accountParameterString = Request.QueryString["ParleyId"]; if (!String.IsNullOrEmpty(accountParameterString)) { int parleyId = Int32.Parse(accountParameterString); if (FinancialAccount.FromIdentity(parleyId).OwnerPersonId == _currentUser.Identity) { this.DropParleys.SelectedValue = parleyId.ToString(); } } if (this.DropParleys.SelectedIndex >= 0) { ViewState[this.ClientID + "_ParleyId"] = this.DropParleys.SelectedValue; PopulateParleyData(); } }
protected void GridBudgetAccounts_ItemCreated(object sender, GridItemEventArgs e) { // CreateExpandCollapseButton(e.Item, "Name"); if (e.Item is GridHeaderItem && e.Item.OwnerTableView != this.GridBudgetAccounts.MasterTableView) { e.Item.Style["display"] = "none"; } if (e.Item is GridNestedViewItem) { e.Item.Cells[0].Visible = false; } if (e.Item is GridDataItem) { FinancialAccount account = (FinancialAccount)e.Item.DataItem; if (account == null) { return; } int year = DateTime.Today.Year; HyperLink editLink = (HyperLink)e.Item.FindControl("ManageLink"); editLink.Attributes["href"] = "#"; editLink.Attributes["onclick"] = String.Format("return ShowBudgetForm('{0}','{1}');", account.FinancialAccountId, e.Item.ItemIndex); editLink.Visible = userHasChangeAuthority; Label labelAccountName = (Label)e.Item.FindControl("LabelAccountName"); Literal literalBudgetLast = (Literal)e.Item.FindControl("LiteralBudgetLastYear"); Literal literalActualsLast = (Literal)e.Item.FindControl("LiteralActualsLastYear"); Literal literalBudgetThis = (Literal)e.Item.FindControl("LiteralBudgetThisYear"); Literal literalActualsThis = (Literal)e.Item.FindControl("LiteralActualsThisYear"); Label labelOwner = (Label)e.Item.FindControl("LabelAccountOwner"); PopulateDualFigure(literalBudgetLast, "LastBudget", ColumnType.LastYearBudget, account.Identity); PopulateDualFigure(literalActualsLast, "LastActuals", ColumnType.LastYearActuals, account.Identity); PopulateDualFigure(literalBudgetThis, "ThisBudget", ColumnType.ThisYearBudget, account.Identity); PopulateDualFigure(literalActualsThis, "ThisActuals", ColumnType.ThisYearActuals, account.Identity); labelAccountName.Text = account.Name; Person owner = account.Owner; if (owner != null) { labelOwner.Text = owner.Initials; } else { labelOwner.Text = "---"; } } }
protected void GridBudgetAccounts_ItemCreated(object sender, GridItemEventArgs e) { // CreateExpandCollapseButton(e.Item, "Name"); if (e.Item is GridHeaderItem && e.Item.OwnerTableView != this.GridBudgetAccounts.MasterTableView) { e.Item.Style["display"] = "none"; } if (e.Item is GridNestedViewItem) { e.Item.Cells[0].Visible = false; } if (e.Item is GridDataItem) { int year = DateTime.Today.Year; FinancialAccount account = (FinancialAccount)e.Item.DataItem; if (account == null) { return; } HyperLink editLink = (HyperLink)e.Item.FindControl("ManageLink"); editLink.Attributes["href"] = "#"; editLink.Attributes["onclick"] = String.Format("return ShowAccountForm('{0}','{1}');", account.FinancialAccountId, e.Item.ItemIndex); PopulateLine(e.Item); } }
public static AjaxUploadCallResult UploadBankStatement(string guid, string itemId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); if (!authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails))) { throw new UnauthorizedAccessException(); } string[] parts = itemId.Split('-'); FinancialAccount account = FinancialAccount.FromIdentity(Int32.Parse(parts[1])); int yearMonth = Int32.Parse(parts[2]); DateTime statementStart = new DateTime(yearMonth / 100, yearMonth % 100, 1); if (account.OrganizationId != authData.CurrentOrganization.Identity) { throw new UnauthorizedAccessException(); } Documents documents = Documents.RecentFromDescription(guid); FinancialAccountDocument accountDoc = FinancialAccountDocument.Create(account, FinancialAccountDocumentType.BankStatement, authData.CurrentUser, statementStart, statementStart.AddMonths(1), string.Empty); documents.SetForeignObjectForAll(accountDoc); return(new AjaxUploadCallResult { Success = true, StillProcessing = false }); }
protected void PopulateLine(GridItem item) { FinancialAccount account = (FinancialAccount)item.DataItem; if (account == null) { return; } Label labelAccountName = (Label)item.FindControl("LabelAccountName"); Literal literalLastYear = (Literal)item.FindControl("LiteralLastYear"); Literal literalQ1 = (Literal)item.FindControl("LiteralQuarter1"); Literal literalQ2 = (Literal)item.FindControl("LiteralQuarter2"); Literal literalQ3 = (Literal)item.FindControl("LiteralQuarter3"); Literal literalQ4 = (Literal)item.FindControl("LiteralQuarter4"); Literal literalYtd = (Literal)item.FindControl("LiteralThisYear"); PopulateDualFigure(literalLastYear, "LastYear", 0, account.Identity); PopulateDualFigure(literalQ1, "Q1", 1, account.Identity); PopulateDualFigure(literalQ2, "Q2", 2, account.Identity); PopulateDualFigure(literalQ3, "Q3", 3, account.Identity); PopulateDualFigure(literalQ4, "Q4", 4, account.Identity); PopulateDualFigure(literalYtd, "Ytd", 5, account.Identity); labelAccountName.Text = account.Name; }
protected void ChargeBudget(FinancialAccount budget, double amount, string comment) { FinancialTransaction newTransaction = FinancialTransaction.Create(1, DateTime.Now, comment); newTransaction.AddRow(budget, amount, _currentUser); newTransaction.AddRow(Organization.FromIdentity(Organization.PPSEid).FinancialAccounts.CostsInfrastructure, -amount, _currentUser); }
protected void ButtonSetBudgets_Click(object sender, EventArgs e) { foreach (RepeaterItem repeaterItem in this.RepeaterAccountBudgets.Items) { HiddenField hiddenAccountId = (HiddenField)repeaterItem.FindControl("HiddenAccountId"); TextBox textBudget = (TextBox)repeaterItem.FindControl("TextBudget"); FinancialAccount account = FinancialAccount.FromIdentity(Int32.Parse(hiddenAccountId.Value)); // TODO: Possible race condition here, fix with HiddenField Int64 newBudgetAmount = Int64.Parse(textBudget.Text.Replace(",", "").Replace(" ", ""), Thread.CurrentThread.CurrentCulture); // TODO: May throw -- catch and send error message Int64 currentBudgetAmount = account.GetTree().GetBudgetSumCents(_year) / 100; // Set the new amount to the difference between the single budget of this account and the intended amount if (newBudgetAmount != currentBudgetAmount) { account.SetBudgetCents(_year, account.GetBudgetCents(_year) + (newBudgetAmount - currentBudgetAmount) * 100); } } // After updating budgets, rebind repeater FinancialAccounts accounts = GetRootLevelResultAccounts(); UpdateYearlyResult(accounts); this.RepeaterAccountBudgets.DataSource = accounts; this.RepeaterAccountBudgets.DataBind(); }
/// <summary> /// Sets the value. /// </summary> /// <param name="account">The account.</param> public void SetValue( FinancialAccount account ) { if ( account != null ) { ItemId = account.Id.ToString(); List<int> parentAccountIds = new List<int>(); var parentAccount = account.ParentAccount; while ( parentAccount != null ) { if ( parentAccountIds.Contains( parentAccount.Id ) ) { // infinite recursion break; } parentAccountIds.Insert( 0, parentAccount.Id ); parentAccount = parentAccount.ParentAccount; } InitialItemParentIds = parentAccountIds.AsDelimited( "," ); ItemName = account.PublicName; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
protected FinancialAccount SelectBudget(Geography geo) { //TODO: Greate a general funtion to select local budget based on geography int financialAccountId = 0; if (geo.Identity == 32 || geo.Inherits(32)) { financialAccountId = 18; } else if (geo.Identity == 33 || geo.Inherits(33)) { financialAccountId = 15; } else if (geo.Identity == 34 || geo.Inherits(34)) { financialAccountId = 17; } else if (geo.Identity == 35 || geo.Inherits(35)) { financialAccountId = 16; } else if (geo.Identity == 39 || geo.Inherits(39)) { financialAccountId = 19; } else { financialAccountId = 27; } return(FinancialAccount.FromIdentity(financialAccountId)); }
public static bool SetAccountSwitch(int accountId, string switchName, bool switchValue) { AuthenticationData authData = GetAuthenticationDataAndCulture(); FinancialAccount account = FinancialAccount.FromIdentity(accountId); if (!PrepareAccountChange(account, authData, false)) { return(false); } switch (switchName) { case "Active": account.Active = switchValue; break; case "Administrative": account.Administrative = switchValue; break; case "Expensable": account.Expensable = switchValue; break; default: throw new NotImplementedException("Unknown switchName parameter"); } return(true); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="accountId">The account identifier.</param> public void ShowDetail( int accountId ) { FinancialAccount account = null; bool editAllowed = UserCanEdit; if ( !accountId.Equals( 0 ) ) { account = new FinancialAccountService( new RockContext() ).Get( accountId ); editAllowed = editAllowed || account.IsAuthorized( Authorization.EDIT, CurrentPerson ); pdAuditDetails.SetEntity( account, ResolveRockUrl( "~" ) ); } if ( account == null ) { account = new FinancialAccount { Id = 0, IsActive = true }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } hfAccountId.Value = account.Id.ToString(); nbEditModeMessage.Text = string.Empty; if (editAllowed) { ShowEditDetails(account); } else { nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(FinancialAccount.FriendlyTypeName); ShowReadonlyDetails(account); } }
protected void Page_Load (object sender, EventArgs e) { // Get account int financialAccountId = Int32.Parse(Request.QueryString["FinancialAccountId"]); _account = FinancialAccount.FromIdentity(financialAccountId); int year = DateTime.Today.Year; if (_account.OwnerPersonId != _currentUser.Identity) { throw new UnauthorizedAccessException("Access Denied"); } this.ComboOwner.Authority = _authority; if (!Page.IsPostBack) { // Populate all data this.LabelAccount.Text = _account.Name; this.LabelOrganization.Text = _account.Organization.Name; if (_account.Owner != null) { this.ComboOwner.Text = _account.Owner.Name + " (#" + _account.Owner.Identity.ToString() + ")"; } } // Page.Title = "Editing Budget: " + _account.Name + ", " + year.ToString(); }
private static bool PrepareAccountChange(FinancialAccount account, AuthenticationData authData, bool checkOpenedYear) { // TODO: Check permissions, too (may be read-only) if (account.OrganizationId != authData.CurrentOrganization.Identity) { throw new UnauthorizedAccessException("A million nopes"); } try { int ledgersClosedUntilYear = authData.CurrentOrganization.Parameters.FiscalBooksClosedUntilYear; if (checkOpenedYear && ledgersClosedUntilYear > 0 && account.OpenedYear <= ledgersClosedUntilYear) { // This requires breaking the account, which we can't do yet (in this sprint, will come next sprint). return(false); } } catch (Exception) { // OpenedYear throws because there isn't a transaction. That's fine. } return(true); }
public void Populate(FinancialAccount root) { this.Tree.Nodes.Clear(); FinancialAccounts accounts = root.GetTree(); accounts.Remove(root); if (accounts.Count > 0) { Populate(accounts); } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="itemKey">The item key.</param> /// <param name="itemKeyValue">The item key value.</param> public void ShowDetail( string itemKey, int itemKeyValue ) { pnlDetails.Visible = false; if ( !itemKey.Equals( "accountId" ) ) { return; } bool editAllowed = true; FinancialAccount account = null; if ( !itemKeyValue.Equals( 0 ) ) { account = new FinancialAccountService( new RockContext() ).Get( itemKeyValue ); editAllowed = account.IsAuthorized( Authorization.EDIT, CurrentPerson ); } else { account = new FinancialAccount { Id = 0, IsActive = true }; } if ( account == null ) { return; } pnlDetails.Visible = true; hfAccountId.Value = account.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !IsUserAuthorized( Authorization.EDIT ) ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( FinancialAccount.FriendlyTypeName ); } if ( readOnly ) { ShowReadonlyDetails( account ); } else { ShowEditDetails( account ); } }
/// <summary> /// Adds the account. /// </summary> /// <param name="lookupContext">The lookup context.</param> /// <param name="fundName">Name of the fund.</param> /// <param name="fundCampusId">The fund campus identifier.</param> /// <returns></returns> private static FinancialAccount AddAccount( RockContext lookupContext, string fundName, int? fundCampusId, int? parentAccountId ) { lookupContext = lookupContext ?? new RockContext(); var account = new FinancialAccount(); account.Name = fundName; account.PublicName = fundName; account.IsTaxDeductible = true; account.IsActive = true; account.CampusId = fundCampusId; account.ParentAccountId = parentAccountId; account.CreatedByPersonAliasId = ImportPersonAlias.Id; lookupContext.FinancialAccounts.Add( account ); lookupContext.SaveChanges( DisableAudit ); return account; }
static internal int WriteFinancialAccount(FinancialAccount o) { DataOperation operation = DataOperation.Parse("writeFSMFinancialAccount", o.Id, o.FinancialProduct.Id, o.Institution.Id, o.Customer.Id, o.SellerId, o.SalesChannelId, o.AuthorizedById, o.ManagerId, o.ExecutiveId, o.CollectorId, o.ContractNumber, o.ContractDate, o.InstitutionCustomerNumber, o.AccountNumber, o.InterBankAccountNumber, o.Notes, o.Keywords, o.BaseCurrency.Id, o.RequestedLimit, o.AuthorizedLimit, o.BillingCycle, o.BillingMode, o.BillingWeekDays, o.BillingNotes, o.CollectCycle, o.CollectMode, o.CollectWeekDays, o.CollectNotes, o.DocumentationVector, o.Score, o.RequestedDate, o.OpeningDate, o.ClosingDate, o.PostedById, o.ReplacedById, o.Status, o.StartDate, o.EndDate); int i = DataWriter.Execute(operation); //GasFacilityData.ChangeCreditAccountStatus(o.CustomerId, o.Status); UpdateAccountsTable(o.Id); return i; }
/// <summary> /// Sets the value. /// </summary> /// <param name="account">The account.</param> public void SetValue( FinancialAccount account ) { if ( account != null ) { ItemId = account.Id.ToString(); var parentAccountIds = string.Empty; var parentAccount = account.ParentAccount; while ( parentAccount != null ) { parentAccountIds = parentAccount.Id + "," + parentAccountIds; parentAccount = parentAccount.ParentAccount; } InitialItemParentIds = parentAccountIds.TrimEnd( new[] { ',' } ); ItemName = account.PublicName; } else { ItemId = Constants.None.IdValue; ItemName = Constants.None.TextHtml; } }
/// <summary> /// Shows the detail. /// </summary> /// <param name="accountId">The account identifier.</param> public void ShowDetail( int accountId ) { FinancialAccount account = null; bool editAllowed = UserCanEdit; if ( !accountId.Equals( 0 ) ) { account = new FinancialAccountService( new RockContext() ).Get( accountId ); editAllowed = editAllowed || account.IsAuthorized( Authorization.EDIT, CurrentPerson ); } if ( account == null ) { account = new FinancialAccount { Id = 0, IsActive = true }; } hfAccountId.Value = account.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if ( !editAllowed || !editAllowed ) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( FinancialAccount.FriendlyTypeName ); } if ( readOnly ) { ShowReadonlyDetails( account ); } else { ShowEditDetails( account ); } }
private FinancialAccountRole CreateFinancialAccountRole(FinancialAccount financialAccount, PartyRole role) { FinancialAccountRole financialAccountRole = new FinancialAccountRole(); financialAccountRole.FinancialAccount = financialAccount; financialAccountRole.PartyRole = role; return financialAccountRole; }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="account">The account.</param> private void ShowEditDetails( FinancialAccount account ) { if ( account.Id == 0 ) { lActionTitle.Text = ActionTitle.Add( FinancialAccount.FriendlyTypeName ).FormatAsHtmlTitle(); } else { lActionTitle.Text = account.Name.FormatAsHtmlTitle(); } hlInactive.Visible = !account.IsActive; SetEditMode( true ); LoadDropDowns(); tbName.Text = account.Name; cbIsActive.Checked = account.IsActive; tbDescription.Text = account.Description; apParentAccount.SetValue( account.ParentAccount ); ddlAccountType.SetValue( account.AccountTypeValueId ); tbPublicName.Text = account.PublicName; cpCampus.SelectedCampusId = account.CampusId; tbGLCode.Text = account.GlCode; cbIsTaxDeductible.Checked = account.IsTaxDeductible; dtpStartDate.SelectedDate = account.StartDate; dtpEndDate.SelectedDate = account.EndDate; }
/// <summary> /// Shows the readonly details. /// </summary> /// <param name="account">The account.</param> private void ShowReadonlyDetails( FinancialAccount account ) { SetEditMode( false ); hfAccountId.SetValue( account.Id ); lActionTitle.Text = account.Name.FormatAsHtmlTitle(); hlInactive.Visible = !account.IsActive; lAccountDescription.Text = account.Description; DescriptionList descriptionList = new DescriptionList(); descriptionList.Add( string.Empty, string.Empty ); lblMainDetails.Text = descriptionList.Html; }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="account">The account.</param> private void ShowEditDetails( FinancialAccount account ) { if ( account.Id == 0 ) { lActionTitle.Text = ActionTitle.Add( FinancialAccount.FriendlyTypeName ).FormatAsHtmlTitle(); // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } else { lActionTitle.Text = account.Name.FormatAsHtmlTitle(); } hlInactive.Visible = !account.IsActive; SetEditMode( true ); LoadDropDowns(); tbName.Text = account.Name; cbIsActive.Checked = account.IsActive; cbIsPublic.Checked = account.IsPublic.HasValue ? account.IsPublic.Value : false; tbDescription.Text = account.Description; cePublicDescription.Text = account.PublicDescription; apParentAccount.SetValue( account.ParentAccount ); ddlAccountType.SetValue( account.AccountTypeValueId ); tbPublicName.Text = account.PublicName; tbUrl.Text = account.Url; cpCampus.SelectedCampusId = account.CampusId; tbGLCode.Text = account.GlCode; cbIsTaxDeductible.Checked = account.IsTaxDeductible; dtpStartDate.SelectedDate = account.StartDate; dtpEndDate.SelectedDate = account.EndDate; }
/// <summary> /// Maps the pledge. /// </summary> /// <param name="queryable">The queryable.</param> /// <exception cref="System.NotImplementedException"></exception> private void MapPledge( IQueryable<Row> tableData ) { var accountService = new FinancialAccountService(); List<FinancialAccount> importedAccounts = accountService.Queryable().ToList(); List<DefinedValue> pledgeFrequencies = new DefinedValueService().GetByDefinedTypeGuid( new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_FREQUENCY ) ).ToList(); List<FinancialPledge> importedPledges = new FinancialPledgeService().Queryable().ToList(); var newPledges = new List<FinancialPledge>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Checking pledge import ({0:N0} found).", totalRows ) ); foreach ( var row in tableData ) { decimal? amount = row["Total_Pledge"] as decimal?; DateTime? startDate = row["Start_Date"] as DateTime?; DateTime? endDate = row["End_Date"] as DateTime?; if ( amount != null && startDate != null && endDate != null ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; int? personId = GetPersonId( individualId, householdId ); if ( personId != null && !importedPledges.Any( p => p.PersonId == personId && p.TotalAmount == amount && p.StartDate.Equals( startDate ) ) ) { var pledge = new FinancialPledge(); pledge.CreatedByPersonAliasId = ImportPersonAlias.Id; pledge.StartDate = (DateTime)startDate; pledge.EndDate = (DateTime)endDate; pledge.TotalAmount = (decimal)amount; string frequency = row["Pledge_Frequency_Name"] as string; if ( frequency != null ) { if ( frequency == "One Time" || frequency == "As Can" ) { pledge.PledgeFrequencyValueId = pledgeFrequencies.FirstOrDefault( f => f.Guid == new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_ONE_TIME ) ).Id; } else { pledge.PledgeFrequencyValueId = pledgeFrequencies .Where( f => f.Name.StartsWith( frequency ) || f.Description.StartsWith( frequency ) ) .Select( f => f.Id ).FirstOrDefault(); } } string fundName = row["Fund_Name"] as string; string subFund = row["Sub_Fund_Name"] as string; if ( fundName != null ) { FinancialAccount matchingAccount = null; int? fundCampusId = null; if ( subFund != null ) { // match by campus if the subfund appears to be a campus fundCampusId = CampusList.Where( c => c.Name.StartsWith( subFund ) || c.ShortCode == subFund ) .Select( c => (int?)c.Id ).FirstOrDefault(); if ( fundCampusId != null ) { matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId != null && a.CampusId.Equals( fundCampusId ) ); } else { matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.Name.StartsWith( subFund ) ); } } else { matchingAccount = importedAccounts.FirstOrDefault( a => a.Name.StartsWith( fundName ) ); } if ( matchingAccount == null ) { matchingAccount = new FinancialAccount(); matchingAccount.Name = fundName; matchingAccount.PublicName = fundName; matchingAccount.IsTaxDeductible = true; matchingAccount.IsActive = true; matchingAccount.CampusId = fundCampusId; matchingAccount.CreatedByPersonAliasId = ImportPersonAlias.Id; accountService.Add( matchingAccount ); accountService.Save( matchingAccount ); importedAccounts.Add( matchingAccount ); pledge.AccountId = matchingAccount.Id; } } // Attributes to add? // Pledge_Drive_Name newPledges.Add( pledge ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} pledges imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { RockTransactionScope.WrapTransaction( () => { var pledgeService = new FinancialPledgeService(); pledgeService.RockContext.FinancialPledges.AddRange( newPledges ); pledgeService.RockContext.SaveChanges(); } ); ReportPartialProgress(); } } } } if ( newPledges.Any() ) { RockTransactionScope.WrapTransaction( () => { var pledgeService = new FinancialPledgeService(); pledgeService.RockContext.FinancialPledges.AddRange( newPledges ); pledgeService.RockContext.SaveChanges(); } ); } ReportProgress( 100, string.Format( "Finished pledge import: {0:N0} pledges imported.", completed ) ); }
private FinancialAccount CreateFinancialAccount(Agreement agreement, DateTime today) { FinancialAccount financialAccountNew1 = new FinancialAccount(); financialAccountNew1.Agreement = agreement; financialAccountNew1.FinancialAccountType = FinancialAccountType.LoanAccountType; return financialAccountNew1; }
private void ChequeModelPrepareForSave(FinancialAccount financialAccount, PartyRole customerPartyRole, int employeePartyRoleId, DateTime today, ChequeModel model) { if (model.IsNew) { var application = financialAccount.Agreement.Application; var loanAccount = financialAccount.LoanAccount; //new payment Payment payment = CreatePayment(customerPartyRole, employeePartyRoleId, model, today); //new cheque Cheque newCheck = new Cheque(); newCheck.BankPartyRoleId = model.BankId; newCheck.CheckDate = model.ChequeDate; newCheck.Payment = payment; //new cheque association ChequeApplicationAssoc chequeAssoc = new ChequeApplicationAssoc(); chequeAssoc.Cheque = newCheck; chequeAssoc.Application = application; //new cheque loan association ChequeLoanAssoc chequeLoanAssoc = new ChequeLoanAssoc(); chequeLoanAssoc.Cheque = newCheck; chequeLoanAssoc.LoanAccount = loanAccount; //new receipt Receipt newReceipt = CreateReceipt(customerPartyRole, payment, model); //new receipt payment assoc ReceiptPaymentAssoc newReceiptAssoc = CreateReceiptPaymentAssoc(payment, newReceipt); //new receipt status CreateReceiptStatus(newReceipt, model, today); //new cheque status CreateChequeStatus(newCheck, model, today); Context.Cheques.AddObject(newCheck); } else if (model.ToBeDeleted) { //throw new NotImplementedException(); var payment = Context.Payments.SingleOrDefault(entity => entity.Id == model.PaymentId); var receiptPaymentAssoc = Context.ReceiptPaymentAssocs.SingleOrDefault(entity => entity.PaymentId == payment.Id); var receipts = receiptPaymentAssoc.Receipt; var cheque = Context.Cheques.SingleOrDefault(entity => entity.Id == model.ChequeId && entity.PaymentId == payment.Id); var assoc = Context.ChequeApplicationAssocs.SingleOrDefault(entity => entity.ChequeId == cheque.Id); Context.ReceiptPaymentAssocs.DeleteObject(receiptPaymentAssoc); Context.Receipts.DeleteObject(receipts); Context.ChequeApplicationAssocs.DeleteObject(assoc); Context.Cheques.DeleteObject(cheque); Context.Payments.DeleteObject(payment); } }
protected FinancialAccount CreateNewFinancialAccount() { FinancialAccount newFinancialAccount = new FinancialAccount(); return newFinancialAccount; }
public void Populate(FinancialAccount root) { Controls_v4_FinancialAccountTree tree = (Controls_v4_FinancialAccountTree)this.DropFinancialAccounts.Items[0].FindControl("FinancialAccountTree"); tree.Populate(root); }
private FinancialAccount CreateFinancialAccountWithParent(Agreement agreement, DateTime today, FinancialAccount financialAccountParent) { FinancialAccount financialAccountNew1 = new FinancialAccount(); financialAccountNew1.Agreement = agreement; financialAccountNew1.FinancialAccountType = FinancialAccountType.LoanAccountType; financialAccountNew1.ParentFinancialAccountId = financialAccountParent.Id; return financialAccountNew1; }
/// <summary> /// Maps the contribution. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="selectedColumns">The selected columns.</param> private void MapContribution( IQueryable<Row> tableData, List<string> selectedColumns = null ) { int transactionEntityTypeId = EntityTypeCache.Read( "Rock.Model.FinancialTransaction" ).Id; var accountService = new FinancialAccountService(); var attributeService = new AttributeService(); var transactionTypeContributionId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION ) ).Id; int currencyTypeACH = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_ACH ) ).Id; int currencyTypeCash = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CASH ) ).Id; int currencyTypeCheck = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK ) ).Id; int currencyTypeCreditCard = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CREDIT_CARD ) ).Id; List<DefinedValue> refundReasons = new DefinedValueService().Queryable().Where( dv => dv.DefinedType.Guid == new Guid( Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON ) ).ToList(); List<FinancialPledge> pledgeList = new FinancialPledgeService().Queryable().ToList(); List<FinancialAccount> accountList = accountService.Queryable().ToList(); // Add an Attribute for the unique F1 Contribution Id int contributionAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == transactionEntityTypeId && a.Key == "F1ContributionId" ).Select( a => a.Id ).FirstOrDefault(); if ( contributionAttributeId == 0 ) { var newContributionAttribute = new Rock.Model.Attribute(); newContributionAttribute.Key = "F1ContributionId"; newContributionAttribute.Name = "F1 Contribution Id"; newContributionAttribute.FieldTypeId = IntegerFieldTypeId; newContributionAttribute.EntityTypeId = transactionEntityTypeId; newContributionAttribute.EntityTypeQualifierValue = string.Empty; newContributionAttribute.EntityTypeQualifierColumn = string.Empty; newContributionAttribute.Description = "The FellowshipOne identifier for the contribution that was imported"; newContributionAttribute.DefaultValue = string.Empty; newContributionAttribute.IsMultiValue = false; newContributionAttribute.IsRequired = false; newContributionAttribute.Order = 0; attributeService.Add( newContributionAttribute, ImportPersonAlias ); attributeService.Save( newContributionAttribute, ImportPersonAlias ); contributionAttributeId = newContributionAttribute.Id; } var contributionAttribute = AttributeCache.Read( contributionAttributeId ); // Get all imported contributions var importedContributions = new AttributeValueService().GetByAttributeId( contributionAttributeId ) .Select( av => new { ContributionId = av.Value.AsType<int?>(), TransactionId = av.EntityId } ) .ToDictionary( t => t.ContributionId, t => t.TransactionId ); // List for batching new contributions var newTransactions = new List<FinancialTransaction>(); int completed = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Checking contribution import ({0:N0} found, {1:N0} already exist).", totalRows, importedContributions.Count() ) ); foreach ( var row in tableData ) { int? individualId = row["Individual_ID"] as int?; int? householdId = row["Household_ID"] as int?; int? contributionId = row["ContributionID"] as int?; if ( contributionId != null && !importedContributions.ContainsKey( contributionId ) ) { var transaction = new FinancialTransaction(); transaction.TransactionTypeValueId = transactionTypeContributionId; transaction.AuthorizedPersonId = GetPersonId( individualId, householdId ); transaction.CreatedByPersonAliasId = ImportPersonAlias.Id; transaction.AuthorizedPersonId = GetPersonId( individualId, householdId ); string summary = row["Memo"] as string; if ( summary != null ) { transaction.Summary = summary; } int? batchId = row["BatchID"] as int?; if ( batchId != null && ImportedBatches.Any( b => b.Key == batchId ) ) { transaction.BatchId = ImportedBatches.FirstOrDefault( b => b.Key == batchId ).Value; } DateTime? receivedDate = row["Received_Date"] as DateTime?; if ( receivedDate != null ) { transaction.TransactionDateTime = receivedDate; transaction.CreatedDateTime = receivedDate; } bool isTypeNonCash = false; string contributionType = row["Contribution_Type_Name"] as string; if ( contributionType != null ) { if ( contributionType == "ACH" ) { transaction.CurrencyTypeValueId = currencyTypeACH; } else if ( contributionType == "Cash" ) { transaction.CurrencyTypeValueId = currencyTypeCash; } else if ( contributionType == "Check" ) { transaction.CurrencyTypeValueId = currencyTypeCheck; } else if ( contributionType == "Credit Card" ) { transaction.CurrencyTypeValueId = currencyTypeCreditCard; } else { isTypeNonCash = true; } } string checkNumber = row["Check_Number"] as string; if ( checkNumber != null && checkNumber.AsType<int?>() != null ) { // routing & account set to zero transaction.CheckMicrEncrypted = Encryption.EncryptString( string.Format( "{0}_{1}_{2}", 0, 0, checkNumber ) ); } string fundName = row["Fund_Name"] as string; string subFund = row["Sub_Fund_Name"] as string; decimal? amount = row["Amount"] as decimal?; if ( fundName != null & amount != null ) { FinancialAccount matchingAccount = null; fundName = fundName.Trim(); int? fundCampusId = null; if ( subFund != null ) { subFund = subFund.Trim(); fundCampusId = CampusList.Where( c => c.Name.StartsWith( subFund ) || c.ShortCode == subFund ) .Select( c => (int?)c.Id ).FirstOrDefault(); if ( fundCampusId != null ) { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId != null && a.CampusId.Equals( fundCampusId ) ); } else { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.Name.StartsWith( subFund ) ); } } else { matchingAccount = accountList.FirstOrDefault( a => a.Name.StartsWith( fundName ) && a.CampusId == null ); } if ( matchingAccount == null ) { matchingAccount = new FinancialAccount(); matchingAccount.Name = fundName; matchingAccount.PublicName = fundName; matchingAccount.IsTaxDeductible = true; matchingAccount.IsActive = true; matchingAccount.CampusId = fundCampusId; matchingAccount.CreatedByPersonAliasId = ImportPersonAlias.Id; accountService.Add( matchingAccount ); accountService.Save( matchingAccount ); accountList.Add( matchingAccount ); } var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = (decimal)amount; transactionDetail.CreatedDateTime = receivedDate; transactionDetail.AccountId = matchingAccount.Id; transactionDetail.IsNonCash = isTypeNonCash; transaction.TransactionDetails.Add( transactionDetail ); if ( amount < 0 ) { var transactionRefund = new FinancialTransactionRefund(); transactionRefund.CreatedDateTime = receivedDate; transactionRefund.RefundReasonSummary = summary; transactionRefund.RefundReasonValueId = refundReasons.Where( dv => summary != null && dv.Name.Contains( summary ) ) .Select( dv => (int?)dv.Id ).FirstOrDefault(); transaction.Refund = transactionRefund; } } // Other Attributes to create: // Pledge_Drive_Name // Stated_Value // True_Value // Liquidation_cost transaction.Attributes = new Dictionary<string, AttributeCache>(); transaction.AttributeValues = new Dictionary<string, List<AttributeValue>>(); transaction.Attributes.Add( contributionAttribute.Key, contributionAttribute ); transaction.AttributeValues.Add( contributionAttribute.Key, new List<AttributeValue>() ); transaction.AttributeValues[contributionAttribute.Key].Add( new AttributeValue() { AttributeId = contributionAttribute.Id, Value = contributionId.ToString(), Order = 0 } ); newTransactions.Add( transaction ); completed++; if ( completed % percentage < 1 ) { int percentComplete = completed / percentage; ReportProgress( percentComplete, string.Format( "{0:N0} contributions imported ({1}% complete).", completed, percentComplete ) ); } else if ( completed % ReportingNumber < 1 ) { RockTransactionScope.WrapTransaction( () => { var transactionService = new FinancialTransactionService(); transactionService.RockContext.FinancialTransactions.AddRange( newTransactions ); transactionService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) ) { var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault(); if ( attributeValue != null ) { attributeValue.EntityId = contribution.Id; attributeValueService.RockContext.AttributeValues.Add( attributeValue ); } } attributeValueService.RockContext.SaveChanges(); } ); newTransactions.Clear(); ReportPartialProgress(); } } } if ( newTransactions.Any() ) { RockTransactionScope.WrapTransaction( () => { var transactionService = new FinancialTransactionService(); transactionService.RockContext.FinancialTransactions.AddRange( newTransactions ); transactionService.RockContext.SaveChanges(); var attributeValueService = new AttributeValueService(); foreach ( var contribution in newTransactions.Where( c => c.Attributes.Any() ) ) { var attributeValue = contribution.AttributeValues[contributionAttribute.Key].FirstOrDefault(); if ( attributeValue != null ) { attributeValue.EntityId = contribution.Id; attributeValueService.RockContext.AttributeValues.Add( attributeValue ); } } attributeValueService.RockContext.SaveChanges(); } ); } ReportProgress( 100, string.Format( "Finished contribution import: {0:N0} contributions imported.", completed ) ); }
private LoanAccount CreateLoanAccount(FinancialAccount financialAccount, AmortizationItemsModel item, DateTime maturityDate, DateTime today) { LoanAccount loanAccountNew = new LoanAccount(); loanAccountNew.FinancialAccount = financialAccount; loanAccountNew.LoanAmount = item.NewLoanAmount; loanAccountNew.LoanBalance = item.NewLoanAmount; //loanAccountNew.LoanReleaseDate = today.Date; loanAccountNew.LoanReleaseDate = item.LoanReleaseDate; loanAccountNew.InterestType = InterestType.PercentageInterestTYpe; if(item.Term != 0) loanAccountNew.MaturityDate = maturityDate; return loanAccountNew; }
public AgingAccountsModel(FinancialAccount financialAccount, DateTime selectedDate) { var owner = ObjectContext.FinancialAccountRoles.FirstOrDefault(entity => entity.FinancialAccountId == financialAccount.Id && entity.PartyRole.RoleTypeId == RoleType.OwnerFinancialType.Id && entity.PartyRole.EndDate == null); //var person = owner.PartyRole.Party.Person; var party = owner.PartyRole.Party; this.AccountName = party.Name; this.SelectedDate = selectedDate; var loanAccount = financialAccount.LoanAccount; var payments = loanAccount.FinancialAccount.FinAcctTrans.Where(entity => entity.FinancialAcctTransTypeId == FinlAcctTransType.AccountPaymentType.Id).OrderByDescending(entity => entity.TransactionDate).FirstOrDefault(); if (payments != null) { this.DueDate1 = payments.TransactionDate; this.LastPaymentDate1 = this.DueDate1; this.DueDate = this.DueDate1.Value.ToString("MMMM dd, yyyy"); this.LastPaymentDate = this.DueDate; } else { this.LastPaymentDate = "None"; this.DueDate1 = loanAccount.LoanReleaseDate; this.DueDate = this.DueDate1.Value.ToString("MMMM dd, yyyy"); this.LoanReleaseDate = this.DueDate; this.LoanReleaseDate1 = this.DueDate1; } this.Balance = loanAccount.LoanBalance; var dateDiff = 0; if (this.SelectedDate.Date.CompareTo(this.DueDate1.Value.Date) <= 0) { this.Current = this.Balance; } else { dateDiff = this.SelectedDate.Date.Subtract(this.DueDate1.Value.Date).Days; if (dateDiff >= 1 && dateDiff <= 30) { this.OneToThirty = this.Balance; } else if (dateDiff >= 31 && dateDiff <= 60) { this.ThirtyOneToSixty = this.Balance; } else if (dateDiff >= 61 && dateDiff <= 90) { this.SixtyOneToNinety = this.Balance; } else if (dateDiff > 90) { this.OverNinety = this.Balance; } } }
private LoanModificationPrevItem CreateLoanModificationPrevItem(LoanModification loanModification, FinancialAccount financialAccount) { LoanModificationPrevItem loanModificationPrevItem = new LoanModificationPrevItem(); loanModificationPrevItem.FinancialAccount = financialAccount; loanModificationPrevItem.LoanModification = loanModification; return loanModificationPrevItem; }
private Agreement CreateNewAgreementWithParent(Application application, DateTime today, FinancialAccount financialAccount) { Agreement agreement = new Agreement(); agreement.Application = application; agreement.AgreementType = AgreementType.LoanAgreementType; agreement.EffectiveDate = today; agreement.AgreementDate = today; agreement.ParentAgreementId = financialAccount.AgreementId; return agreement; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); var accountId = PageParameter("accountId").AsInteger(); if ( !Page.IsPostBack ) { ShowDetail( accountId ); } // Add any attribute controls. // This must be done here regardless of whether it is a postback so that the attribute values will get saved. var account = new FinancialAccountService(new RockContext()).Get(accountId); if (account == null) { account = new FinancialAccount(); } account.LoadAttributes(); phAttributes.Controls.Clear(); Helper.AddEditControls(account, phAttributes, true, BlockValidationGroup); }
private FinancialAccountProduct CreateFinancialAccountProduct(FinancialAccount financialAccount, FinancialProduct financialProduct, DateTime today) { FinancialAccountProduct financialAccountProductNew1 = new FinancialAccountProduct(); financialAccountProductNew1.FinancialAccount = financialAccount; financialAccountProductNew1.FinancialProduct = financialProduct; financialAccountProductNew1.EffectiveDate = today; return financialAccountProductNew1; }
private void FixupFinancialAccount(FinancialAccount previousValue) { if (IsDeserializing) { return; } if (previousValue != null && previousValue.FundFlows.Contains(this)) { previousValue.FundFlows.Remove(this); } if (FinancialAccount != null) { if (!FinancialAccount.FundFlows.Contains(this)) { FinancialAccount.FundFlows.Add(this); } FinancialAccountId = FinancialAccount.Id; } if (ChangeTracker.ChangeTrackingEnabled) { if (ChangeTracker.OriginalValues.ContainsKey("FinancialAccount") && (ChangeTracker.OriginalValues["FinancialAccount"] == FinancialAccount)) { ChangeTracker.OriginalValues.Remove("FinancialAccount"); } else { ChangeTracker.RecordOriginalValue("FinancialAccount", previousValue); } if (FinancialAccount != null && !FinancialAccount.ChangeTracker.ChangeTrackingEnabled) { FinancialAccount.StartTracking(); } } }