VAT Report work

This commit is contained in:
Rick Falkvinge
2017-10-08 20:52:58 +02:00
parent b8ebf424ef
commit 8c73218594
8 changed files with 274 additions and 3 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Swarmops.Database
/// </summary>
public static int DbVersionExpected
{
get { return 45; }
get { return 46; }
}
+40
View File
@@ -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<BasicFinancialAccountRow> result = new List<BasicFinancialAccountRow>();
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)
+2 -1
View File
@@ -42,4 +42,5 @@
0042 - Bugfix to SetInboundInvoiceOrganizationSequenceId [RF]
0043 - FinancialTransactionRows housekeeping [RF]
0044 - Mark bitcoin as cryptocurrency [RF]
0045 - VAT Report work [RF]
0045 - VAT Report work [RF]
0046 - VatReports.Turnover=>TurnoverCents [RF]
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `VatReports`
CHANGE COLUMN `Turnover` `TurnoverCents` BIGINT(20) NOT NULL
+148 -1
View File
@@ -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<int, bool> transactionsIncludedLookup = new Dictionary<int, bool>();
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<int, bool> 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<int, bool> turnoverAccountLookup = new Dictionary<int, bool>();
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;
}
}
}
+24
View File
@@ -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);
}
}
}
}
+56
View File
@@ -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<VatReports, VatReport, BasicVatReport>
{
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));
}
}
}
+1
View File
@@ -39,6 +39,7 @@ namespace Swarmops.Frontend
// BEGIN TEST CODE
//VatReports.CreateNewReports();
// END TEST CODE