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);
    }
Esempio n. 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this._authenticationData = GetAuthenticationDataAndCulture();
            this._year = DateTime.Today.Year;

            if (
                !this._authenticationData.CurrentUser.HasAccess(new Access(
                                                                    this._authenticationData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Read)))
            {
                throw new UnauthorizedAccessException();
            }

            // TODO: Get and cache account tree and account balances

            Response.ContentType = "application/json";

            string response = string.Empty;

            PopulateLookups(FinancialAccounts.ForOrganization(this._authenticationData.CurrentOrganization));
            this._hashedAccounts  = FinancialAccounts.GetHashedAccounts(this._authenticationData.CurrentOrganization);
            this._resultAccountId = this._authenticationData.CurrentOrganization.FinancialAccounts.CostsYearlyResult.Identity;

            response += GetAccountGroup(FinancialAccountType.Asset, Resources.Global.Financial_Asset) + ",";
            response += GetAccountGroup(FinancialAccountType.Debt, Resources.Global.Financial_Debt) + ",";
            response +=
                GetAccountGroup(FinancialAccountType.Income, Resources.Global.Financial_Income) + ",";
            response += GetAccountGroup(FinancialAccountType.Cost, Resources.Global.Financial_Cost);

            Response.Output.WriteLine("[" + response + "]");
            Response.End();
        }
Esempio n. 3
0
    protected void PopulateGrid()
    {
        FinancialAccounts      allAccounts     = FinancialAccounts.ForOrganization(Organization.PPSE);
        Dictionary <int, bool> accountIsParent = new Dictionary <int, bool>();

        FinancialAccounts resultAccounts = new FinancialAccounts();

        foreach (FinancialAccount account in allAccounts)
        {
            if (account.AccountType == FinancialAccountType.Income ||
                account.AccountType == FinancialAccountType.Cost)
            {
                resultAccounts.Add(account);

                if (account.ParentIdentity != 0)
                {
                }
            }
        }

        // Add expansion headers


        this.GridBudgetAccounts.DataSource = resultAccounts;

        PopulateLookups(resultAccounts);
    }
Esempio n. 4
0
    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);
    }
        static private Dictionary <int, bool> GetAttestationRights()
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            // Right now, this function is quite primitive. At some point in the future, it needs to take into
            // account that a budget may have several attesters. Right now, it just loops over all accounts and
            // checks the owner.

            Dictionary <int, bool> result   = new Dictionary <int, bool>();
            FinancialAccounts      accounts = FinancialAccounts.ForOrganization(authData.CurrentOrganization);

            foreach (FinancialAccount account in accounts)
            {
                if (account.OwnerPersonId == authData.CurrentUser.Identity ||
                    (account.OwnerPersonId == 0 && authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Administration))))
                {
                    if (account.AccountType == FinancialAccountType.Cost)
                    {
                        result[account.Identity] = true;
                    }
                }
            }

            return(result);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _authenticationData = GetAuthenticationDataAndCulture();
            _year = DateTime.Today.Year;

            if (!_authenticationData.CurrentUser.HasAccess(new Access(_authenticationData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Read)))
            {
                throw new UnauthorizedAccessException();
            }

            // TODO: Get and cache account tree and account balances

            Response.ContentType = "application/json";

            string response = string.Empty;

            PopulateLookups(FinancialAccounts.ForOrganization(_authenticationData.CurrentOrganization));
            _hashedAccounts = FinancialAccounts.GetHashedAccounts(_authenticationData.CurrentOrganization);

            response += GetAccountGroup(FinancialAccountType.Asset, Resources.Pages.Ledgers.BalanceSheet_Assets) + ",";
            response += GetAccountGroup(FinancialAccountType.Debt, Resources.Pages.Ledgers.BalanceSheet_Debt) + ",";
            response += GetAccountGroup(FinancialAccountType.Income, Resources.Pages.Ledgers.ProfitLossStatement_Income) + ",";
            response += GetAccountGroup(FinancialAccountType.Cost, Resources.Pages.Ledgers.ProfitLossStatement_Costs);

            Response.Output.WriteLine("[" + response + "]");
            Response.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.CurrentOrganization.IsEconomyEnabled)
            {
                Response.Redirect("/Pages/v5/Financial/EconomyNotEnabled.aspx", true);
                return;
            }

            this.PageIcon       = "iconshock-treasure";
            this.PageTitle      = Resources.Pages.Ledgers.ResyncExternalAccount_PageTitle;
            this.InfoBoxLiteral = Resources.Pages.Ledgers.ResyncExternalAccount_Info;

            if (!Page.IsPostBack)
            {
                this.DropAccounts.Items.Add(new ListItem(Resources.Global.Global_SelectOne, "0"));

                FinancialAccounts accounts = FinancialAccounts.ForOrganization(this.CurrentOrganization,
                                                                               FinancialAccountType.Asset);

                foreach (FinancialAccount account in accounts)
                {
                    // TODO: COnstruct import settings for accounts

                    if (this.CurrentOrganization.Name == "Piratpartiet SE" && account.Identity == 1)
                    {
                        this.DropAccounts.Items.Add(new ListItem(account.Name + " (SE/SEB)", account.Identity.ToString(CultureInfo.InvariantCulture)));
                    }
                }


                Localize();
            }
        }
    private Dictionary <int, Int64> GetAttestationRights()
    {
        // Right now, this function is quite primitive. At some point in the future, it needs to take into
        // account that a budget may have several attesters. Right now, it just loops over all accounts and
        // checks the owner.

        Dictionary <int, Int64> result   = new Dictionary <int, Int64>();
        FinancialAccounts       accounts = FinancialAccounts.ForOrganization(CurrentOrganization);

        foreach (FinancialAccount account in accounts)
        {
            if (account.OwnerPersonId == CurrentUser.Identity)
            {
                if (account.AccountType == FinancialAccountType.Cost)
                {
                    result[account.Identity] = account.GetBudgetCentsRemaining();
                }
                else
                {
                    result[account.Identity] = 1; // any value
                }
            }
        }

        return(result);
    }
Esempio n. 9
0
        public static string GetInactiveAccountCount()
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            int inactiveAccountCount = FinancialAccounts.ForOrganization(authData.CurrentOrganization).Count(account => !account.Active);

            return(inactiveAccountCount.ToString("N0"));
        }
Esempio n. 10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CurrentOrganization.IsEconomyEnabled)
            {
                Response.Redirect("/Pages/v5/Financial/EconomyNotEnabled.aspx", true);
                return;
            }

            if (!Page.IsPostBack)
            {
                // Localize

                PageIcon           = "iconshock-openbook";
                this.BoxTitle.Text = PageTitle = Resources.Pages.Ledgers.AccountPlan_PageTitle;
                InfoBoxLiteral     = Resources.Pages.Ledgers.AccountPlan_Info;
                this.LiteralExpensesBudgetsAreNegative.Text =
                    Resources.Pages.Ledgers.AccountPlan_ExpensesBudgetsAreNegative;
                this.LiteralDebtBalancesAreNegative.Text =
                    Resources.Pages.Ledgers.AccountPlan_DebtBalancesAreNegative;
                this.LiteralHeaderAccountName.Text          = Resources.Pages.Ledgers.AccountPlan_Header_AccountName;
                this.LiteralHeaderBalance.Text              = Resources.Pages.Ledgers.AccountPlan_Header_Balance;
                this.LiteralHeaderBudget.Text               = Resources.Pages.Ledgers.AccountPlan_Header_Budget;
                this.LiteralHeaderEdit.Text                 = Resources.Pages.Ledgers.AccountPlan_Header_Edit;
                this.LiteralHeaderEditingAccount.Text       = Resources.Pages.Ledgers.AccountPlan_Edit_Header;
                this.LiteralHeaderFlags.Text                = Resources.Pages.Ledgers.AccountPlan_Header_Flags;
                this.LiteralHeaderOwner.Text                = Global.Global_Owner;
                this.LiteralLabelAccountName.Text           = Resources.Pages.Ledgers.AccountPlan_Edit_AccountName;
                this.LiteralLabelActiveLong.Text            = Resources.Pages.Ledgers.AccountPlan_Edit_ActiveLong;
                this.LiteralLabelActiveShort.Text           = Resources.Pages.Ledgers.AccountPlan_Edit_ActiveShort;
                this.LiteralLabelAdministrativeLong.Text    = Resources.Pages.Ledgers.AccountPlan_Edit_AdministrativeLong;
                this.LiteralLabelAdministrativeShort.Text   = Resources.Pages.Ledgers.AccountPlan_Edit_AdministrativeShort;
                this.LiteralLabelBudgetBalance.Text         = Resources.Pages.Ledgers.AccountPlan_Edit_BudgetBalance;
                this.LiteralLabelExpensableLong.Text        = Resources.Pages.Ledgers.AccountPlan_Edit_ExpensableLong;
                this.LiteralLabelExpensableShort.Text       = Resources.Pages.Ledgers.AccountPlan_Edit_ExpensableShort;
                this.LiteralLabelFileUploadProfile.Text     = Resources.Pages.Ledgers.AccountPlan_Edit_FileUploadProfile;
                this.LiteralLabelHeaderAutomation.Text      = Resources.Pages.Ledgers.AccountPlan_Edit_HeaderAutomation;
                this.LiteralLabelHeaderConfiguration.Text   = Resources.Pages.Ledgers.AccountPlan_Edit_HeaderConfiguration;
                this.LiteralLabelHeaderDailyOperations.Text =
                    Resources.Pages.Ledgers.AccountPlan_Edit_HeaderDailyOperations;
                this.LiteralLabelOwner.Text  = Global.Global_Owner;
                this.LiteralLabelParent.Text = Resources.Pages.Ledgers.AccountPlan_Edit_Parent;

                this.LiteralLabelInitialAmount.Text =
                    String.Format(Resources.Pages.Ledgers.AccountPlan_Edit_InitialBalance,
                                  CurrentOrganization.FirstFiscalYear, CurrentOrganization.Currency.DisplayCode);

                FinancialAccounts organizationAccounts = FinancialAccounts.ForOrganization(this.CurrentOrganization);
                int inactiveCount = organizationAccounts.Count(account => !account.Active);

                this.LabelSidebarOptions.Text      = Resources.Global.Sidebar_Options;
                this.LabelOptionsShowInactive.Text = String.Format(Resources.Pages.Ledgers.AccountPlan_Options_ShowInactive, inactiveCount);
            }
            PageAccessRequired = new Access(CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write);
            DbVersionRequired  = 2; // Account reparenting

            RegisterControl(EasyUIControl.DataGrid | EasyUIControl.Tree);
            RegisterControl(IncludedControl.SwitchButton);
        }
Esempio n. 11
0
    private void PopulateAccounts(int organizationId)
    {
        FinancialAccounts accounts = FinancialAccounts.ForOrganization(Organization.FromIdentity(organizationId));

        this.DropAccounts.Items.Add(new ListItem("-- None --", "0"));
        foreach (FinancialAccount account in accounts)
        {
            this.DropAccounts.Items.Add(new ListItem("[" + account.AccountType.ToString().Substring(0, 1) + "] " + account.Name, account.Identity.ToString()));
        }
    }
Esempio n. 12
0
    private void PopulateAccounts(int organizationId)
    {
        FinancialAccounts accounts = FinancialAccounts.ForOrganization(Organization.FromIdentity(organizationId));

        this.DropAccounts.Items.Add(new ListItem("-- Select account --", "0"));
        foreach (FinancialAccount account in accounts)
        {
            this.DropAccounts.Items.Add(new ListItem(account.Name, account.Identity.ToString()));
        }
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";
            FinancialAccountType accountType =
                (FinancialAccountType)(Enum.Parse(typeof(FinancialAccountType), Request.QueryString["AccountType"]));

            string accountsJson = string.Empty;

            int excludeId = -1;

            string excludeIdString = Request.QueryString["ExcludeId"];

            if (!String.IsNullOrEmpty(excludeIdString))
            {
                excludeId = Int32.Parse(excludeIdString);
            }

            // Get accounts

            FinancialAccounts accounts = FinancialAccounts.ForOrganization(this.CurrentOrganization, accountType);

            // Build tree (there should be a template for this)

            Dictionary <int, List <FinancialAccount> > treeMap = new Dictionary <int, List <FinancialAccount> >();

            foreach (FinancialAccount account in accounts)
            {
                if (account.Identity == excludeId)
                {
                    continue;
                }

                if (!treeMap.ContainsKey(account.ParentIdentity))
                {
                    treeMap[account.ParentIdentity] = new List <FinancialAccount>();
                }

                treeMap[account.ParentIdentity].Add(account);
            }

            if (treeMap.ContainsKey(0))
            {
                accountsJson = RecurseTreeMap(treeMap, 0);
            }

            accountsJson = "[{\"id\":\"0\",\"text\":\"" +
                           JsonSanitize(Resources.Global.ResourceManager.GetString("Financial_" + accountType.ToString())) +
                           "\",\"state\":\"open\",\"children\":" +
                           accountsJson +
                           "}]";

            Response.Output.WriteLine(accountsJson);

            Response.End();
        }
Esempio n. 14
0
    protected void PopulateGrid()
    {
        FinancialAccounts allAccounts = FinancialAccounts.ForOrganization(Organization.PPSE);

        FinancialAccounts volatileAccounts = new FinancialAccounts();

        foreach (FinancialAccount account in allAccounts)
        {
            if (account.AccountType == FinancialAccountType.Cost ||
                account.AccountType == FinancialAccountType.Income)
            {
                volatileAccounts.Add(account);
            }
        }

        this.GridBudgetAccounts.DataSource = volatileAccounts;

        PopulateLookups(volatileAccounts);
    }
Esempio n. 15
0
        private Dictionary <int, bool> GetAttestationRights()
        {
            // Right now, this function is quite primitive. At some point in the future, it needs to take into
            // account that a budget may have several attesters. Right now, it just loops over all accounts and
            // checks the owner.

            Dictionary <int, bool> result   = new Dictionary <int, bool>();
            FinancialAccounts      accounts = FinancialAccounts.ForOrganization(CurrentOrganization);

            foreach (FinancialAccount account in accounts)
            {
                if (account.OwnerPersonId == CurrentUser.Identity)
                {
                    result[account.Identity] = true;
                }
            }

            return(result);
        }
Esempio n. 16
0
    protected void PopulateGrid()
    {
        FinancialAccounts allAccounts = FinancialAccounts.ForOrganization(Organization.PPSE);

        FinancialAccounts balanceAccounts = new FinancialAccounts();

        foreach (FinancialAccount account in allAccounts)
        {
            if (account.AccountType == FinancialAccountType.Asset ||
                account.AccountType == FinancialAccountType.Debt)
            {
                balanceAccounts.Add(account);
            }
        }

        // Add main headers

        this.GridBudgetAccounts.DataSource = balanceAccounts;

        PopulateLookups(balanceAccounts);
    }
Esempio n. 17
0
    protected void PopulateAccounts()
    {
        this.DropAccounts.Items.Clear();
        this.DropAccountsCreate.Items.Clear();

        this.DropAccounts.Items.Add(new ListItem("-- Select account --", "0"));
        this.DropAccountsCreate.Items.Add(new ListItem("-- Select account --", "0"));

        if (_organizationId == 0)
        {
            return; // no valid org
        }

        FinancialAccounts accounts = FinancialAccounts.ForOrganization(Organization.FromIdentity(_organizationId));

        foreach (FinancialAccount account in accounts)
        {
            this.DropAccounts.Items.Add(new ListItem("[" + account.AccountType.ToString().Substring(0, 1) + "] " + account.Name, account.Identity.ToString()));
            this.DropAccountsCreate.Items.Add(new ListItem("[" + account.AccountType.ToString().Substring(0, 1) + "] " + account.Name, account.Identity.ToString()));
        }
    }
    private void PopulateLedger()
    {
        FinancialAccounts accounts = new FinancialAccounts();

        if (this.RadioAllAccounts.Checked)
        {
            accounts =
                FinancialAccounts.ForOrganization(
                    Organization.FromIdentity(Int32.Parse(this.DropOrganizations.SelectedValue)));
        }
        else if (this.RadioAccountGroup.Checked)
        {
            accounts =
                FinancialAccounts.ForOrganization(
                    Organization.FromIdentity(Int32.Parse(this.DropOrganizations.SelectedValue)), (FinancialAccountType)Int32.Parse(this.DropAccountGroups.SelectedValue));
        }
        else if (this.RadioSpecificAccount.Checked)
        {
            accounts.Add(this.DropAccounts.SelectedFinancialAccount);
        }

        Ledger.Accounts = accounts;

        Ledger.DateStart = (DateTime)this.DateStart.SelectedDate;
        Ledger.DateEnd   = (DateTime)this.DateEnd.SelectedDate;

        Ledger.MaxAmount = 1.0e12m; // catches all transactions -- if not, PW is kind of outscaled

        if (this.RadioCreditingTransactions.Checked)
        {
            Ledger.MaxAmount = 0.0m;
        }
        else if (this.RadioCreditingTransactionsLarge.Checked)
        {
            Ledger.MaxAmount = -1000.0m;
        }

        Ledger.Populate();
    }
Esempio n. 19
0
    private void Populate(XmlElement root)
    {
        int year = DateTime.Now.Year;;

        FinancialAccounts allAccounts = FinancialAccounts.ForOrganization(Organization.PPSE);

        foreach (FinancialAccount account in allAccounts)
        {
            if (
                ((account.AccountType == FinancialAccountType.Cost ||
                  account.AccountType == FinancialAccountType.Income) &&
                 Request["type"] == null)
                ||
                (account.AccountType == FinancialAccountType.Cost && Request["type"] == "Cost")
                ||
                (account.AccountType == FinancialAccountType.Income) && Request["type"] == "Income")
            {
                string     budget   = Math.Round(account.GetBudget(year)).ToString();
                string     actual   = Math.Round(-account.GetDelta(new DateTime(year, 1, 1), new DateTime(year + 1, 1, 1))).ToString();
                XmlElement XAccount = xDoc.CreateElement("account");
                root.AppendChild(XAccount);
                XAccount.SetAttribute("id", account.FinancialAccountId.ToString());
                XAccount.SetAttribute("name", account.Name);
                XAccount.SetAttribute("parentid", account.ParentFinancialAccountId.ToString());
                XAccount.SetAttribute("ownerid", account.OwnerPersonId.ToString());
                if (localCall)
                {
                    if (account.Owner != null)
                    {
                        XAccount.SetAttribute("ownername", account.Owner.Name);
                        XAccount.SetAttribute("ownerphone", account.Owner.Phone);
                        XAccount.SetAttribute("ownermail", account.Owner.PartyEmail);
                    }
                    XAccount.SetAttribute("actual", actual);
                }
                XAccount.SetAttribute("budget", budget);
            }
        }
    }
Esempio n. 20
0
        public static int[] GetUninitializedBudgets()
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            // This function finds the exceptional accounts that aren't initialized, to let a sysadmin approve expenses to them.

            List <int>        result   = new List <int>();
            FinancialAccounts accounts = FinancialAccounts.ForOrganization(authData.CurrentOrganization);

            foreach (FinancialAccount account in accounts)
            {
                if (account.AccountType == FinancialAccountType.Cost)
                {
                    if (account.OwnerPersonId == 0 &&
                        authData.Authority.HasAccess(new Access(authData.CurrentOrganization,
                                                                AccessAspect.Administration)))
                    {
                        result.Add(account.Identity);
                    }
                }
            }

            return(result.ToArray());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";
            FinancialAccountType accountType =
                (FinancialAccountType)(Enum.Parse(typeof(FinancialAccountType), Request.QueryString["AccountType"]));

            string response = string.Empty;

            int excludeId = -1;

            string excludeIdString = Request.QueryString["ExcludeId"];

            if (!String.IsNullOrEmpty(excludeIdString))
            {
                excludeId = Int32.Parse(excludeIdString);
            }

            int resultsAccountId = CurrentOrganization.FinancialAccounts.CostsYearlyResult.Identity;

            // Get accounts

            FinancialAccounts accounts = FinancialAccounts.ForOrganization(CurrentOrganization, accountType);

            // Build tree (there should be a template for this)

            Dictionary <int, List <FinancialAccount> > treeMap = new Dictionary <int, List <FinancialAccount> >();

            foreach (FinancialAccount account in accounts)
            {
                if (account.Identity == excludeId || account.Identity == resultsAccountId)
                {
                    continue;
                }

                if (!treeMap.ContainsKey(account.ParentIdentity))
                {
                    treeMap[account.ParentIdentity] = new List <FinancialAccount>();
                }

                treeMap[account.ParentIdentity].Add(account);
            }

            this._hashedAccounts = treeMap;

            if (accountType == FinancialAccountType.Asset || accountType == FinancialAccountType.Balance ||
                accountType == FinancialAccountType.All)
            {
                response += GetAccountGroup(FinancialAccountType.Asset, Resources.Global.Financial_Asset) +
                            ",";
            }

            if (accountType == FinancialAccountType.Debt || accountType == FinancialAccountType.Balance ||
                accountType == FinancialAccountType.All)
            {
                response += GetAccountGroup(FinancialAccountType.Debt, Resources.Global.Financial_Debt) + ",";
            }

            if (accountType == FinancialAccountType.Income || accountType == FinancialAccountType.Result ||
                accountType == FinancialAccountType.All)
            {
                response +=
                    GetAccountGroup(FinancialAccountType.Income, Resources.Global.Financial_Income) +
                    ",";
            }

            if (accountType == FinancialAccountType.Cost || accountType == FinancialAccountType.Result ||
                accountType == FinancialAccountType.All)
            {
                response += GetAccountGroup(FinancialAccountType.Cost, Resources.Global.Financial_Cost);
            }

            response = response.TrimEnd(',');
            // removes last comma regardless of where it came from or if it's even there

            Response.Output.WriteLine("[" + response + "]");
            Response.End();
        }
Esempio n. 22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CurrentOrganization.IsEconomyEnabled)
            {
                Response.Redirect("/Pages/v5/Financial/EconomyNotEnabled.aspx", true);
                return;
            }

            if (!Page.IsPostBack)
            {
                // Localize

                PageIcon           = "iconshock-openbook";
                this.BoxTitle.Text = PageTitle = Resources.Pages.Ledgers.AccountPlan_PageTitle;
                InfoBoxLiteral     = Resources.Pages.Ledgers.AccountPlan_Info;
                this.LiteralExpensesBudgetsAreNegative.Text =
                    Resources.Pages.Ledgers.AccountPlan_ExpensesBudgetsAreNegative;
                this.LiteralDebtBalancesAreNegative.Text =
                    Resources.Pages.Ledgers.AccountPlan_DebtBalancesAreNegative;
                this.LiteralHeaderAccountName.Text          = Resources.Pages.Ledgers.AccountPlan_Header_AccountName;
                this.LiteralHeaderBalance.Text              = Resources.Pages.Ledgers.AccountPlan_Header_Balance;
                this.LiteralHeaderBudget.Text               = Resources.Pages.Ledgers.AccountPlan_Header_Budget;
                this.LiteralHeaderEdit.Text                 = Resources.Pages.Ledgers.AccountPlan_Header_Edit;
                this.LiteralHeaderEditingAccount.Text       = Resources.Pages.Ledgers.AccountPlan_Edit_Header;
                this.LiteralHeaderFlags.Text                = Resources.Pages.Ledgers.AccountPlan_Header_Flags;
                this.LiteralHeaderOwner.Text                = Global.Global_Owner;
                this.LiteralLabelAccountName.Text           = Resources.Pages.Ledgers.AccountPlan_Edit_AccountName;
                this.LiteralLabelActiveLong.Text            = Resources.Pages.Ledgers.AccountPlan_Edit_ActiveLong;
                this.LiteralLabelActiveShort.Text           = Resources.Pages.Ledgers.AccountPlan_Edit_ActiveShort;
                this.LiteralLabelAdministrativeLong.Text    = Resources.Pages.Ledgers.AccountPlan_Edit_AdministrativeLong;
                this.LiteralLabelAdministrativeShort.Text   = Resources.Pages.Ledgers.AccountPlan_Edit_AdministrativeShort;
                this.LiteralLabelBudgetBalance.Text         = Resources.Pages.Ledgers.AccountPlan_Edit_BudgetBalance;
                this.LiteralLabelExpensableLong.Text        = Resources.Pages.Ledgers.AccountPlan_Edit_ExpensableLong;
                this.LiteralLabelExpensableShort.Text       = Resources.Pages.Ledgers.AccountPlan_Edit_ExpensableShort;
                this.LabelFileUploadProfile.Text            = Resources.Pages.Ledgers.AccountPlan_Edit_FileUploadProfile;
                this.LabelHeaderAutomation.Text             = Resources.Pages.Ledgers.AccountPlan_Edit_HeaderAutomation;
                this.LiteralLabelHeaderConfiguration.Text   = Resources.Pages.Ledgers.AccountPlan_Edit_HeaderConfiguration;
                this.LiteralLabelHeaderDailyOperations.Text =
                    Resources.Pages.Ledgers.AccountPlan_Edit_HeaderDailyOperations;
                this.LiteralLabelOwner.Text  = Global.Global_Owner;
                this.LiteralLabelParent.Text = Resources.Pages.Ledgers.AccountPlan_Edit_Parent;

                this.LiteralLabelInitialAmount.Text =
                    String.Format(Resources.Pages.Ledgers.AccountPlan_Edit_InitialBalance,
                                  CurrentOrganization.FirstFiscalYear, CurrentOrganization.Currency.DisplayCode);

                FinancialAccounts organizationAccounts = FinancialAccounts.ForOrganization(this.CurrentOrganization);
                int inactiveCount = organizationAccounts.Count(account => !account.Active);

                this.LabelSidebarOptions.Text      = Resources.Global.Sidebar_Options;
                this.LabelOptionsShowInactive.Text = String.Format(Resources.Pages.Ledgers.AccountPlan_Options_ShowInactive, inactiveCount);

                this.DropAccountAutomationProfile.Items.Add(new ListItem(Resources.Global.Global_SelectOne, "0"));

                // Hardcoded automation profiles for the time being

                this.DropAccountAutomationProfile.Items.Add(new ListItem("[BTC] Bitcoin Core - Armory", ((int)(FinancialAccountAutomationProfileHardIds.BitcoinCoreArmory)).ToString()));
                this.DropAccountAutomationProfile.Items.Add(new ListItem("[BCH] Bitcoin Cash - Armory", ((int)(FinancialAccountAutomationProfileHardIds.BitcoinCoreArmory)).ToString()));
                this.DropAccountAutomationProfile.Items.Add(new ListItem("[CZ CZK] Fio CSV", ((int)(FinancialAccountAutomationProfileHardIds.BankCzechFio)).ToString()));
                this.DropAccountAutomationProfile.Items.Add(new ListItem("[DE EUR] Postbank CSV", ((int)(FinancialAccountAutomationProfileHardIds.BankGermanyPostbank)).ToString()));
                this.DropAccountAutomationProfile.Items.Add(new ListItem("[SE SEK] SEB CSV", ((int)(FinancialAccountAutomationProfileHardIds.BankSwedenSeb)).ToString()));
            }
            PageAccessRequired = new Access(CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write);
            DbVersionRequired  = 2; // Account reparenting

            RegisterControl(EasyUIControl.DataGrid | EasyUIControl.Tree);
            RegisterControl(IncludedControl.SwitchButton);
        }
    SeriesCollection GetFinancialData()
    {
        FinancialAccounts accounts = FinancialAccounts.ForOrganization(Organization.PPSE, FinancialAccountType.Balance);

        accounts.Remove(Organization.PPSE.FinancialAccounts.DebtsCapital);

        FinancialAccountRows rows = accounts.GetRows(new DateTime(2006, 1, 1), DateTime.Today.AddDays(1));



        SeriesCollection collection   = new SeriesCollection();
        DateTime         dateIterator = new DateTime(2009, 1, 1);

        DateTime endDate = DateTime.Now.Date;

        Series series = new Series();

        series.Name = "Each event";

        decimal maxValue       = 0;
        decimal minValue       = Decimal.MaxValue;
        int     rowIndex       = 0;
        decimal currentBalance = 0;

        while (rows[rowIndex].TransactionDateTime < dateIterator && rowIndex < rows.Count)
        {
            currentBalance += rows[rowIndex].Amount;

            rowIndex++;
        }

        Element newElement = new Element();

        newElement.XDateTime = dateIterator;
        newElement.YValue    = (double)currentBalance;

        while (dateIterator < endDate)
        {
            if (rowIndex >= rows.Count)
            {
                break;
            }

            DateTime nextDate = dateIterator.AddDays(1);
            while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate)
            {
                currentBalance += rows[rowIndex].Amount;

                rowIndex++;
            }

            if (currentBalance < minValue)
            {
                minValue = currentBalance;
            }

            if (currentBalance > maxValue)
            {
                maxValue = currentBalance;
            }

            newElement           = new Element();
            newElement.XDateTime = dateIterator;
            newElement.YValue    = (double)currentBalance;
            series.Elements.Add(newElement);
            dateIterator = nextDate;
        }

        /*
         * Chart.YAxis.Maximum = (maxValue + 90) / 10000 * 10000;
         * Chart.YAxis.Minimum = minValue / 100 * 100;*/

        series.Type                 = SeriesType.Line;
        series.Line.Width           = 5;
        series.DefaultElement.Color = Color.MidnightBlue;
        //series.DefaultElement.Marker = new ElementMarker(ElementMarkerType.None);
        collection.Add(series);

        return(collection);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";

            string yearString  = Request.QueryString["Year"];
            string monthString = Request.QueryString["Month"];

            int year  = Int32.Parse(yearString);
            int month = Int32.Parse(monthString);

            if (!CurrentAuthority.HasAccess(new Access(CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Read)))
            {
                throw new UnauthorizedAccessException("Access denied because security tokens say so");
            }

            DateTime periodStart, periodEnd;
            bool     zeroStart          = false;
            bool     zeroEnd            = false;
            bool     displayDescription = CurrentAuthority.HasAccess(new Access(CurrentOrganization, AccessAspect.BookkeepingDetails, AccessType.Read));

            // HACK HACK HACK
            if (CurrentOrganization.Identity == 8 && CurrentOrganization.Name.StartsWith("Rick Falkvinge"))
            {
                // TODO
                displayDescription = true; // FIX THIS WITH A DAMN SETTING, YOU MORON, DON'T HARDCODE IT
            }

            bool canSeeAudit = CurrentAuthority.HasAccess(new Access(CurrentOrganization, AccessAspect.Auditing, AccessType.Read));

            if (month > 0 && month <= 12)
            {
                periodStart = new DateTime(year, month, 1);
                periodEnd   = periodStart.AddMonths(1);
            }
            else if (month > 20 && month < 25) // quarters 1..4 are coded as months 21..24
            {
                periodStart = new DateTime(year, (month - 21) * 3 + 1, 1);
                periodEnd   = periodStart.AddMonths(3);
            }
            else if (month == 31) // "whole year" is coded as month 31
            {
                periodStart = new DateTime(year, 1, 1);
                periodEnd   = new DateTime(year + 1, 1, 1);
            }
            else
            {
                throw new ArgumentException("Invalid month supplied: " + month.ToString(CultureInfo.InvariantCulture));
            }

            DateTime profitLossStart = new DateTime(periodStart.Year, 1, 1);
            DateTime balanceStart    = Constants.DateTimeLow;

            FinancialAccounts    accounts = FinancialAccounts.ForOrganization(CurrentOrganization);
            FinancialAccountRows rows     = accounts.GetRows(periodStart, periodEnd);

            StringBuilder result = new StringBuilder(16384);

            Dictionary <int, Int64>            runningBalanceLookup = new Dictionary <int, long>();
            Dictionary <int, FinancialAccount> accountLookup        = new Dictionary <int, FinancialAccount>();

            foreach (FinancialAccount accountLoop in accounts)
            {
                accountLookup[accountLoop.Identity] = accountLoop;
            }

            int currentTransactionId = 0;
            int rowCount             = 0;

            foreach (FinancialAccountRow row in rows)
            {
                string creditString = string.Empty;
                string debitString  = string.Empty;

                FinancialAccount account = accountLookup[row.FinancialAccountId];
                if (!runningBalanceLookup.ContainsKey(row.FinancialAccountId))
                {
                    if (account.AccountType == FinancialAccountType.Asset || account.AccountType == FinancialAccountType.Debt)
                    {
                        runningBalanceLookup[account.Identity] = account.GetDeltaCents(balanceStart, periodStart);
                    }
                    else
                    {
                        runningBalanceLookup[account.Identity] = account.GetDeltaCents(profitLossStart, periodStart);
                    }
                }

                if (row.FinancialTransactionId != currentTransactionId)
                {
                    // We're starting a new transaction here

                    // If it's not the first one, close the previous one first
                    if (currentTransactionId != 0)
                    {
                        result.Append("]},");
                    }

                    FinancialTransaction transaction = row.Transaction;
                    string description = transaction.Description;

                    string hasDoxString =
                        "<img src='/Images/Icons/iconshock-search-256px.png' onmouseover=\"this.src='/Images/Icons/iconshock-search-hot-256px.png';\" onmouseout=\"this.src='/Images/Icons/iconshock-search-256px.png';\" data-txid='{0}' class='LocalViewDox' style='cursor:pointer' height='20' width='20' />" +
                        "<img src='/Images/Icons/iconshock-download-240px.png' onmouseover=\"this.src='/Images/Icons/iconshock-download-hot-240px.png';\" onmouseout=\"this.src='/Images/Icons/iconshock-download-240px.png';\" data-docid='{1}' data-docname=\"{2}\" class='LocalDownloadDox' style='cursor:pointer' height='18' width='18' />";

                    string actionHtml = string.Empty;

                    Documents documents = Documents.ForObject(transaction.Dependency ?? transaction);

                    if (documents.Count > 0)
                    {
                        foreach (Document doc in documents)
                        {
                            actionHtml += String.Format("<a href='/Pages/v5/Support/StreamUpload.aspx?DocId={0}&hq=1' data-caption=\"{1}\" class='FancyBox_Gallery' data-fancybox='{2}'></a>",
                                                        doc.Identity, doc.ClientFileName.Replace("\"", "'"), transaction.Identity);
                        }

                        actionHtml = String.Format(hasDoxString, row.FinancialTransactionId.ToString(CultureInfo.InvariantCulture), documents[0].Identity, CurrentOrganization.Name + " - " + Resources.Global.Financial_GeneralLedger + " " + transaction.DateTime.ToShortDateString() + " - " + Resources.Global.Financial_TransactionIdShort + transaction.OrganizationSequenceId.ToString("N0")) + "<span class='hiddenDocLinks'>" + actionHtml + "</span>";
                    }

                    result.Append("{" + String.Format(
                                      "\"id\":\"{0:N0}\",\"idDisplay\":\"<span class='weight-more-emphasis'>{0:N0}</span>\",\"datetime\":\"<span class='weight-more-emphasis'>{1:MMM-dd HH:mm}</span>\",\"txDescription\":\"<span class='weight-more-emphasis tx-description'>{2}</span>\",\"action\":\"{3}\"," +
                                      "\"state\":\"open\",\"children\":[",
                                      row.Transaction.OrganizationSequenceId,
                                      row.TransactionDateTime,
                                      JsonSanitize(description),
                                      JsonSanitize(actionHtml)));

                    if (transaction.Dependency != null)
                    {
                        IHasIdentity dependency = transaction.Dependency;
                        string       info       = string.Empty;
                        Documents    docs       = null;

                        if (dependency is VatReport)
                        {
                            VatReport report = (VatReport)dependency;
                            if (report.OpenTransactionId == transaction.Identity)
                            {
                                info = String.Format(Resources.Pages.Ledgers.InspectLedgers_TxInfo_OpenVatReport,
                                                     report.DescriptionShort);
                            }
                            else if (report.CloseTransactionId == transaction.Identity)
                            {
                                info = String.Format(Resources.Pages.Ledgers.InspectLedgers_TxInfo_CloseVatReport,
                                                     report.DescriptionShort);
                            }
                        }

                        // TODO: Continue here with adding Info row under transactions where it's helpful
                        // TODO: Remember that the Info row needs cell merging, colspan=5 or =6
                    }


                    /*
                     * result.Append("{" + String.Format(
                     *  "\"id\":\"{0:N0}\",\"datetime\":\"{1:MMM-dd HH:mm}\",\"description\":\"{2}\"," +
                     *  "\"action\":\"{6}\",\"state\":\"open\",\"children\":[",
                     *  row.Transaction.OrganizationSequenceId,
                     *  row.TransactionDateTime,
                     *  JsonSanitize(description),
                     *  debitString,
                     *  creditString,
                     *  runningBalanceLookup[row.FinancialAccountId]/100.0,
                     *  JsonSanitize(actionHtml)));
                     */

                    currentTransactionId = row.FinancialTransactionId;
                    rowCount             = 1;
                }
                else
                {
                    // still same transaction
                    result.Append(",");
                    rowCount++;
                }

                if (row.AmountCents < 0)
                {
                    creditString = String.Format("{0:N2}", row.AmountCents / 100.0);
                }
                else if (row.AmountCents > 0)
                {
                    debitString = String.Format("{0:N2}", row.AmountCents / 100.0);
                }

                runningBalanceLookup[row.FinancialAccountId] += row.AmountCents;

                /*
                 * if (canSeeAudit)
                 * {
                 *  actionHtml +=
                 *      String.Format (
                 *          "&nbsp;<img src=\"/Images/Icons/iconshock-flag-white-16px.png\" class=\"LocalIconFlag\" txId=\"{0}\" />",
                 *          row.FinancialTransactionId.ToString (CultureInfo.InvariantCulture));
                 * }*/

                //result.Append("{\"description\":\"child\"}");

                string accountClass;
                switch (accountLookup[row.FinancialAccountId].AccountType)
                {
                case FinancialAccountType.Asset:
                    accountClass = Resources.Global.Financial_Asset;
                    break;

                case FinancialAccountType.Debt:
                    accountClass = Resources.Global.Financial_Debt;
                    break;

                case FinancialAccountType.Income:
                    accountClass = Resources.Global.Financial_Income;
                    break;

                case FinancialAccountType.Cost:
                    accountClass = Resources.Global.Financial_Cost;
                    break;

                default:
                    throw new NotImplementedException();
                }

                string accountName = account.Name;

                if (account.ParentIdentity != 0)
                {
                    if (!accountLookup.ContainsKey(account.ParentIdentity))
                    {
                        accountLookup[account.ParentIdentity] = account.Parent;
                    }

                    accountName = accountLookup[account.ParentIdentity].Name + " » " + accountName;
                }

                result.Append("{" + String.Format(
                                  "\"id\":\"{0:N0}-{6:N0}\",\"idDisplay\":\"{0:N0}:{6:N0}\",\"datetime\":\"{1}\",\"txDescription\":\"{2}\"," +
                                  "\"deltaPos\":\"{3}\",\"deltaNeg\":\"{4}\",\"balance\":\"{5:N2}\"",
                                  row.Transaction.OrganizationSequenceId,
                                  JsonSanitize(accountClass),
                                  JsonSanitize(accountName),
                                  debitString,
                                  creditString,
                                  runningBalanceLookup[row.FinancialAccountId] / 100.0,
                                  rowCount) + "}");
            }

            if (rows.Count == 0)
            {
                // If there are no transactions in this time period, say so

                result.Append("{\"description\":\"" +
                              JsonSanitize(Resources.Pages.Ledgers.InspectLedgers_NoTransactions) + "\"},");
            }

            Response.Output.WriteLine("[" + result.ToString().TrimEnd(',') + "]}]");
            Response.End();
        }
Esempio n. 25
0
    public void Populate(Organization organization, FinancialAccountType accountType)
    {
        FinancialAccounts accounts = FinancialAccounts.ForOrganization(organization, accountType);

        Populate(accounts);
    }
Esempio n. 26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        this.PageAccessRequired = new Access(this.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write);

        this.PageTitle = "Close Ledgers";
        this.PageIcon  = "iconshock-calculator-lock";

        // Check if on a closable year

        if (this.CurrentOrganization.Parameters.EconomyEnabled == false || this.CurrentOrganization.Parameters.FiscalBooksClosedUntilYear == DateTime.Today.Year - 1)
        {
            this.PanelCannotClose.Visible           = true;
            this.PanelSuccess.Visible               = false;
            this.LabelCannotCloseLedgersReason.Text = "Ledgers are already closed as far as possible. [LOC]";
            return; // a return out of Page_Load is kind of unusual, see it as a "break" or "abort"
        }

        // Check if all transactions are balanced, so we can close

        FinancialTransactions unbalancedTransactions = FinancialTransactions.GetUnbalanced(this.CurrentOrganization); // TODO: this fn should move to Organization

        int closingYear = this.CurrentOrganization.Parameters.FiscalBooksClosedUntilYear + 1;

        bool hasOpenTxForClosingYear = false;

        foreach (FinancialTransaction unbalancedTransaction in unbalancedTransactions)
        {
            if (unbalancedTransaction.DateTime.Year <= closingYear)
            {
                hasOpenTxForClosingYear = true;
            }
        }

        if (hasOpenTxForClosingYear)
        {
            this.PanelCannotClose.Visible = true;
            this.PanelSuccess.Visible     = false;
            return; // a return out of Page_Load is kind of unusual, see it as a "break" or "abort"
        }

        // Start actually closing the ledgers


        // First, roll over virtual balances.

        //if (false) // if this.CurrentOrganization.Parameters.VirtualBankingEnabled
        //{
        //    FinancialAccount rootAccount = FinancialAccount.FromIdentity(29);  // HACK: Hardcoded account; should be _organization.FinancialAccount.CostsVirtualBankingRoot
        //    FinancialAccount tempAccount = FinancialAccount.FromIdentity(98);  // HACK: Hardcoded account; should be _organization.FinancialAccount.AssetsVirtualRollover

        //    FinancialAccounts localAccounts = rootAccount.GetTree();

        //    foreach (FinancialAccount account in localAccounts)
        //    {
        //        Int64 currentBalanceCents = account.GetDeltaCents(new DateTime(closingYear, 1, 1), new DateTime(closingYear+1, 1, 1));
        //        Int64 budgetCents = -account.GetBudgetCents(closingYear);
        //        Int64 carryOverCents = budgetCents - currentBalanceCents;

        //        if (carryOverCents != 0)
        //        {
        //            FinancialTransaction transactionOldYear = FinancialTransaction.Create(1,
        //                                                                                  new DateTime(closingYear, 12,
        //                                                                                               31, 23, 50,
        //                                                                                               00),
        //                                                                                  "Budgetrest " + account.Name);
        //                // HACK: Localize rollover label

        //            transactionOldYear.AddRow(account, carryOverCents, null);
        //            transactionOldYear.AddRow(tempAccount, -carryOverCents, null);

        //            FinancialTransaction transactionNewYear = FinancialTransaction.Create(1,
        //                                                                                  new DateTime(closingYear + 1,
        //                                                                                               1, 1, 0, 10, 0),
        //                                                                                  "Budgetrest " +
        //                                                                                  closingYear.ToString() + " " +
        //                                                                                  account.Name);

        //            transactionNewYear.AddRow(account, -carryOverCents, null);
        //            transactionNewYear.AddRow(tempAccount, carryOverCents, null);
        //        }
        //    }
        //}

        // Then, actually close the ledgers.

        FinancialAccounts accounts          = FinancialAccounts.ForOrganization(this.CurrentOrganization);
        Int64             balanceDeltaCents = 0;
        Int64             resultsDeltaCents = 0;

        foreach (FinancialAccount account in accounts)
        {
            Int64 accountBalanceCents;

            if (account.AccountType == FinancialAccountType.Asset || account.AccountType == FinancialAccountType.Debt)
            {
                accountBalanceCents = account.GetDeltaCents(new DateTime(2006, 1, 1), new DateTime(closingYear + 1, 1, 1));
                balanceDeltaCents  += accountBalanceCents;
            }
            else
            {
                accountBalanceCents = account.GetDeltaCents(new DateTime(closingYear, 1, 1), new DateTime(closingYear + 1, 1, 1));
                resultsDeltaCents  += accountBalanceCents;
            }
        }

        if (balanceDeltaCents == -resultsDeltaCents && closingYear < DateTime.Today.Year)
        {
            FinancialTransaction resultTransaction = FinancialTransaction.Create(this.CurrentOrganization.Identity, new DateTime(closingYear, 12, 31, 23, 59, 00), "Årets resultat " + closingYear.ToString());  // TODO: Localize string
            resultTransaction.AddRow(this.CurrentOrganization.FinancialAccounts.CostsYearlyResult, -resultsDeltaCents, null);
            resultTransaction.AddRow(this.CurrentOrganization.FinancialAccounts.DebtsEquity, -balanceDeltaCents, null);

            // Ledgers are now at zero-sum for the year's result accounts and from the start up until end-of-closing-year for the balance accounts.

            Organization.PPSE.Parameters.FiscalBooksClosedUntilYear = closingYear;
        }
        else
        {
            Console.WriteLine("NOT creating transaction.");
        }
    }
Esempio n. 27
0
        public static ChangeAccountDataResult SetAccountBudget(int accountId, string budget)
        {
            try
            {
                AuthenticationData authData = GetAuthenticationDataAndCulture();
                FinancialAccount   account  = FinancialAccount.FromIdentity(accountId);

                if (!PrepareAccountChange(account, authData, false))
                {
                    return(new ChangeAccountDataResult
                    {
                        Result = ChangeAccountDataOperationsResult.NoPermission
                    });
                }

                Int64 newTreeBudget;
                budget = budget.Replace("%A0", "%20");
                // some very weird browser space-to-otherspace translation weirds out number parsing
                budget = HttpContext.Current.Server.UrlDecode(budget);

                if (budget.Trim().Length > 0 &&
                    Int64.TryParse(budget, NumberStyles.Currency, CultureInfo.CurrentCulture, out newTreeBudget))
                {
                    newTreeBudget *= 100; // convert to cents

                    int year = DateTime.Today.Year;
                    FinancialAccounts accountTree         = account.ThisAndBelow();
                    Int64             currentTreeBudget   = accountTree.GetBudgetSumCents(year);
                    Int64             currentSingleBudget = account.GetBudgetCents(year);
                    Int64             suballocatedBudget  = currentTreeBudget - currentSingleBudget;

                    Int64 newSingleBudget = newTreeBudget - suballocatedBudget;

                    account.SetBudgetCents(DateTime.Today.Year, newSingleBudget);

                    // Once we've set the budget, also update the "yearly result" budget.
                    // The "yearly result" budget isn't shown in the account plan, but is
                    // abstracted to "projected loss" or "projected gain" pseudobudgets.

                    int thisYear = DateTime.UtcNow.Year;
                    FinancialAccounts allProfitLossAccounts   = FinancialAccounts.ForOrganization(authData.CurrentOrganization);
                    Int64             newProfitLossProjection = allProfitLossAccounts.Where(queryAccount => queryAccount.Identity != authData.CurrentOrganization.FinancialAccounts.CostsYearlyResult.Identity).Sum(queryAccount => queryAccount.GetBudgetCents(thisYear));

                    authData.CurrentOrganization.FinancialAccounts.CostsYearlyResult.SetBudgetCents(thisYear, -newProfitLossProjection);

                    return(new ChangeAccountDataResult
                    {
                        Result = ChangeAccountDataOperationsResult.Changed,
                        NewData = (newTreeBudget / 100).ToString("N0", CultureInfo.CurrentCulture)
                    });
                }

                return(new ChangeAccountDataResult
                {
                    Result = ChangeAccountDataOperationsResult.Invalid
                });
            }
            catch (Exception weirdException)
            {
                // Exceptions are happening here in deployment ONLY. We're logging it to find which one and why.
                // TODO: This really needs to be in Logic. DO NOT DO NOT DO NOT call Database layer directly from Site layer.

                SwarmDb.GetDatabaseForWriting()
                .CreateExceptionLogEntry(DateTime.UtcNow, "AccountPlan-SetBudget", weirdException);

                throw;
            }
        }
Esempio n. 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            FinancialAccounts allOwned = new FinancialAccounts();

            Memberships memberships = this.person.GetMemberships();

            int  orgOwned     = 0;
            bool multipleOrgs = false;

            foreach (Membership membership in memberships)
            {
                FinancialAccounts orgAccounts = FinancialAccounts.ForOrganization(membership.Organization);
                foreach (FinancialAccount account in orgAccounts)
                {
                    if (account.OwnerPersonId == this.person.Identity)
                    {
                        allOwned.Add(account);

                        if (orgOwned == 0 || orgOwned == membership.OrganizationId)
                        {
                            orgOwned = membership.OrganizationId;
                        }
                        else
                        {
                            multipleOrgs = true;
                        }
                    }
                }
            }

            if (allOwned.Count > 0)
            {
                string literal =
                    "<span style=\"line-height:150%\"><table border=\"0\" cellspacing=\"0\" width=\"100%\">";

                int      year        = DateTime.Today.Year;
                DateTime now         = DateTime.Now;
                DateTime jan1        = new DateTime(year, 1, 1);
                bool     budgetFound = false;

                foreach (FinancialAccount account in allOwned)
                {
                    double  budget    = -account.GetBudget(year);
                    decimal spent     = account.GetDelta(jan1, now);
                    decimal remaining = (decimal)budget - spent;

                    if (budget == 0.0 && spent == 0.0m)
                    {
                        continue; // not interesting
                    }

                    budgetFound = true;
                    literal    += "<tr><td>";

                    if (multipleOrgs)
                    {
                        literal += Server.HtmlEncode(account.Organization.NameShort) + " - ";
                    }

                    literal += "<a href=\"/Pages/v4/Financial/ManageBudget.aspx?AccountId=" + account.Identity + "\">" + Server.HtmlEncode(account.Name) + "</a>&nbsp;</td><td align=\"right\">";

                    literal += Server.HtmlEncode(remaining.ToString("N2"));

                    literal += "</td><td>&nbsp;of&nbsp;</td><td align=\"right\">";

                    literal += Server.HtmlEncode(budget.ToString("N2"));

                    literal += "</td><td align=\"right\">&nbsp;(";

                    if (budget != 0.0)
                    {
                        literal += (remaining / (decimal)budget).ToString("P0");
                    }
                    else
                    {
                        literal += "--%";
                    }

                    literal += " left)</td><tr>\r\n";
                }

                if (!budgetFound)
                {
                    literal += "<tr><td>No budget allocated to you (yet?) for " + year.ToString() + ".</td></tr>\r\n";
                }

                literal +=
                    "<tr><td>&nbsp;</td></tr><tr><td colspan=\"5\" align=\"right\"><a href=\"/Pages/v4/Financial/AllocateFunds.aspx\">Allocate funds...</a></td></tr>\r\n";

                literal += "</table></span>";

                this.LiteralBudgetData.Text = literal;
            }
            else
            {
                this.LiteralBudgetData.Text = "You own no budgets.";
            }
        }
Esempio n. 29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.PageAccessRequired = new Access(this.CurrentOrganization, AccessAspect.BookkeepingDetails);

            this.PageTitle =
                this.Title =
                    this.LabelHeader.Text =
                        String.Format(Resources.Pages.Ledgers.EndOfMonth_Title, DateTime.UtcNow.AddMonths(-1));

            this.InfoBoxLiteral = Resources.Pages.Ledgers.EndOfMonth_Info;

            // Check which reports are required

            ItemGroups = new List <EomItemGroup>();

            // Group I: External data & accounts

            EomItemGroup group1 = new EomItemGroup();

            group1.Header = Resources.Pages.Ledgers.EndOfMonth_Header_ExternalData;
            group1.Id     = "ExternalData";

            string lastUploadItemId = string.Empty;

            // Iterate over all Balance accounts and check for automation;
            // if so, add it to an upload sequence

            FinancialAccounts assetAccounts = FinancialAccounts.ForOrganization(this.CurrentOrganization,
                                                                                FinancialAccountType.Asset);

            DateTime lastMonthEndDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1).AddDays(-1);
            int      lastMonth        = lastMonthEndDate.Year * 100 + lastMonthEndDate.Month;
            bool     skippable        = true;

            foreach (FinancialAccount assetAccount in assetAccounts)
            {
                if (assetAccount.AutomationProfileId != 0)
                {
                    // This account has automation
                    // If automation has Bank Account Statement enabled (assume true for now):

                    FinancialAccountDocument lastBankStatement =
                        assetAccount.GetMostRecentDocument(FinancialAccountDocumentType.BankStatement);
                    int lastStatementMonth = (this.CurrentOrganization.FirstFiscalYear - 1) * 100 + 12;
                    // December of the year before

                    if (lastBankStatement != null)
                    {
                        lastStatementMonth = lastBankStatement.ConcernsPeriodStart.Year * 100 +
                                             lastBankStatement.ConcernsPeriodStart.Month;
                        skippable = false;
                    }

                    string lastId        = string.Empty;
                    int    monthIterator = lastStatementMonth;

                    while (monthIterator < lastMonth)
                    {
                        monthIterator++;
                        if (monthIterator % 100 == 13)
                        {
                            monthIterator += 88;
                        }

                        EomItem bankStatement = new EomItem();
                        bankStatement.DependsOn = lastId; // empty for first record
                        bankStatement.Id        = lastId = "BankStatement-" +
                                                           assetAccount.Identity.ToString(CultureInfo.InvariantCulture) + '-' +
                                                           monthIterator;
                        bankStatement.Name = string.Format(Resources.Pages.Ledgers.EndOfMonth_UploadBankStatementFor,
                                                           assetAccount.Name, "PDF",
                                                           new DateTime(monthIterator / 100, monthIterator % 100, 15).ToString("MMMM yyyy"));
                        bankStatement.Completed = false; // TODO
                        bankStatement.Icon      = "upload";
                        bankStatement.Skippable = skippable;

                        group1.Items.Add(bankStatement);
                    }

                    // Add data upload item

                    // TODO: Check if the last data upload was into the current month

                    EomItem dataUploadItem = new EomItem();
                    dataUploadItem.Id        = "BankTransactionData-" + assetAccount.Identity.ToString(CultureInfo.InvariantCulture);
                    dataUploadItem.Icon      = "upload";
                    dataUploadItem.Completed = false; // todo
                    dataUploadItem.Name      = String.Format(Resources.Pages.Ledgers.EndOfMonth_UploadTransactionDataFor,
                                                             assetAccount.Name, "CSV");
                    dataUploadItem.Skippable = false;

                    group1.Items.Add(dataUploadItem);

                    // Check if we need to add a resync of the hotwallet's native ledger

                    if (CurrentOrganization.FinancialAccounts.AssetsBitcoinHot != null) // has hotwallet
                    {
                        Int64 cashSatoshisInLedger =
                            CurrentOrganization.FinancialAccounts.AssetsBitcoinHot.GetForeignCurrencyBalanceDeltaCents(
                                Constants.DateTimeLow, Constants.DateTimeHigh).Cents;

                        Int64 cashSatoshisInHotwallet =
                            HotBitcoinAddresses.GetSatoshisInHotwallet(CurrentOrganization)[BitcoinChain.Cash];

                        if (cashSatoshisInHotwallet != cashSatoshisInLedger)
                        {
                            // Resync required

                            EomItem resyncSatoshiCountItem = new EomItem();
                            resyncSatoshiCountItem.Id        = "ResyncSatoshisInLedger";
                            resyncSatoshiCountItem.Icon      = "approve";
                            resyncSatoshiCountItem.Completed = false;
                            resyncSatoshiCountItem.Skippable = false;
                            resyncSatoshiCountItem.Callback  = "ResyncSatoshisInLedger";
                            resyncSatoshiCountItem.Name      = Resources.Pages.Ledgers.EndOfMonth_CheckLedgerAgainstHotWallet;
                            group1.Items.Add(resyncSatoshiCountItem);
                        }
                    }
                }
            }

            // If there are any items in Group 1, OR if an account matching is necessary, then
            // add that as an action item

            if (group1.Items.Count() > 0 || FinancialTransactions.GetUnbalanced(this.CurrentOrganization).Count() > 0)
            {
                EomItem matchAccounts = new EomItem();
                matchAccounts.DependsOn = lastUploadItemId; // may be empty if there's nothing to upload and that's ok
                matchAccounts.Id        = "MatchAccounts";
                matchAccounts.Completed = false;            // we already know there's at least one unbalanced
                matchAccounts.Icon      = "wrench";
                matchAccounts.Skippable = false;
                matchAccounts.Name      = Resources.Pages.Ledgers.EndOfMonth_MatchAccounts;

                group1.Items.Add(matchAccounts);
            }

            if (group1.Items.Count > 0)
            {
                ItemGroups.Add(group1);
            }

            // Group: Payroll and Taxes

            EomItemGroup group2 = new EomItemGroup();

            group2.Header = Resources.Pages.Ledgers.EndOfMonth_Header_PayrollTaxes;
            group2.Id     = "PayrollTaxes";

            ReportRequirement vatRequired = VatReport.IsRequired(this.CurrentOrganization);

            if (vatRequired == ReportRequirement.Required || vatRequired == ReportRequirement.Completed)
            {
                EomItem vatReport = new EomItem();
                vatReport.Id        = "VatReport";
                vatReport.Callback  = "CreateVatReport";
                vatReport.Completed = (vatRequired == ReportRequirement.Completed ? true : false);
                vatReport.Name      = String.Format(Resources.Pages.Ledgers.EndOfMonth_CreateVatReport,
                                                    (vatReport.Completed
                        ? VatReport.LastReportDescription(this.CurrentOrganization)
                        : VatReport.NextReportDescription(this.CurrentOrganization)));
                vatReport.Icon = "document";

                group2.Items.Add(vatReport);
            }

            Payroll payroll = Payroll.ForOrganization(this.CurrentOrganization);

            if (payroll.Any())
            {
                // There is active payroll

                // TODO: Taxes for last month and processing for this month
            }
            else
            {
                EomItem payrollInactive = new EomItem();
                payrollInactive.Id        = "PayrollInactive";
                payrollInactive.Completed = true;
                payrollInactive.Name      = Resources.Pages.Ledgers.EndOfMonth_PayrollInactive;
                payrollInactive.Icon      = "document";
                group2.Items.Add(payrollInactive);
            }

            if (group2.Items.Count > 0)
            {
                ItemGroups.Add(group2);
            }

            // Group: Closure of Ledgers and Annual Reports

            int lastClosedYear = CurrentOrganization.Parameters.FiscalBooksClosedUntilYear;

            if (lastClosedYear - 1 < DateTime.UtcNow.Year)
            {
                EomItemGroup groupReports = new EomItemGroup();

                groupReports.Header = Resources.Pages.Ledgers.EndOfMonth_Header_AnnualReports;
                EomItem itemCloseYear = new EomItem();
                itemCloseYear.Id       = "CloseLedgers";
                itemCloseYear.Callback = "CloseLedgers";
                itemCloseYear.Icon     = "document";
                itemCloseYear.Name     = String.Format(Resources.Pages.Ledgers.EndOfMonth_CloseLedgersFor,
                                                       lastClosedYear + 1);

                groupReports.Items.Add(itemCloseYear);
                ItemGroups.Add(groupReports);
            }
        }