diff --git a/Database/Configuration.cs b/Database/Configuration.cs index e0e2bfd2..c382fe74 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -14,7 +14,7 @@ namespace Swarmops.Database /// public static int DbVersionExpected { - get { return 45; } + get { return 46; } } diff --git a/Database/Database-VatReports.cs b/Database/Database-VatReports.cs index 3d68958c..e34a70dc 100644 --- a/Database/Database-VatReports.cs +++ b/Database/Database-VatReports.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Globalization; using Swarmops.Basic.Types; using Swarmops.Basic.Types.Financial; using Swarmops.Common.Enums; @@ -163,6 +164,45 @@ namespace Swarmops.Database #endregion + + #region Database optimizations + + + public BasicFinancialAccountRow[] GetAccountRowsNotInVatReport(int accountId, DateTime endDate) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT " + accountId.ToString(CultureInfo.InvariantCulture) + ", FinancialTransactions.TransactionId, FinancialTransactions.DateTime, FinancialTransactions.Comment, AmountCents, CreatedDateTime, CreatedByPersonId " + + " FROM FinancialTransactionRows " + + " JOIN FinancialTransactions ON (FinancialTransactionRows.FinancialTransactionId = FinancialTransactions.FinancialTransactionId) " + + " WHERE NOT EXISTS (SELECT * FROM VatReportItems WHERE FinancialTransactionId = FinancialTransactions.FinancialTransactionRowId) " + + " AND AccountId = @accountId " + + " AND FinancialTransaction.DateTime < @endDateTime" , connection); + + AddParameterWithName(command, "accountId", accountId); + AddParameterWithName(command, "endDateTime", endDate); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadFinancialAccountRowFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + #endregion + + #region Creation and manipulation - stored procedures public int CreateVatReport (int organizationId, string guid, int yearMonthStart, int monthCount) diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index e3c4f542..3c1206c8 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -42,4 +42,5 @@ 0042 - Bugfix to SetInboundInvoiceOrganizationSequenceId [RF] 0043 - FinancialTransactionRows housekeeping [RF] 0044 - Mark bitcoin as cryptocurrency [RF] -0045 - VAT Report work [RF] \ No newline at end of file +0045 - VAT Report work [RF] +0046 - VatReports.Turnover=>TurnoverCents [RF] \ No newline at end of file diff --git a/Database/Schemata/upgrade-0046.sql b/Database/Schemata/upgrade-0046.sql new file mode 100644 index 00000000..116a5850 --- /dev/null +++ b/Database/Schemata/upgrade-0046.sql @@ -0,0 +1,2 @@ +ALTER TABLE `VatReports` +CHANGE COLUMN `Turnover` `TurnoverCents` BIGINT(20) NOT NULL diff --git a/Logic/Financial/VatReport.cs b/Logic/Financial/VatReport.cs index b0e15fc5..e4162ce7 100644 --- a/Logic/Financial/VatReport.cs +++ b/Logic/Financial/VatReport.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Swarmops.Basic.Types.Financial; +using Swarmops.Common.Enums; using Swarmops.Common.Interfaces; using Swarmops.Database; using Swarmops.Logic.Structure; @@ -38,7 +39,7 @@ namespace Swarmops.Logic.Financial return FromBasic(SwarmDb.GetDatabaseForWriting().GetVatReport(vatReportId)); } - public static VatReport Create(Organization organization, int year, int startMonth, int monthCount) + private static VatReport CreateDbRecord (Organization organization, int year, int startMonth, int monthCount) { System.Guid guid = System.Guid.NewGuid(); @@ -47,11 +48,141 @@ namespace Swarmops.Logic.Financial return FromIdentityAggressive(vatReportId); } + internal static VatReport Create(Organization organization, int year, int startMonth, int monthCount) + { + VatReport newReport = CreateDbRecord(organization, year, startMonth, monthCount); + DateTime startDate = new DateTime(year, startMonth, 1).AddYears(-1); // start a year before report starts + DateTime endDate = new DateTime(year, startMonth, 1).AddMonths(monthCount); + + FinancialAccount vatInbound = organization.FinancialAccounts.AssetsVatInboundUnreported; + FinancialAccount vatOutbound = organization.FinancialAccounts.DebtsVatOutboundUnreported; + FinancialAccount sales = organization.FinancialAccounts.IncomeSales; + + FinancialAccountRows inboundRows = RowsNotInVatReport(vatInbound, endDate); + FinancialAccountRows outboundRows = RowsNotInVatReport(vatOutbound, endDate); + FinancialAccountRows turnoverRows = RowsNotInVatReport(sales, endDate); + + Dictionary transactionsIncludedLookup = new Dictionary(); + + newReport.AddVatReportItemsFromAccountRows(inboundRows, transactionsIncludedLookup); + newReport.AddVatReportItemsFromAccountRows(outboundRows, transactionsIncludedLookup); + newReport.AddVatReportItemsFromAccountRows(turnoverRows, transactionsIncludedLookup); + + newReport.Release(); + + string transactionComment = String.Format("VAT Report {0}", year); + + if (monthCount != 12) + { + transactionComment += String.Format(" {0:MMM}", new DateTime(year, startMonth, 16)); + } + + if (monthCount != 1) + { + transactionComment += String.Format("-{0:MMM}", new DateTime(year, startMonth+monthCount-1, 16)); + } + + // Create financial TX that moves this VAT from unreported to reported + + Int64 differenceCents = newReport.VatInboundCents - newReport.VatOutboundCents; + + if (differenceCents != 0 && newReport.VatInboundCents > 0) + { + // if there's anything to report + + FinancialTransaction vatReportTransaction = FinancialTransaction.Create(organization, DateTime.UtcNow, + transactionComment); + vatReportTransaction.AddRow(organization.FinancialAccounts.AssetsVatInboundUnreported, + -newReport.VatInboundCents, null); + vatReportTransaction.AddRow(organization.FinancialAccounts.DebtsVatOutboundUnreported, + newReport.VatOutboundCents, null); // not negative, because our number is sign-different from the bookkeeping's + + if (differenceCents < 0) // outbound > inbound + { + vatReportTransaction.AddRow(organization.FinancialAccounts.DebtsVatOutboundReported, + differenceCents, null); // debt, so negative as in our variable + } + else // inbound > outbound + { + vatReportTransaction.AddRow(organization.FinancialAccounts.AssetsVatInboundReported, + differenceCents, null); // asset, so positive as in our variable + } + + vatReportTransaction.Dependency = newReport; + } + + return newReport; + } + + private void AddVatReportItemsFromAccountRows(FinancialAccountRows rows, + Dictionary transactionsIncludedLookup) + { + if (rows.Count == 0) + { + return; + } + + Organization organization = rows[0].Transaction.Organization; // there is always a rows[0] because check above + int vatInboundAccountId = organization.FinancialAccounts.AssetsVatInboundUnreported.Identity; + int vatOutboundAccountId = organization.FinancialAccounts.DebtsVatOutboundUnreported.Identity; + + Dictionary turnoverAccountLookup = new Dictionary(); + + FinancialAccounts turnoverAccounts = FinancialAccounts.ForOrganization(organization, + FinancialAccountType.Income); + + foreach (FinancialAccount turnoverAccount in turnoverAccounts) + { + turnoverAccountLookup[turnoverAccount.Identity] = true; + } + + foreach (FinancialAccountRow accountRow in rows) + { + FinancialTransaction tx = accountRow.Transaction; + + if (!transactionsIncludedLookup.ContainsKey(tx.Identity)) + { + Int64 vatInbound = 0; + Int64 vatOutbound = 0; + Int64 turnOver = 0; + + transactionsIncludedLookup[accountRow.FinancialTransactionId] = true; + + FinancialTransactionRows txRows = accountRow.Transaction.Rows; + + foreach (FinancialTransactionRow txRow in txRows) + { + if (txRow.FinancialAccountId == vatInboundAccountId) + { + vatInbound += txRow.AmountCents; + } + else if (txRow.FinancialAccountId == vatOutboundAccountId) + { + vatOutbound += -txRow.AmountCents; // this is a negative, so converting to positive + } + else if (turnoverAccountLookup.ContainsKey(txRow.FinancialAccountId)) + { + turnOver += txRow.AmountCents; + } + } + + // Add new row to the VAT report + + AddItem(tx, turnOver, vatInbound, vatOutbound); + } + } + } + #endregion public void AddItem(FinancialTransaction transaction, Int64 turnoverCents, Int64 vatInboundCents, Int64 vatOutboundCents) { + if (!UnderConstruction) + { + throw new InvalidOperationException("Cannot add items once the report is released"); + } + VatReportItem newItem = VatReportItem.Create(this, transaction, turnoverCents, vatInboundCents, vatOutboundCents); } @@ -68,12 +199,28 @@ namespace Swarmops.Logic.Financial // Releasing calculates sums of turnover, VAT inbound, outbound across items into report record SwarmDb.GetDatabaseForWriting().SetVatReportReleased(this.Identity); + base.UnderConstruction = false; + base.TurnoverCents = Items.TurnoverCents; + base.VatInboundCents = Items.VatInboundCents; + base.VatOutboundCents = Items.VatOutboundCents; } public VatReportItems Items { get { return VatReportItems.ForReport(this); } } + + private static FinancialAccountRows RowsNotInVatReport(FinancialAccount account, DateTime endDateTime) + { + Organization organization = account.Organization; + + FinancialAccountRows rows = + FinancialAccountRows.FromArray( + SwarmDb.GetDatabaseForReading().GetAccountRowsNotInVatReport(account.Identity, endDateTime)); + + return rows; + } } + } diff --git a/Logic/Financial/VatReportItems.cs b/Logic/Financial/VatReportItems.cs index 6191c100..50646e22 100644 --- a/Logic/Financial/VatReportItems.cs +++ b/Logic/Financial/VatReportItems.cs @@ -19,5 +19,29 @@ namespace Swarmops.Logic.Financial } #endregion + + public Int64 TurnoverCents + { + get + { + return this.Sum(item => item.TurnoverCents); + } + } + + public Int64 VatInboundCents + { + get + { + return this.Sum(item => item.VatInboundCents); + } + } + + public Int64 VatOutboundCents + { + get + { + return this.Sum(item => item.VatOutboundCents); + } + } } } diff --git a/Logic/Financial/VatReports.cs b/Logic/Financial/VatReports.cs index f4f3bd48..9dfc4a81 100644 --- a/Logic/Financial/VatReports.cs +++ b/Logic/Financial/VatReports.cs @@ -4,12 +4,68 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Swarmops.Basic.Types.Financial; +using Swarmops.Database; +using Swarmops.Logic.Structure; using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { public class VatReports: PluralBase { + static public void CreateNewReports() + { + // This goes through all organizations and creates VAT reports where organizations are registered for VAT + // and it's time for a new report to be created. + DateTime nowUtc = DateTime.UtcNow; + + // HACK: Only for organization #8 at the moment while we're building this function. + + // foreach organization, if organization is VAT enabled + + Organization organization = Organization.FromIdentity(8); // HACK TEMPORARY HACK + int reportMonthInterval = 1; // TODO: READ FROM ORG PARAMETERS + + // Get the list of previous VAT reports + + VatReports reports = VatReports.ForOrganization(organization); + + if (reports.Count == 0) + { + DateTime firstReportGenerationTime = + new DateTime(organization.FirstFiscalYear, 1, 1).AddMonths(reportMonthInterval).AddDays(4); + + if (nowUtc > firstReportGenerationTime) + { + VatReport.Create(organization, organization.FirstFiscalYear, 1, reportMonthInterval); + } + } + else + { + reports.Sort(VatReportSorterByDate); + + DateTime lastReport = new DateTime(reports.Last().YearMonthStart/100, reports.Last().YearMonthStart%100, + 1); + DateTime nextReport = lastReport.AddMonths(reportMonthInterval); + + DateTime nextReportGenerationTime = nextReport.AddMonths(reportMonthInterval).AddDays(4); // Make the report on the 4th after the period has ended + if (nextReportGenerationTime > nowUtc) + { + // Create a new report + + VatReport.Create(organization, nextReport.Year, nextReport.Month, reportMonthInterval); + } + } + } + + private static int VatReportSorterByDate (VatReport a, VatReport b) + { + return a.YearMonthStart - b.YearMonthStart; + } + + public static VatReports ForOrganization(Organization organization) + { + return FromArray(SwarmDb.GetDatabaseForReading().GetVatReports(organization)); + } } } diff --git a/Site/Master-v5.master.cs b/Site/Master-v5.master.cs index b2bb627f..42001bac 100644 --- a/Site/Master-v5.master.cs +++ b/Site/Master-v5.master.cs @@ -39,6 +39,7 @@ namespace Swarmops.Frontend // BEGIN TEST CODE + //VatReports.CreateNewReports(); // END TEST CODE