Compare commits

..

2 Commits

Author SHA1 Message Date
abijah
c9ade62536 Very, very messy and broken. It does work somewhat, but I can see just what a mess it's going to be to carry it out, so I'm abandoning.
git-svn-id: file:///svn-source/pmgr/branches/reconcile_entry_to_receipt_20090629@187 97e9348a-65ac-dc4b-aefc-98561f571b83
2009-06-30 00:59:09 +00:00
abijah
4f0b5ffc28 Branch to work on another possible solution to this mess
git-svn-id: file:///svn-source/pmgr/branches/reconcile_entry_to_receipt_20090629@186 97e9348a-65ac-dc4b-aefc-98561f571b83
2009-06-30 00:57:11 +00:00
14 changed files with 680 additions and 652 deletions

View File

@@ -633,6 +633,15 @@ CREATE TABLE `pmgr_customers` (
-- If NULL, rely on the contact info exclusively
`name` VARCHAR(80) DEFAULT NULL,
-- A customer gets their own account, although any
-- lease specific charge (rent, late fees, etc) will
-- be debited against the lease account. This one
-- will be used for non-lease related charges, as
-- well as charges that intentionally span more than
-- one lease (such as one security deposit to cover
-- two or more units).
`account_id` INT(10) UNSIGNED NOT NULL,
-- Primary Contact... every customer must have one
-- (and presumably, most customers will _be_ one).
-- REVISIT <AP> 20090612:
@@ -699,6 +708,7 @@ CREATE TABLE `pmgr_leases` (
`lease_type_id` INT(10) UNSIGNED NOT NULL,
`unit_id` INT(10) UNSIGNED NOT NULL,
`customer_id` INT(10) UNSIGNED NOT NULL,
`account_id` INT(10) UNSIGNED NOT NULL,
`late_schedule_id` INT(10) UNSIGNED DEFAULT NULL,
`lease_date` DATE NOT NULL,
@@ -838,7 +848,7 @@ CREATE TABLE `pmgr_accounts` (
-- For LIABILITY, EQUITY, and INCOME, the opposite
-- is true, with reconciliations posted, under
-- normal circumstances, when a debit occurs.
`trackable` INT UNSIGNED DEFAULT 1,
`trackable` INT UNSIGNED DEFAULT 0,
-- Security Level
`level` INT UNSIGNED DEFAULT 1,
@@ -859,17 +869,15 @@ INSERT INTO `pmgr_accounts` (`type`, `name`, `trackable`)
('ASSET', 'Invoice', 1),
('ASSET', 'Receipt', 1),
('LIABILITY', 'A/P', 1),
('LIABILITY', 'Tax', 1),
('LIABILITY', 'Tax', 0),
('LIABILITY', 'Customer Credit', 1),
('ASSET', 'Bank', 1),
('ASSET', 'Cash', 1),
('ASSET', 'Check', 1),
('ASSET', 'Money Order', 1),
('ASSET', 'Bank', 0),
('ASSET', 'Till', 0),
('LIABILITY', 'Security Deposit', 1),
('INCOME', 'Rent', 1),
('INCOME', 'Late Charge', 1),
('EXPENSE', 'Concession', 1),
('EXPENSE', 'Bad Debt', 1);
('INCOME', 'Rent', 0),
('INCOME', 'Late Charge', 0),
('EXPENSE', 'Concession', 0),
('EXPENSE', 'Bad Debt', 0);
UNLOCK TABLES;
@@ -934,10 +942,6 @@ DROP TABLE IF EXISTS `pmgr_transactions`;
CREATE TABLE `pmgr_transactions` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
-- `type` ENUM('INVOICE',
-- 'RECEIPT')
-- NOT NULL,
`stamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`through_date` DATE DEFAULT NULL,
`due_date` DATE DEFAULT NULL,
@@ -985,9 +989,16 @@ DROP TABLE IF EXISTS `pmgr_reconciliations`;
CREATE TABLE `pmgr_reconciliations` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`debit_ledger_entry_id` INT(10) UNSIGNED NOT NULL,
`credit_ledger_entry_id` INT(10) UNSIGNED NOT NULL,
`amount` FLOAT(12,2) NOT NULL,
`type` ENUM('DEBIT',
'CREDIT')
NOT NULL,
-- Match up the ledger entry to the transaction that
-- reconciles it. For example, this could be a charge
-- matching up with a receipt.
`ledger_entry_id` INT(10) UNSIGNED NOT NULL,
`transaction_id` INT(10) UNSIGNED NOT NULL,
`amount` FLOAT(12,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

View File

@@ -4,8 +4,6 @@ use DBI;
use Data::Dumper;
use File::Copy;
my $use_ir = 1;
# Internally adjust all numbers coming from the database to
# be in inches. Not necessary to go to this detail, but the
# actual units used is irrelevant, provided everything is to
@@ -482,10 +480,8 @@ foreach $row (@$result) {
}
# For compatibility, while deciding on account names
if (!defined $newdb{'lookup'}{'account'}{'Cash'}) {
$newdb{'lookup'}{'account'}{'Cash'}
= $newdb{'lookup'}{'account'}{'Till'};
}
$newdb{'lookup'}{'account'}{'Cash'}
= $newdb{'lookup'}{'account'}{'Till'};
$newdb{'lookup'}{'charge_type'} = {};
$newdb{'lookup'}{'charge_type'}{'Rent'} =
@@ -512,9 +508,9 @@ $newdb{'lookup'}{'payment_type'} = {};
$newdb{'lookup'}{'payment_type'}{1}
= { 'name' => 'Cash', 'account_name' => 'Cash', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'Cash'} };
$newdb{'lookup'}{'payment_type'}{2}
= { 'name' => 'Check', 'account_name' => 'Check', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'Check'} };
= { 'name' => 'Check', 'account_name' => 'Cash', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'Check'} };
$newdb{'lookup'}{'payment_type'}{3}
= { 'name' => 'Money Order', 'account_name' => 'Money Order', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'Money Order'} };
= { 'name' => 'Money Order', 'account_name' => 'Cash', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'Money Order'} };
$newdb{'lookup'}{'payment_type'}{4}
= { 'name' => 'ACH', 'account_name' => 'Bank', 'monetary_type' => $newdb{'lookup'}{'monetary_type'}{'ACH'} };
$newdb{'lookup'}{'payment_type'}{12}
@@ -696,11 +692,15 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'} =
$newdb{'tables'}{'contacts'}{'autoid'};
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'account_id'} =
$newdb{'lookup'}{'account'}{'A/R'}{'account_id'};
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'ledger_id'} =
$newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'};
addRow('customers',
{ 'name' => "$row->{'LastName'}, $row->{'FirstName'}",
'primary_contact_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'},
});
'account_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'account_id'} });
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'} =
$newdb{'tables'}{'customers'}{'autoid'};
@@ -814,18 +814,23 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'ledger'} = {};
$query = "SELECT L.*, A.TenantID FROM TenantLedger L LEFT JOIN `Access` A ON A.LedgerID = L.LedgerID WHERE L.UnitID <> 'POS\$' ORDER BY L.DateIn";
$query = "SELECT L.*, A.TenantID FROM TenantLedger L LEFT JOIN `Access` A ON A.LedgerID = L.LedgerID WHERE L.UnitID <> 'POS\$' ORDER BY L.LedgerID";
foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}
= { 'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'} };
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'account_id'}
= $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'account_id'};
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'ledger_id'}
= $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'ledger_id'};
addRow('leases',
{ #'number' => $newdb{'tables'}{'leases'}{'autoid'}+1,
'number' => $row->{'LedgerID'},
{ 'number' => $row->{'LedgerID'},
'lease_type_id' => $newdb{'tables'}{'lease_types'}{'autoid'},
'unit_id' => $newdb{'lookup'}{'unit'}{$row->{'UnitID'}}{'id'},
'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'},
'account_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'account_id'},
'lease_date' => datefmt($row->{'DateIn'}),
'movein_date' => datefmt($row->{'DateIn'}),
'moveout_date' => datefmt($row->{'DateOut'}),
@@ -849,78 +854,36 @@ foreach $row (@{query($sdbh, $query)}) {
##
######################################################################
## Invoices
## Charges
$newdb{'lookup'}{'charge'} = {};
$query = "SELECT *, ChargeAmount+TaxAmount AS InvoiceAmount FROM Charges ORDER BY ChargeID";
$query = "SELECT * FROM Charges ORDER BY ChargeID";
foreach $row (@{query($sdbh, $query)}) {
my $credit_ledger_id;
my $ledger_entry_id;
addRow('transactions',
{ 'stamp' => datefmt($row->{'ChargeDate'}),
'through_date' => datefmt($row->{'EndDate'}) });
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}
= { 'invoice' =>
{ 'tx' => $newdb{'tables'}{'transactions'}{'autoid'},
'lease_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'},
'customer_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'customer_id'},
'amount' => $row->{'InvoiceAmount'},
} };
= { 'tx' => $newdb{'tables'}{'transactions'}{'autoid'},
'ledger_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'ledger_id'},
#'ledger_id' => $newdb{'lookup'}{'account'}{'Invoice'}{'ledger_id'},
'amount' => $row->{'ChargeAmount'},
'tax_amount' => $row->{'TaxAmount'},
'customer_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'},
};
# Invoice must debit the A/R ledger...
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'debit_ledger_id'}
= $newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'};
$credit_ledger_id = $newdb{'lookup'}{'charge_type'}{$row->{'ChargeDescription'}}{'ledger_id'};
# ...and credit the Invoice ledger.
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'credit_ledger_id'}
= $newdb{'lookup'}{'account'}{'Invoice'}{'ledger_id'};
# Create the invoice entry
# debit: A/R credit: Invoice
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'credit_ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'lease_id'},
'amount' => $row->{'InvoiceAmount'},
'comment' => "Invoice: Charge: $row->{'ChargeID'}" });
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
}
######################################################################
## Charges
$query = "SELECT * FROM Charges ORDER BY ChargeID";
foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'}
= $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'tx'};
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'}
= $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'customer_id'};
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'}
= $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'};
# Charge must credit the invoice ledger...
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'credit_ledger_id'}
= $newdb{'lookup'}{'charge_type'}{$row->{'ChargeDescription'}}{'ledger_id'};
# ...and debit the A/R ledger.
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'debit_ledger_id'}
= $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'credit_ledger_id'};
# Add the charge entry
# debit: Invoice credit: Rent/LateCharge/Etc
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'credit_ledger_id'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'},
'credit_ledger_id' => $credit_ledger_id,
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => $row->{'ChargeAmount'},
@@ -929,46 +892,23 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
# Reconcile the Invoice account. Our two entries look like:
# debit: Invoice credit: Rent/LateCharge/Etc
# debit: A/R credit: Invoice
# Since this is from the perspective of the Invoice account,
# the credit entry is the Invoice<->A/R, and the debit
# entry is the actual charge ledger entry.
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'},
'credit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'ledger_entry_id'},
'amount' => $row->{'ChargeAmount'},
});
next unless $row->{'TaxAmount'};
# Add the tax charge entry
# debit: Invoice credit: Tax
$credit_ledger_id = $newdb{'lookup'}{'charge_type'}{'Tax'}{'ledger_id'};
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'account'}{'Tax'}{'ledger_id'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'},
'credit_ledger_id' => $credit_ledger_id,
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => $row->{'TaxAmount'},
'comment' => "Tax for ChargeID:$row->{'ChargeID'}" });
'comment' => undef });
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tax_ledger_entry_id'}
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tax_entry'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
# Reconcile the Invoice account. Our two entries look like:
# debit: Invoice credit: Tax
# debit: A/R credit: Invoice
# Since this is from the perspective of the Invoice account,
# the credit entry is the Invoice<->A/R, and the debit
# entry is the actual tax ledger entry.
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tax_ledger_entry_id'},
'credit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'ledger_entry_id'},
'amount' => $row->{'TaxAmount'},
});
}
@@ -977,168 +917,42 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'receipt'} = {};
############################################################
############################################################
############################################################
# REVISIT <AP> 20090630
# Handling of receipts is all backwards. The way things
# _should_ look if someone provides Cash and Check to pay
# rent & tax for two units (50 on UnitA and 40 UnitB):
#
# RENT TAX INVOICE A/R RECEIPT CASH CHECK
# ------- ------- ------- ------- ------- ------- -------
# |50 | 50| | | | |
# | | 5 5| | | | |
# | | |55 55| | | |
# |40 | 40| | | | |
# | | 4 4| | | | |
# | | |44 44| | | |
# | | | | |79 | 79|
# | | | | |20 20| |
# | | | |99 99| | |
# | | | | | | |
#
# HOWEVER,
# Our current implementation MUST match LedgerEntry to
# LedgerEntry for reconcile purposes. Thus, although there
# is a way to reconcile that $50 was received, there is no
# way to flag the payment as being for UnitA, unless we
# either rely on the charge to determine the fact (a
# solution that has proven very messy), or we add it to
# the reconciliations table. The hope, for simplicity's
# sake, was to ensure there was a single ledger entry in
# A/R for each payment that could correspond to a lease/unit,
# so that no A/R ledger entry ever represented payment for
# more than one lease. However, to do so, our ledgers
# appear like this instead:
#
# RENT TAX INVOICE A/R RECEIPT CASH CHECK
# ------- ------- ------- ------- ------- ------- -------
# |50 | 50| | | | |
# | | 5 5| | | | |
# | | |55 55| | | |
# |40 | 40| | | | |
# | | 4 4| | | | |
# | | |44 44| | | |
# | | | | |79 | 79|
# | | | | |20 20| |
# | | | |50 50| | |
# | | | | 5 5| | |
# | | | |40 40| | |
# | | | | 4 4| | |
# | | | | | | |
#
# There is another possible solution, although it is
# very probably ledger overkill (even invoice/receipt
# already fall into the overkill category).
#
# RENT TAX INVOICE A/R MERGE RECEIPT CASH CHECK
# ------- ------- ------- ------- ------- ------- ------- -------
# |50 | 50| | | | | |
# | | 5 5| | | | | |
# | | |55 55| | | | |
# |40 | 40| | | | | |
# | | 4 4| | | | | |
# | | |44 44| | | | |
# | | | | | |79 | 79|
# | | | | | |20 20| |
# | | | | |50 50| | |
# | | | | | 5 5| | |
# | | | | |40 40| | |
# | | | | | 4 4| | |
# | | | |99 99| | | |
# | | | | | | | |
#
# I might opt for this last option, but ultimately, none
# of these are really correct. We need a better solution.
# Until then, I'll go with the easiest.
############################################################
############################################################
############################################################
# Sitelink splits one physical payment into multiple "payments" to match each charge.
# The solution here is kludgy, but for our cases at least, it brings those pseudo-payments
# back into a single one. This presumes there is only one PaymentType per receipt.
$query =
"SELECT R.ReceiptNum, R.ReceiptDate, P.PaymentType, P.CheckNum, SUM(P.PaymentAmount) AS ReceiptAmount" .
" FROM Receipts R, Payments P" .
"SELECT R.ReceiptNum, C.LedgerID, R.ReceiptDate" .
" FROM Receipts R, Payments P, Charges C" .
" WHERE P.ReceiptNum = R.ReceiptNum" .
" GROUP BY R.ReceiptNum, R.ReceiptDate, P.PaymentType, P.CheckNum" .
" ORDER BY R.ReceiptNum, P.PaymentType";
" AND C.ChargeID = P.ChargeID" .
" GROUP BY R.ReceiptNum, C.LedgerID, R.ReceiptDate" .
" ORDER BY R.ReceiptNum";
foreach $row (@{query($sdbh, $query)}) {
# if ($newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}) {
# next;
# }
if (!$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}) {
addRow('transactions',
{ 'stamp' => datefmt($row->{'ReceiptDate'}),
'through_date' => undef });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}
= {'tx' => $newdb{'tables'}{'transactions'}{'autoid'} };
}
if ($row->{'ReceiptDate'} =~ m%3/25/2009%) {
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}
= $newdb{'ids'}{'monetary_source'}{'Closing'};
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'account_name'}
= 'Bank';
}
else {
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}
= $newdb{'ids'}{'monetary_source'}{
$newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'name'}
};
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'account_name'}
= $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'account_name'};
if ($newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}) {
die unless ($newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'customer_id'}
== $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'customer_id'});
push(@{$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'ledgers'}},
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'ledger_id'});
#print Dumper $receipt_map{$row->{'ReceiptNum'}};
next;
}
# Set up a monetary source for the receipt,
if (!$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}) {
my $name = $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'name'};
if ($name eq 'Check') {
$name = 'Check #' . $row->{'CheckNum'};
}
addRow('monetary_sources',
{ 'monetary_type_id' => $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'monetary_type'}{'id'},
'name' => $name,
'comment' => "Receipt:$row->{'ReceiptNum'}; Payment:$row->{'PaymentType'}; Check:$row->{'CheckNum'}" });
addRow('transactions',
{ 'stamp' => datefmt($row->{'ReceiptDate'}),
'through_date' => undef });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}
= $newdb{'tables'}{'monetary_sources'}{'autoid'};
}
# Receipt must debit the "money" asset (bank, cash, check, etc)...
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'debit_ledger_id'}
= $newdb{'lookup'}{'account'}{
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'account_name'}
}{'ledger_id'};
# ...and credit the Receipt ledger
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'credit_ledger_id'}
= $newdb{'lookup'}{'account'}{'Receipt'}{'ledger_id'};
# NOTE THE ABOVE LARGE COMMENT BLOCK
# The choice of credit/debit ledgers does not mirror the
# choices for invoice. This _should_ be A/R to Receipt,
# but it is Money to Receipt instead.
# debit: Cash/Check/Etc credit: Receipt
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'credit_ledger_id'},
'amount' => $row->{'ReceiptAmount'},
'comment' => "Receipt: $row->{'ReceiptNum'}; " });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}
= {'tx' => $newdb{'tables'}{'transactions'}{'autoid'},
# NOTE: Use of 'lease_id' would be invalid, since the
# receipt could be for multiple leases. 'customer_id'
# could be OK, but better to avoid this issue all
# together by excluding them both from this lookup.
'ledgers' => [ $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'ledger_id'} ] };
}
# sub idkeys { [ sort( {$a <=> $b} keys(%{$_[0]})) ] }
# $Data::Dumper::Sortkeys = \&idkeys;
######################################################################
## Payments
@@ -1150,66 +964,86 @@ foreach $row (@{query($sdbh, $query)})
{
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}} = {};
# NOTE THE ABOVE LARGE COMMENT BLOCK
# The choice of credit/debit ledgers does not mirror the
# choices for charges. This _should_ be Money to Receipt,
# but it is A/R to Receipt instead.
if ($row->{'PaymentDate'} =~ m%3/25/2009%) {
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'monetary_source_id'}
= $newdb{'ids'}{'monetary_source'}{'Closing'};
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'account_name'}
= 'Bank';
}
else {
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'monetary_source_id'}
= $newdb{'ids'}{'monetary_source'}{
$newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'name'}
};
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'account_name'}
= $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'account_name'};
}
if (!$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}) {
if (!defined $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'monetary_source_id'}) {
my $name;
$name = $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'name'};
if ($name eq 'Check') {
$name = 'Check #' . $row->{'CheckNum'};
}
addRow('monetary_sources',
{ 'monetary_type_id' => $newdb{'lookup'}{'payment_type'}{$row->{'PaymentType'}}{'monetary_type'}{'id'},
'name' => $name,
'comment' => "Payment: $row->{'PaymentID'}; Type: $row->{'PaymentType'}; Check: $row->{'CheckNum'}; $row->{'Memo'}" });
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'monetary_source_id'}
= $newdb{'tables'}{'monetary_sources'}{'autoid'};
}
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}
= $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'monetary_source_id'};
}
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'}
= $newdb{'lookup'}{'account'}{$newdb{'lookup'}{'payment'}{
$row->{'PaymentID'}}{'account_name'}
}{'ledger_id'};
# Sitelink splits one physical payment into multiple "payments" to match each charge
# This is kludgy, but for our cases at least, brings those pseudo-payments back into
# a single one. It presumes that there is only one PaymentType per receipt.
if (!$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}) {
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
#'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => 0,
'comment' => "Receipt: $row->{'ReceiptNum'}; " });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
}
# Ensure Receipt has the right customer
$newdb{'tables'}{'ledger_entries'}{'rows'}[
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
]{'customer_id'} = $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'};
]{'amount'} += $row->{'PaymentAmount'};
# Payment must debit the associated receipt ledger (which should be Receipt)...
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'}
= $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'credit_ledger_id'};
# ...and credit the A/R ledger.
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'credit_ledger_id'}
= $newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'};
# Add the payment entry
# debit: Receipt credit: A/R
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'credit_ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => $row->{'PaymentAmount'},
'comment' => "Receipt: $row->{'ReceiptNum'}; Charge: $row->{'ChargeID'}; Payment: $row->{'PaymentID'}" });
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'};
# Reconcile the Receipt account. Our two entries look like:
# debit: Cash/Check/Etc credit: Receipt
# debit: Receipt credit: A/R
# Since this is from the perspective of the Receipt account,
# the debit entry is the Receipt<->A/R, and the credit
# entry is the actual receipt ledger entry.
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'},
'credit_ledger_entry_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'},
'amount' => $row->{'PaymentAmount'},
});
$newdb{'tables'}{'ledger_entries'}{'rows'}[
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
]{'comment'} .= 'P:'.$row->{'PaymentID'} . '-&gt;C:' . $row->{'ChargeID'} . '; ';
# OK, now that the receipt is reconciled, update
# payment to reference the true ledger_entry_id
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'}
= $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'};
# Figure out how much of the charge can be reconciled
my $reconcile_amount = $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'amount'};
#print STDERR Dumper($newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}); exit;
my $reconcile_amount = $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'amount'};
$reconcile_amount = $row->{'PaymentAmount'} if $row->{'PaymentAmount'} <= $reconcile_amount;
# Reconcile the A/R account. Our two entries look like:
# debit: Receipt credit: A/R
# debit: A/R credit: Invoice
# Since this is from the perspective of the A/R account,
# the debit entry is the Invoice<->A/R, and the credit
# entry is the Receipt<->A/R.
# Reconcile the A/R account. Since this is from the perspective
# of the A/R, charge is the debit, and payment is the credit
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'invoice'}{'ledger_entry_id'},
'credit_ledger_entry_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'},
{ 'type' => 'DEBIT',
'ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'},
'amount' => $reconcile_amount,
});
@@ -1229,83 +1063,83 @@ my %fake =
('customer_id' => 4,
'ledger_id' => 4,
'invoice' => [ { 'id' => 1000,
'date' => '2009-05-05',
'entry' => [ { 'id' => 2100,
'account_name' => 'Security Deposit',
'amount' => 10,
'tax' => 0 },
],
},
{ 'id' => 1001,
'date' => '2009-05-01',
'thru' => '2009-05-31',
'entry' => [ { 'id' => 2110,
'account_name' => 'Rent',
'amount' => 100,
'tax' => 5 },
],
},
{ 'id' => 1002,
'date' => '2009-05-11',
'entry' => [ { 'id' => 2120,
'account_name' => 'Late Charge',
'amount' => 25,
'tax' => 0 },
],
},
],
'date' => '2009-05-05',
'entry' => [ { 'id' => 2100,
'account_name' => 'Security Deposit',
'amount' => 10,
'tax' => 0 },
],
},
{ 'id' => 1001,
'date' => '2009-05-01',
'thru' => '2009-05-31',
'entry' => [ { 'id' => 2110,
'account_name' => 'Rent',
'amount' => 100,
'tax' => 5 },
],
},
{ 'id' => 1002,
'date' => '2009-05-11',
'entry' => [ { 'id' => 2120,
'account_name' => 'Late Charge',
'amount' => 25,
'tax' => 0 },
],
},
],
'receipt' => [ { 'id' => 2000,
'date' => '2009-05-15',
'entry' => [ { 'id' => 2200,
'track' => [ { 'debit'=>2100, 'amount'=>10 },
{ 'debit'=>2110, 'amount'=>5 } ],
'type' => 1,
'amount' => 15 },
{ 'id' => 2201,
'track' => [ { 'debit'=>2110, 'amount'=>10 } ],
'type' => 2,
'amount' => 10 },
{ 'id' => 2202,
'track' => [ { 'debit'=>2110, 'amount'=>5 } ],
'type' => 3,
'amount' => 5 },
],
},
{ 'id' => 2001,
'date' => '2009-05-18',
'entry' => [ { 'id' => 2210,
'track' => [ { 'debit'=>2110, 'amount'=>30 } ],
'type' => 5,
'amount' => 30 },
{ 'id' => 2211,
'track' => [ { 'debit'=>2110, 'amount'=>20 } ],
'type' => 6,
'amount' => 20 },
],
},
{ 'id' => 2002,
'date' => '2009-05-22',
'entry' => [ { 'id' => 2220,
'track' => [ { 'debit'=>2110, 'amount'=>10 } ],
'type' => 1,
'amount' => 10 },
{ 'id' => 2221,
'track' => [ { 'debit'=>2110, 'amount'=>5 } ],
'type' => 2,
'amount' => 5 },
{ 'id' => 2222,
'track' => [ { 'debit'=>2110, 'amount'=>15 },
{ 'debit'=>2111, 'amount'=>5 },
{ 'debit'=>2120, 'amount'=>5 } ],
'type' => 7,
'amount' => 25 },
{ 'id' => 2223,
'track' => [ { 'debit'=>2120, 'amount'=>20 } ],
'type' => 8,
'amount' => 30 },
],
},
],
'date' => '2009-05-15',
'entry' => [ { 'id' => 2200,
'track' => [ { 'debit'=>2100, 'amount'=>10 },
{ 'debit'=>2110, 'amount'=>5 } ],
'type' => 1,
'amount' => 15 },
{ 'id' => 2201,
'track' => [ { 'debit'=>2110, 'amount'=>10 } ],
'type' => 2,
'amount' => 10 },
{ 'id' => 2202,
'track' => [ { 'debit'=>2110, 'amount'=>5 } ],
'type' => 3,
'amount' => 5 },
],
},
{ 'id' => 2001,
'date' => '2009-05-18',
'entry' => [ { 'id' => 2210,
'track' => [ { 'debit'=>2110, 'amount'=>30 } ],
'type' => 5,
'amount' => 30 },
{ 'id' => 2211,
'track' => [ { 'debit'=>2110, 'amount'=>20 } ],
'type' => 6,
'amount' => 20 },
],
},
{ 'id' => 2002,
'date' => '2009-05-22',
'entry' => [ { 'id' => 2220,
'track' => [ { 'debit'=>2110, 'amount'=>10 } ],
'type' => 1,
'amount' => 10 },
{ 'id' => 2221,
'track' => [ { 'debit'=>2110, 'amount'=>5 } ],
'type' => 2,
'amount' => 5 },
{ 'id' => 2222,
'track' => [ { 'debit'=>2110, 'amount'=>15 },
{ 'debit'=>2111, 'amount'=>5 },
{ 'debit'=>2120, 'amount'=>5 } ],
'type' => 7,
'amount' => 25 },
{ 'id' => 2223,
'track' => [ { 'debit'=>2120, 'amount'=>20 } ],
'type' => 8,
'amount' => 30 },
],
},
],
);
@@ -1332,7 +1166,7 @@ sub fakeTesting {
}
addRow('transactions',
{ 'stamp' => '2009-04-30' });
{ 'stamp' => '2009-05-10' });
addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
@@ -1359,10 +1193,10 @@ sub fakeTesting {
1);
foreach my $e (@{$tx->{'entry'}}) {
my $ircrdr = ($ir eq 'invoice') ? 'Invoice' : 'Receipt';
my $crdr = ($ir eq 'invoice') ? 'Invoice' : 'Receipt';
my $dr = ($ir eq 'invoice') ? 'A/R' : 'Cash';
$crdr = $dr;
my $cr = ($ir eq 'invoice') ? $e->{'account_name'} : 'A/R';
my $crdr;
my $monetary_source_id;
if (defined $e->{'type'}) {
@@ -1376,87 +1210,64 @@ sub fakeTesting {
$monetary_source_id = $newdb{'ids'}{'monetary_source'}{'internal'};
}
$crdr = $dr;
if ($use_ir) {
$crdr = $ircrdr;
addRow('ledger_entries',
{ 'id' => $e->{'id'}+10000,
'monetary_source_id' => ($ir eq 'invoice' ? undef : $monetary_source_id),
'transaction_id' => $tx->{'id'},
'debit_ledger_id' => $newdb{'lookup'}{'account'}{$dr}{'ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
'customer_id' => $fake{'customer_id'},
#'lease_id' => $fake{'lease_id'},
'amount' => $e->{'amount'},
'comment' => "Fake $ir entry" },
1);
}
addRow('ledger_entries',
{ 'id' => $e->{'id'},
'monetary_source_id' => ($ir eq 'invoice' ? $monetary_source_id : undef),
'monetary_source_id' => $monetary_source_id,
'transaction_id' => $tx->{'id'},
'debit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'account'}{$cr}{'ledger_id'},
'customer_id' => $fake{'customer_id'},
'lease_id' => $fake{'lease_id'},
'amount' => $e->{'amount'},
'comment' => "Fake Entry" },
'comment' => "Fake $ir entry" },
1);
if ($use_ir) {
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $e->{'id'} + ($ir eq 'invoice' ? 10000 : 0),
'credit_ledger_entry_id' => $e->{'id'} + ($ir eq 'invoice' ? 0 : 10000),
'amount' => $e->{'amount'},
});
}
# addRow('ledger_entries',
# { 'id' => $e->{'id'},
# 'monetary_source_id' => $monetary_source_id,
# 'transaction_id' => $tx->{'id'},
# 'debit_ledger_id' => $newdb{'lookup'}{'account'}{$dr}{'ledger_id'},
# 'credit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
# 'customer_id' => $fake{'customer_id'},
# 'lease_id' => $fake{'lease_id'},
# 'amount' => $e->{'amount'},
# 'comment' => "Fake $ir entry" },
# 1);
foreach my $t (@{$e->{'track'}}) {
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $t->{'debit'},
'credit_ledger_entry_id' => $e->{'id'},
{ 'type' => 'DEBIT',
'ledger_entry_id' => $t->{'debit'},
'transaction_id' => $tx->{'id'},
'amount' => $t->{'amount'}
});
}
next unless $e->{'tax'};
$crdr = $dr;
if ($use_ir) {
$crdr = $ircrdr;
addRow('ledger_entries',
{ 'id' => $e->{'id'}+10001,
'monetary_source_id' => ($ir eq 'invoice' ? undef : $monetary_source_id),
'transaction_id' => $tx->{'id'},
'debit_ledger_id' => $newdb{'lookup'}{'account'}{$dr}{'ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
'customer_id' => $fake{'customer_id'},
#'lease_id' => $fake{'lease_id'},
'amount' => $e->{'tax'},
'comment' => "Fake Tax Invoice Entry" },
1);
}
addRow('ledger_entries',
{ 'id' => $e->{'id'}+1,
'monetary_source_id' => ($ir eq 'invoice' ? $monetary_source_id : undef),
'monetary_source_id' => $monetary_source_id,
'transaction_id' => $tx->{'id'},
'debit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'account'}{'Tax'}{'ledger_id'},
'customer_id' => $fake{'customer_id'},
'lease_id' => $fake{'lease_id'},
'amount' => $e->{'tax'},
'comment' => "Fake Tax Entry" },
'amount' => $e->{'amount'},
'comment' => "Fake Tax" },
1);
if ($use_ir) {
addRow('reconciliations',
{ 'debit_ledger_entry_id' => $e->{'id'} + ($ir eq 'invoice' ? 10001 : 1),
'credit_ledger_entry_id' => $e->{'id'} + ($ir eq 'invoice' ? 1 : 10001),
'amount' => $e->{'tax'},
});
}
# addRow('ledger_entries',
# { 'id' => $e->{'id'}+1,
# 'monetary_source_id' => $monetary_source_id,
# 'transaction_id' => $tx->{'id'},
# 'debit_ledger_id' => $newdb{'lookup'}{'account'}{$dr}{'ledger_id'},
# 'credit_ledger_id' => $newdb{'lookup'}{'account'}{$crdr}{'ledger_id'},
# 'customer_id' => $fake{'customer_id'},
# 'lease_id' => $fake{'lease_id'},
# 'amount' => $e->{'tax'},
# 'comment' => "Fake Tax" },
# 1);
}
}
}

View File

@@ -33,7 +33,7 @@ class LedgerEntriesController extends AppController {
}
}
function jqGridDataTables(&$params, &$model) {
function jqGridDataCountTables(&$params, &$model) {
$link =
array(// Models
'Transaction' =>
@@ -95,8 +95,13 @@ class LedgerEntriesController extends AppController {
);
}
if (isset($params['custom']['account_id'])) {
$account_id = $params['custom']['account_id'];
if (isset($params['custom']['account_id']) || isset($params['custom']['lease_id'])) {
if (isset($params['custom']['account_id']))
$account_id = $params['custom']['account_id'];
else
$account_id =
$this->LedgerEntry->DebitLedger->Account->accountReceivableAccountID();
$link['Ledger'] =
array('fields' => array('id', 'sequence'),
'conditions' => ("Ledger.id = IF(DebitLedger.account_id = $account_id," .
@@ -108,18 +113,57 @@ class LedgerEntriesController extends AppController {
);
}
if (isset($params['custom']['lease_id'])) {
$account_id = $params['custom']['lease_id'];
$link['Transaction']['ReconciledLedgerEntry'] =
array('fields' => array('id', 'Reconciliation.amount', 'Reconciliation.type'),
);
}
if (isset($params['custom']['reconcile_id'])) {
$ftype = $params['custom']['account_ftype'];
$ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype);
$ftype = ucfirst($ftype);
$link[$ftype.'ReconciliationLedgerEntry'] =
array('fields' => array('Reconciliation.amount'));
$link['ReconcilingTransaction'] =
array('fields' => array('Reconciliation.amount'),
'conditions' => array('Reconciliation.type' => $ftype),
);
}
return array('link' => $link);
}
function jqGridDataTables(&$params, &$model) {
return $this->jqGridDataCountTables($params, $model);
}
function jqGridDataFields(&$params, &$model) {
if (isset($params['custom']['lease_id'])) {
$account_id =
$this->LedgerEntry->DebitLedger->Account->accountReceivableAccountID();
$fields = array('id', 'name', 'comment', 'amount');
$fields[] = ("IF(DebitLedger.account_id = $account_id," .
" SUM(IF(ReconciledLedgerEntry.amount IS NULL," .
" LedgerEntry.amount," .
" ReconciledLedgerEntry.amount))," .
" NULL) AS debit");
$fields[] = ("IF(CreditLedger.account_id = $account_id," .
" SUM(IF(ReconciledLedgerEntry.amount IS NULL," .
" LedgerEntry.amount," .
" ReconciledLedgerEntry.amount))," .
" NULL) AS credit");
$Account = new Account();
$account_ftype = ucfirst($Account->fundamentalType($account_id));
$fields[] = ("(IF({$account_ftype}Ledger.account_id = $account_id, 1, -1)" .
" * SUM(IF(ReconciledLedgerEntry.amount IS NULL," .
" LedgerEntry.amount," .
" ReconciledLedgerEntry.amount)))" .
" AS balance");
return $fields;
}
$ledger_id = (isset($params['custom']['ledger_id'])
? $params['custom']['ledger_id']
: null);
@@ -143,60 +187,39 @@ class LedgerEntriesController extends AppController {
$conditions = parent::jqGridDataConditions($params, $model);
if ($params['action'] === 'ledger') {
if ($params['action'] === 'ledger' && isset($ledger_id)) {
$conditions[] = $model->ledgerContextConditions($ledger_id, $account_type);
}
if (isset($params['custom']['reconcile_id'])) {
$ftype = $params['custom']['account_ftype'];
//$ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype);
$conditions[] = array('Reconciliation.'.$ftype.'_ledger_entry_id' => $params['custom']['reconcile_id']);
//$link['ReconcilingTransaction']['conditions'][] = array('Reconciliation.type' => $ftype);
$conditions[] = array('Reconciliation.ledger_entry_id' => $params['custom']['reconcile_id']);
}
if (isset($params['custom']['account_id'])) {
$conditions[] =
array('OR' =>
array('OR' =>
array(array('CreditAccount.id' => $params['custom']['account_id']),
array('DebitAccount.id' => $params['custom']['account_id'])));
/* $conditions[] = */
/* array('Account.id' => $params['custom']['account_id']); */
}
if (isset($params['custom']['customer_id'])) {
$conditions[] =
array('Customer.id' => $params['custom']['customer_id']);
/* $Account = new Account(); */
/* if (isset($params['custom']['account_ftype']) || */
/* isset($params['custom']['ledger_id'])) { */
/* $conditions[] = */
/* array('OR' => array('Account.id' => $Account->invoiceAccountID(), */
/* 'Account.id' => $Account->receiptAccountID())); */
/* } else { */
/* $conditions[] = */
/* array('OR' => array('DebitAccount.id' => $Account->invoiceAccountID(), */
/* //'CreditAccount.id' => $Account->invoiceAccountID(), */
/* //'DebitAccount.id' => $Account->receiptAccountID(), */
/* 'CreditAccount.id' => $Account->receiptAccountID(), */
/* )); */
/* } */
}
if (isset($params['custom']['lease_id'])) {
$conditions[] =
array('Lease.id' => $params['custom']['lease_id']);
/* $Account = new Account(); */
/* if (isset($params['custom']['account_ftype']) || */
/* isset($params['custom']['ledger_id'])) { */
/* $conditions[] = */
/* array('OR' => array('Account.id' => $Account->invoiceAccountID(), */
/* 'Account.id' => $Account->receiptAccountID())); */
/* } else { */
/* $conditions[] = */
/* array('OR' => array('DebitAccount.id' => $Account->invoiceAccountID(), */
/* //'CreditAccount.id' => $Account->invoiceAccountID(), */
/* //'DebitAccount.id' => $Account->receiptAccountID(), */
/* 'CreditAccount.id' => $Account->receiptAccountID(), */
/* )); */
/* } */
array('OR' => array
(array('Lease.id' => $params['custom']['lease_id']),
array('ReconciledLedgerEntry.lease_id' => $params['custom']['lease_id']),
));
}
if (isset($params['custom']['transaction_id'])) {
@@ -334,8 +357,8 @@ class LedgerEntriesController extends AppController {
$stats['credit_amount_remaining'] = $entry['LedgerEntry']['amount'] - $stats['credit_amount_reconciled'];
//pr($stats);
$reconciled = $this->LedgerEntry->findReconciledLedgerEntries($id);
//pr($reconciled);
$reconciled = $this->LedgerEntry->findReconcilingTransactions($id);
//pr(compact('reconciled'));
// Prepare to render.
$title = "Ledger Entry #{$entry['LedgerEntry']['id']}";

View File

@@ -41,6 +41,43 @@ class TransactionsController extends AppController {
* to jqGrid.
*/
function jqGridDataSetup(&$params) {
parent::jqGridDataSetup($params);
}
function jqGridDataTables(&$params, &$model) {
$link = array();
if (isset($params['custom']['reconcile_ledger_entry_id'])) {
$ftype = $params['custom']['reconcile_type'];
//$ftype = $this->Transaction->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype);
$link['ReconciledLedgerEntry'] =
array('fields' => array('Reconciliation.amount'),
'conditions' => array('Reconciliation.type' => $ftype)
);
}
return array('link' => $link);
}
function jqGridDataFields(&$params, &$model) {
return parent::jqGridDataFields($params, $model);
}
function jqGridDataConditions(&$params, &$model) {
$conditions = parent::jqGridDataConditions($params, $model);
if (isset($params['custom']['reconcile_ledger_entry_id'])) {
/* $ftype = $params['custom']['reconcile_type']; */
/* $ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype); */
/* $conditions[] = array('Reconciliation.type' => $ftype); */
$conditions[] = array('Reconciliation.ledger_entry_id'
=> $params['custom']['reconcile_ledger_entry_id']);
}
return $conditions;
}
function jqGridRecordLinks(&$params, &$model, &$records, $links) {
$links['Transaction'] = array('id');
return parent::jqGridRecordLinks($params, $model, $records, $links);

View File

@@ -226,20 +226,20 @@ class Account extends AppModel {
? array($fundamental_type)
: array('debit', 'credit')) AS $fund) {
$ucfund = ucfirst($fund);
$unreconciled[$fund]['entry'] = $this->find
$unreconciled[$fund]['LedgerEntry'] = $this->find
('all', array
('link' => array
('Ledger' => array
('fields' => array(),
"LedgerEntry" => array
'LedgerEntry' => array
('class' => "{$ucfund}LedgerEntry",
'fields' => array('id', 'amount'),
"ReconciliationLedgerEntry" => array
('class' => "{$ucfund}ReconciliationLedgerEntry",
'fields' => array
'ReconcilingTransaction' => array
('fields' => array
("COALESCE(SUM(Reconciliation.amount),0) AS 'reconciled'",
"LedgerEntry.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'",
),
'conditions' => array('Reconciliation.type' => $fund),
),
),
),
@@ -251,7 +251,7 @@ class Account extends AppModel {
'fields' => array(),
));
$balance = 0;
foreach ($unreconciled[$fund]['entry'] AS &$entry) {
foreach ($unreconciled[$fund]['LedgerEntry'] AS &$entry) {
$entry = array_merge(array_diff_key($entry["LedgerEntry"], array(0=>true)),
$entry[0]);
$balance += $entry['balance'];
@@ -279,7 +279,7 @@ class Account extends AppModel {
function reconcileNewLedgerEntry($id, $fundamental_type, $amount, $cond = null) {
$ofund = $this->fundamentalOpposite($fundamental_type);
$unreconciled = array($ofund => array('entry'=>array(), 'balance'=>0));
$unreconciled = array($ofund => array('LedgerEntry'=>array(), 'balance'=>0));
$applied = 0;
// if there is no money in the entry, it can reconcile nothing
@@ -287,14 +287,14 @@ class Account extends AppModel {
if ($amount > 0) {
$unreconciled = $this->findUnreconciledLedgerEntries($id, $ofund, $cond);
foreach ($unreconciled[$ofund]['entry'] AS $i => &$entry) {
foreach ($unreconciled[$ofund]['LedgerEntry'] AS $i => &$entry) {
// Determine if amount is sufficient to cover the entry
if ($amount > $entry['balance'])
$apply = $entry['balance'];
elseif ($amount > 0)
$apply = $amount;
else {
unset($unreconciled[$ofund]['entry'][$i]);
unset($unreconciled[$ofund]['LedgerEntry'][$i]);
continue;
}

View File

@@ -85,6 +85,28 @@ class LinkableBehavior extends ModelBehavior {
protected $_defaults = array('type' => 'LEFT');
function pr($lev, $mixed) {
if ($lev >= 5)
return;
pr($mixed);
return;
$trace = debug_backtrace(false);
//array_shift($trace);
$calls = array();
foreach ($trace AS $call) {
$call = array_intersect_key($call,
array('file'=>1,
'line'=>1,
//'class'=>1,
'function'=>1,
));
$calls[] = implode("; ", $call);
}
pr(array('debug' => $mixed, 'stack' => $calls));
}
/*
* This is a function for made recursive str_replaces in an array
* NOTE: The palacement of this function is terrible, but I don't
@@ -108,7 +130,10 @@ class LinkableBehavior extends ModelBehavior {
}
public function beforeFind(&$Model, $query) {
/* pr("Linkable::beforeFind() begin"); pr($query); */
$this->pr(10,
array('function' => 'Linkable::beforeFind',
'args' => array('Model->alias' => '$Model->alias') + compact('query'),
));
if (isset($query[$this->_key])) {
$optionsDefaults = $this->_defaults + array('reference' =>
array('class' => $Model->alias,
@@ -132,7 +157,10 @@ class LinkableBehavior extends ModelBehavior {
unset($iterator['defaults']);
}
$iterations = Set::normalize($iterator);
/* pr(array('checkpoint' => 'Iterations', compact('iterations'))); */
$this->pr(25,
array('checkpoint' => 'Iterations',
compact('iterations'),
));
foreach ($iterations as $alias => $options) {
if (is_null($options)) {
$options = array();
@@ -145,7 +173,15 @@ class LinkableBehavior extends ModelBehavior {
if (empty($options['class']))
$options['class'] = $alias;
/* pr(array('checkpoint' => 'Begin Model Work', compact('alias', 'options'))); */
if (!isset($options['conditions']))
$options['conditions'] = array();
elseif (!is_array($options['conditions']))
$options['conditions'] = array($options['conditions']);
$this->pr(20,
array('checkpoint' => 'Begin Model Work',
compact('alias', 'options'),
));
$modelClass = $options['class'];
$modelAlias = $options['alias'];
@@ -154,11 +190,13 @@ class LinkableBehavior extends ModelBehavior {
$_Model =& ClassRegistry::init($modelClass); // the incoming model to be linked in query
$Reference =& ClassRegistry::init($referenceClass); // the already in query model that links to $_Model
/* pr(array('checkpoint' => 'Aliases Established', */
/* 'Model' => ($modelAlias .' : '. $modelClass . */
/* ' ('. $_Model->alias .' : '. $_Model->name .')'), */
/* 'Reference' => ($referenceAlias .' : '. $referenceClass . */
/* ' ('. $Reference->alias .' : '. $Reference->name .')'))); */
$this->pr(12,
array('checkpoint' => 'Aliases Established',
'Model' => ($modelAlias .' : '. $modelClass .
' ('. $_Model->alias .' : '. $_Model->name .')'),
'Reference' => ($referenceAlias .' : '. $referenceClass .
' ('. $Reference->alias .' : '. $Reference->name .')'),
));
$db =& $_Model->getDataSource();
@@ -169,20 +207,20 @@ class LinkableBehavior extends ModelBehavior {
// a relationship if one doesn't otherwise already exists.
if (($associations = $Reference->getAssociated()) &&
isset($associations[$_Model->alias])) {
/* pr("Reference defines association to _Model"); */
$this->pr(12, array('checkpoint' => "Reference defines association to _Model"));
$associatedThroughReference = 1;
$type = $associations[$_Model->alias];
$association = $Reference->{$type}[$_Model->alias];
}
elseif (($associations = $_Model->getAssociated()) &&
isset($associations[$Reference->alias])) {
/* pr("_Model defines association to Reference"); */
$this->pr(12, array('checkpoint' => "_Model defines association to Reference"));
$type = $associations[$Reference->alias];
$association = $_Model->{$type}[$Reference->alias];
}
else {
// No relationship... make our best effort to create one.
/* pr("No assocation between _Model and Reference"); */
$this->pr(12, array('checkpoint' => "No assocation between _Model and Reference"));
$type = 'belongsTo';
$_Model->bind($Reference->alias);
// Grab the association now, since we'll unbind in a moment.
@@ -212,93 +250,119 @@ class LinkableBehavior extends ModelBehavior {
$associationAlias,
$association['conditions']);
/* pr(array('checkpoint' => 'Models Established - Check Associations', */
/* 'primaryModel' => $primaryAlias .' : '. $primaryModel->name, */
/* 'foreignModel' => $foreignAlias .' : '. $foreignModel->name, */
/* compact('type', 'association'))); */
$this->pr(15,
array('checkpoint' => 'Models Established - Check Associations',
'primaryModel' => $primaryAlias .' : '. $primaryModel->name,
'foreignModel' => $foreignAlias .' : '. $foreignModel->name,
compact('type', 'association'),
));
if (empty($options['conditions'])) {
if ($type === 'hasAndBelongsToMany') {
if (isset($association['with']))
$linkClass = $association['with'];
else
$linkClass = Inflector::classify($association['joinTable']);
if ($type === 'hasAndBelongsToMany') {
if (isset($association['with']))
$linkClass = $association['with'];
else
$linkClass = Inflector::classify($association['joinTable']);
$Link =& $_Model->{$linkClass};
$Link =& $_Model->{$linkClass};
if (isset($options['linkalias']))
$linkAlias = $options['linkalias'];
else
$linkAlias = $Link->alias;
if (isset($options['linkalias']))
$linkAlias = $options['linkalias'];
else
$linkAlias = $Link->alias;
// Get the foreign key fields (for the link table) directly from
// the defined model associations, if they exists. This is the
// users direct specification, and therefore definitive if present.
$modelLink = $Link->escapeField($association['foreignKey'], $linkAlias);
$referenceLink = $Link->escapeField($association['associationForeignKey'], $linkAlias);
$this->pr(17,
array('checkpoint' => 'Linking HABTM',
compact('linkClass', 'linkAlias'),
));
// If we haven't figured out the foreign keys, see if there is a
// model for the link table, and if it has the appropriate
// associations with the two tables we're trying to join.
if (empty($modelLink) && isset($Link->belongsTo[$_Model->alias]))
$modelLink = $Link->escapeField($Link->belongsTo[$_Model->alias]['foreignKey'], $linkAlias);
if (empty($referenceLink) && isset($Link->belongsTo[$Reference->alias]))
$referenceLink = $Link->escapeField($Link->belongsTo[$Reference->alias]['foreignKey'], $linkAlias);
// Get the foreign key fields (for the link table) directly from
// the defined model associations, if they exists. This is the
// users direct specification, and therefore definitive if present.
$modelLink = $Link->escapeField($association['foreignKey'], $linkAlias);
$referenceLink = $Link->escapeField($association['associationForeignKey'], $linkAlias);
// We're running quite thin here. None of the models spell
// out the appropriate linkages. We'll have to SWAG it.
if (empty($modelLink))
$modelLink = $Link->escapeField(Inflector::underscore($_Model->alias) . '_id', $linkAlias);
if (empty($referenceLink))
$referenceLink = $Link->escapeField(Inflector::underscore($Reference->alias) . '_id', $linkAlias);
// If we haven't figured out the foreign keys, see if there is a
// model for the link table, and if it has the appropriate
// associations with the two tables we're trying to join.
if (empty($modelLink) && isset($Link->belongsTo[$_Model->alias]))
$modelLink = $Link->escapeField($Link->belongsTo[$_Model->alias]['foreignKey'], $linkAlias);
if (empty($referenceLink) && isset($Link->belongsTo[$Reference->alias]))
$referenceLink = $Link->escapeField($Link->belongsTo[$Reference->alias]['foreignKey'], $linkAlias);
// Get the primary key from the tables we're joining.
$referenceKey = $Reference->escapeField(null, $referenceAlias);
$modelKey = $_Model->escapeField(null, $modelAlias);
// We're running quite thin here. None of the models spell
// out the appropriate linkages. We'll have to SWAG it.
if (empty($modelLink))
$modelLink = $Link->escapeField(Inflector::underscore($_Model->alias) . '_id', $linkAlias);
if (empty($referenceLink))
$referenceLink = $Link->escapeField(Inflector::underscore($Reference->alias) . '_id', $linkAlias);
// Get the primary key from the tables we're joining.
$referenceKey = $Reference->escapeField(null, $referenceAlias);
$modelKey = $_Model->escapeField(null, $modelAlias);
// Join the linkage table to our model. We'll use an inner join,
// as the whole purpose of the linkage table is to make this
// connection. As we are embedding this join, the INNER will not
// cause any problem with the overall query, should the user not
// be concerned with whether or not the join has any results.
// They control that with the 'type' parameter which will be at
// the top level join.
$options['joins'][] = array('type' => 'INNER',
'alias' => $modelAlias,
'conditions' => "{$modelKey} = {$modelLink}",
'table' => $db->fullTableName($_Model, true));
// Now for the top level join. This will be added into the list
// of joins down below, outside of the HABTM specific code.
$options['class'] = $linkClass;
$options['alias'] = $linkAlias;
$options['table'] = $Link->getDataSource()->fullTableName($Link);
$options['conditions'][] = "{$referenceLink} = {$referenceKey}";
}
elseif (isset($association['foreignKey']) && $association['foreignKey']) {
$foreignKey = $primaryModel->escapeField($association['foreignKey'], $primaryAlias);
$primaryKey = $foreignModel->escapeField($foreignModel->primaryKey, $foreignAlias);
// Only differentiating to help show the logical flow.
// Either way works and this test can be tossed out
if (($type === 'hasMany' || $type === 'hasOne') ^ $associatedThroughReference)
$options['conditions'][] = "{$primaryKey} = {$foreignKey}";
else
$options['conditions'][] = "{$foreignKey} = {$primaryKey}";
}
else {
// No Foreign Key... nothing we can do.
$options['conditions'] = array();
}
// The user may have specified conditions directly in the model
// for this join. Make sure to adhere to those conditions.
if (isset($association['conditions']) && is_array($association['conditions']))
$options['conditions'] = array_merge($options['conditions'], $association['conditions']);
elseif (!empty($association['conditions']))
$options['conditions'][] = $association['conditions'];
// Join the linkage table to our model. We'll use an inner join,
// as the whole purpose of the linkage table is to make this
// connection. As we are embedding this join, the INNER will not
// cause any problem with the overall query, should the user not
// be concerned with whether or not the join has any results.
// They control that with the 'type' parameter which will be at
// the top level join.
$options['joins'][] = array('type' => 'INNER',
'alias' => $modelAlias,
'conditions' => "{$modelKey} = {$modelLink}",
'table' => $db->fullTableName($_Model, true));
// Now for the top level join. This will be added into the list
// of joins down below, outside of the HABTM specific code.
$options['class'] = $linkClass;
$options['alias'] = $linkAlias;
$options['table'] = $Link->getDataSource()->fullTableName($Link);
$options['conditions'][] = "{$referenceLink} = {$referenceKey}";
}
elseif (isset($association['foreignKey']) && $association['foreignKey']) {
$foreignKey = $primaryModel->escapeField($association['foreignKey'], $primaryAlias);
$primaryKey = $foreignModel->escapeField($foreignModel->primaryKey, $foreignAlias);
$this->pr(17,
array('checkpoint' => 'Linking due to foreignKey',
compact('foreignKey', 'primaryKey'),
));
// Only differentiating to help show the logical flow.
// Either way works and this test can be tossed out
if (($type === 'hasMany' || $type === 'hasOne') ^ $associatedThroughReference)
$options['conditions'][] = "{$primaryKey} = {$foreignKey}";
else
$options['conditions'][] = "{$foreignKey} = {$primaryKey}";
}
else {
$this->pr(17,
array('checkpoint' => 'Linking with no logic (expecting user defined)',
));
// No Foreign Key... nothing we can do.
}
$this->pr(19,
array('checkpoint' => 'Conditions',
array('options[conditions]' => $options['conditions'],
'association[conditions]' => $association['conditions'],
),
));
// The user may have specified conditions directly in the model
// for this join. Make sure to adhere to those conditions.
if (isset($association['conditions']) && is_array($association['conditions']))
$options['conditions'] = array_merge($options['conditions'], $association['conditions']);
elseif (!empty($association['conditions']))
$options['conditions'][] = $association['conditions'];
$this->pr(19,
array('checkpoint' => 'Conditions2',
array('options[conditions]' => $options['conditions'],
),
));
if (empty($options['table'])) {
$options['table'] = $db->fullTableName($_Model, true);
}
@@ -312,26 +376,31 @@ class LinkableBehavior extends ModelBehavior {
(empty($association['fields'])
? array() : $db->fields($_Model, $modelAlias, $association['fields'])));
/* pr(array('checkpoint' => 'Model Work Complete', compact('options', 'modelClass', 'modelAlias'))); */
$options[$this->_key] = am($options[$this->_key], array_diff_key($options, $optionsKeys));
$options = array_intersect_key($options, $optionsKeys);
if (!empty($options[$this->_key])) {
$iterators[] = $options[$this->_key] +
array('defaults' =>
array_merge($defaults,
array_merge($defaults,
array('reference' =>
array('class' => $modelClass,
'alias' => $modelAlias))));
}
$query['joins'][] = array_intersect_key($options, array('type' => true, 'alias' => true, 'table' => true, 'joins' => true, 'conditions' => true));
$this->pr(19,
array('checkpoint' => 'Model Join Complete',
compact('options', 'modelClass', 'modelAlias', 'query'),
));
}
++$cont;
$notDone = isset($iterators[$cont]);
} while ($notDone);
}
/* pr(array('checkpoint' => 'Linkable::beforeFind() end', */
/* compact('query'))); */
$this->pr(20,
array('function' => 'Linkable::beforeFind',
'return' => compact('query'),
));
return $query;
}
}

View File

@@ -147,7 +147,11 @@ class Lease extends AppModel {
return null;
$stats = $this->Account->stats($this->Account->accountReceivableAccountID(), true,
array('LedgerEntry.lease_id' => $id));
array('OR' => array
(array('LedgerEntry.lease_id' => $id),
array('ReconciledLedgerEntry.lease_id' => $id),
),
));
// Pull to the top level and return
$stats = $stats['Ledger'];

View File

@@ -25,17 +25,11 @@ class LedgerEntry extends AppModel {
);
var $hasAndBelongsToMany = array(
'DebitReconciliationLedgerEntry' => array(
'className' => 'LedgerEntry',
'ReconcilingTransaction' => array(
'className' => 'Transaction',
'joinTable' => 'reconciliations',
'foreignKey' => 'credit_ledger_entry_id',
'associationForeignKey' => 'debit_ledger_entry_id',
),
'CreditReconciliationLedgerEntry' => array(
'className' => 'LedgerEntry',
'joinTable' => 'reconciliations',
'foreignKey' => 'debit_ledger_entry_id',
'associationForeignKey' => 'credit_ledger_entry_id',
'foreignKey' => 'transaction_id',
'associationForeignKey' => 'ledger_entry_id',
),
);
@@ -167,36 +161,36 @@ class LedgerEntry extends AppModel {
/**************************************************************************
**************************************************************************
**************************************************************************
* function: findReconciledLedgerEntries
* - Returns ledger entries that are reconciled to the given entry.
* (such as payments towards a charge).
* function: findReconcilingTransactions
* - Returns transactions that reconcile the given entry
* (such as receipts that reconcile a charge).
*/
function findReconciledLedgerEntries($id = null, $fundamental_type = null) {
function findReconcilingTransactions($id = null, $fundamental_type = null) {
foreach (($fundamental_type
? array($fundamental_type)
: array('debit', 'credit')) AS $fund) {
$ucfund = ucfirst($fund);
$reconciled[$fund]['entry'] = $this->find
$reconciled[$fund]['LedgerEntry'] = $this->find
('all', array
('link' => array
("ReconciliationLedgerEntry" => array
('class' => "{$ucfund}ReconciliationLedgerEntry",
'fields' => array
('ReconcilingTransaction' => array
('fields' => array
('id',
"COALESCE(SUM(Reconciliation.amount),0) AS 'reconciled'",
"LedgerEntry.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'",
//"ReconcilingTransaction.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'",
"COALESCE(7) AS 'balance'",
),
'conditions' => array('Reconciliation.type' => $fund),
),
),
'group' => ("ReconciliationLedgerEntry.id"),
'group' => ('ReconcilingTransaction.id'),
'conditions' => array('LedgerEntry.id' => $id),
'fields' => array(),
));
//pr($reconciled);
$balance = 0;
foreach ($reconciled[$fund]['entry'] AS &$entry) {
$entry = array_merge($entry["ReconciliationLedgerEntry"], $entry[0]);
foreach ($reconciled[$fund]['LedgerEntry'] AS &$entry) {
$entry = array_merge($entry["ReconcilingTransaction"], $entry[0]);
$balance += $entry['balance'];
}
$reconciled[$fund]['balance'] = $balance;
@@ -212,27 +206,31 @@ class LedgerEntry extends AppModel {
* function: stats
* - Returns summary data from the requested ledger entry
*/
function stats($id) {
function stats($id, $cond = null) {
if (!isset($cond))
$cond = array();
$cond[] = array('LedgerEntry.id' => $id);
$query = array
(
'link' => array('ReconcilingTransaction'),
'fields' => array("SUM(Reconciliation.amount) AS 'reconciled'"),
'conditions' => array(isset($cond) ? $cond : array(),
array('LedgerEntry.id' => $id)),
'group' => 'LedgerEntry.id',
);
// Get the applied amounts on the debit side
$query['link'] =
array('DebitReconciliationLedgerEntry' => array('alias' => 'DRLE', 'DRLETransaction' => array('class' => 'Transaction')));
$qcond = $cond;
$qcond[] = array('Reconciliation.type' => 'DEBIT');
$query['conditions'] = $qcond;
$tmpstats = $this->find('first', $query);
$stats['debit_amount_reconciled'] = $tmpstats[0]['reconciled'];
// Get the applied amounts on the credit side
$query['link'] =
array('CreditReconciliationLedgerEntry' => array('alias' => 'CRLE', 'CRLETransaction' => array('class' => 'Transaction')));
$qcond = $cond;
$qcond[] = array('Reconciliation.type' => 'CREDIT');
$query['conditions'] = $qcond;
$tmpstats = $this->find('first', $query);
$stats['credit_amount_reconciled'] = $tmpstats[0]['reconciled'];

View File

@@ -14,6 +14,14 @@ class Transaction extends AppModel {
'LedgerEntry',
);
var $hasAndBelongsToMany = array(
'ReconciledLedgerEntry' => array(
'className' => 'LedgerEntry',
'joinTable' => 'reconciliations',
'foreignKey' => 'ledger_entry_id',
'associationForeignKey' => 'transaction_id',
),
);
function beforeSave() {
@@ -24,5 +32,40 @@ class Transaction extends AppModel {
return true;
}
/**************************************************************************
**************************************************************************
**************************************************************************
* function: findReconciledLedgerEntries
* - Returns ledger entries that are reconciled by the given
* transaction (such as charges reconciled by a receipt)
*/
function findReconciledLedgerEntries($id = null) {
$reconciled['LedgerEntry'] = $this->find
('all', array
('link' => array
('ReconciledLedgerEntry' => array
('fields' => array
('id',
"COALESCE(SUM(Reconciliation.amount),0) AS 'reconciled'",
"ReconciledLedgerEntry.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'",
),
),
),
'group' => ('ReconciledLedgerEntry.id'),
'conditions' => array('Transaction.id' => $id),
'fields' => array(),
));
//pr($reconciled);
$balance = 0;
foreach ($reconciled['LedgerEntry'] AS &$entry) {
$entry = array_merge($entry["ReconciledLedgerEntry"], $entry[0]);
$balance += $entry['balance'];
}
$reconciled['balance'] = $balance;
return $reconciled;
}
}
?>

View File

@@ -119,7 +119,7 @@ foreach ($jqGridColumns AS &$col) {
}
elseif ($col['formatter'] === 'date') {
$default['formatoptions'] = array('newformat' => 'm/d/Y');
$default['width'] = 90;
$default['width'] = 100;
$default['align'] = 'center';
}
elseif ($col['formatter'] === 'name' || $col['formatter'] === 'longname') {

View File

@@ -1,17 +1,24 @@
<?php /* -*- mode:PHP -*- */
if (isset($account_ftype) || isset($ledger_id) || isset($account_id) || isset($ar_account)) {
if (isset($account_ftype) || isset($ledger_id) || isset($lease_id) || isset($account_id) || isset($ar_account)) {
$single_account = true;
} else {
$single_account = false;
}
if (isset($ledger_id) || isset($account_id) || isset($ar_account)) {
if (isset($ledger_id) || isset($lease_id) || isset($account_id) || isset($ar_account)) {
$single_amount = false;
} else {
$single_amount = true;
}
if (isset($lease_id) || isset($customer_id)) {
$references = false;
}
else {
$references = true;
}
if (isset($reconcile_id)) {
$applied_amount = true;
} else {
@@ -47,9 +54,13 @@ else {
$cols['Debit Account'] = array('index' => 'DebitAccount.name', 'formatter' => 'name');
$cols['Credit Account'] = array('index' => 'CreditAccount.name', 'formatter' => 'name');
}
$cols['Customer'] = array('index' => 'Customer.name', 'formatter' => 'longname');
$cols['Lease'] = array('index' => 'Lease.number', 'formatter' => 'id');
$cols['Unit'] = array('index' => 'Unit.name', 'formatter' => 'name');
if ($references) {
$cols['Customer'] = array('index' => 'Customer.name', 'formatter' => 'longname');
$cols['Lease'] = array('index' => 'Lease.number', 'formatter' => 'id');
$cols['Unit'] = array('index' => 'Unit.name', 'formatter' => 'name');
}
$cols['Source'] = array('index' => 'MonetarySource.name', 'formatter' => 'name');
$cols['Comment'] = array('index' => 'LedgerEntry.comment', 'formatter' => 'comment', 'width'=>150);

View File

@@ -1,17 +1,38 @@
<?php /* -*- mode:PHP -*- */
if (isset($reconcile_ledger_entry_id)) {
$applied_amount = true;
} else {
$applied_amount = false;
}
$subtotal_amount = false;
// Define the table columns
$cols = array();
$cols['ID'] = array('index' => 'Transaction.id', 'formatter' => 'id');
//$cols['Customer'] = array('index' => 'Customer.name', 'formatter' => 'longname');
$cols['Timesamp'] = array('index' => 'Transaction.stamp', 'formatter' => 'date');
$cols['Timestamp'] = array('index' => 'Transaction.stamp', 'formatter' => 'date');
$cols['Through'] = array('index' => 'Transaction.through_date', 'formatter' => 'date');
$cols['Due'] = array('index' => 'Transaction.due_date', 'formatter' => 'date');
$cols['Comment'] = array('index' => 'Transaction.comment', 'formatter' => 'comment');
if ($applied_amount) {
$cols['Applied'] = array('index' => "Reconciliation.amount", 'formatter' => 'currency');
}
if ($subtotal_amount) {
$cols['Sub-Total'] = array('index' => 'subtotal', 'formatter' => 'currency', 'sortable' => false);
}
$jqGrid_options = array('jqGridColumns' => $cols,
'controller' => 'transactions',
'caption' => isset($caption) ? $caption : null);
);
$jqGrid_options += compact('grid_div_id', 'grid_id', 'caption', 'grid_setup', 'limit');
$custom_post_data = compact('reconcile_type', 'reconcile_ledger_entry_id');
if (isset($transactions)) {
$jqGrid_options += array('custom_ids' =>
@@ -20,8 +41,14 @@ if (isset($transactions)) {
$transactions),
'limit' => 5);
}
elseif (isset($reconcile_ledger_entry_id)) {
$jqGrid_options += array('limit' => 5);
}
else {
$jqGrid_options += array('search_fields' => array('Due', 'Comment'));
}
$jqGrid_options += compact('custom_post_data');
$jqGrid_options['sort_column'] = 'Timestamp';
echo $this->element('jqGrid', $jqGrid_options);

View File

@@ -81,7 +81,7 @@ echo '<div CLASS="detail supporting">' . "\n";
echo $this->element('ledger_entries',
array('caption' => 'Account',
'lease_id' => $lease['id'],
'ar_account' => true,
//'ar_account' => true,
));

View File

@@ -81,16 +81,12 @@ echo $this->element('table',
echo '<div class="infobox">' . "\n";
$rows = array();
if ($debit_ledger['Account']['trackable']) {
$rows[] = array("Applied from {$debit_ledger['Account']['name']}:",
FormatHelper::currency($stats['debit_amount_reconciled']));
$rows[] = array("{$debit_ledger['Account']['name']} Amount Remaining:",
FormatHelper::currency($stats['debit_amount_remaining']));
$rows[] = array('Debit Amount Reconciled:', FormatHelper::currency($stats['debit_amount_reconciled']));
$rows[] = array('Debit Amount Remaining:', FormatHelper::currency($stats['debit_amount_remaining']));
}
if ($credit_ledger['Account']['trackable']) {
$rows[] = array("Applied to {$credit_ledger['Account']['name']}:",
FormatHelper::currency($stats['credit_amount_reconciled']));
$rows[] = array("{$credit_ledger['Account']['name']} Amount Remaining:",
FormatHelper::currency($stats['credit_amount_remaining']));
$rows[] = array('Credit Amount Reconciled:', FormatHelper::currency($stats['credit_amount_reconciled']));
$rows[] = array('Credit Amount Remaining:', FormatHelper::currency($stats['credit_amount_remaining']));
}
echo $this->element('table',
array('class' => 'summary',
@@ -116,22 +112,20 @@ echo '<div CLASS="detail supporting">' . "\n";
*/
if ($debit_ledger['Account']['trackable']) {
echo $this->element('ledger_entries',
array('caption' => "Applied to " . $debit_ledger['Account']['name'],
echo $this->element('transactions',
array('caption' => "Payments Received",
'grid_div_id' => 'debit_reconciliation_ledger_entries',
'account_ftype' => 'debit',
'reconcile_id' => $entry['id'],
//'ledger_entries' => $reconciled['debit']['entry'],
'reconcile_type' => 'debit',
'reconcile_ledger_entry_id' => $entry['id'],
));
}
if ($credit_ledger['Account']['trackable']) {
echo $this->element('ledger_entries',
array('caption' => "Applied to " . $credit_ledger['Account']['name'],
echo $this->element('transactions',
array('caption' => "Charges Paid",
'grid_div_id' => 'credit_reconciliation_ledger_entries',
'account_ftype' => 'credit',
'reconcile_id' => $entry['id'],
//'ledger_entries' => $reconciled['credit']['entry'],
'reconcile_type' => 'credit',
'reconcile_ledger_entry_id' => $entry['id'],
));
}