Compare commits

..

3 Commits

Author SHA1 Message Date
abijah
861eabc6b5 Forgot the new files on the last checkin
git-svn-id: file:///svn-source/pmgr/branches/statements_20090623@185 97e9348a-65ac-dc4b-aefc-98561f571b83
2009-06-24 17:18:25 +00:00
abijah
6baa7fa6e6 Nowhere near complete, but must snapshot prior to my Boston trip.
git-svn-id: file:///svn-source/pmgr/branches/statements_20090623@184 97e9348a-65ac-dc4b-aefc-98561f571b83
2009-06-24 17:16:39 +00:00
abijah
8cb45ad1d6 Branch for adding the concepts of statements. I suspect I'll end up killing it.
git-svn-id: file:///svn-source/pmgr/branches/statements_20090623@183 97e9348a-65ac-dc4b-aefc-98561f571b83
2009-06-24 17:14:39 +00:00
23 changed files with 692 additions and 554 deletions

View File

@@ -633,14 +633,8 @@ CREATE TABLE `pmgr_customers` (
-- If NULL, rely on the contact info exclusively -- If NULL, rely on the contact info exclusively
`name` VARCHAR(80) DEFAULT NULL, `name` VARCHAR(80) DEFAULT NULL,
-- A customer gets their own account, although any -- Statement of charges/payments
-- lease specific charge (rent, late fees, etc) will `statement_id` INT(10) UNSIGNED NOT NULL,
-- 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 -- Primary Contact... every customer must have one
-- (and presumably, most customers will _be_ one). -- (and presumably, most customers will _be_ one).
@@ -703,12 +697,13 @@ CREATE TABLE `pmgr_leases` (
-- Allow user to specify their own lease numbers -- Allow user to specify their own lease numbers
-- If NULL, `id` will be used -- If NULL, `id` will be used
`number` VARCHAR(20) DEFAULT NULL, -- `number` VARCHAR(20) DEFAULT NULL,
`number` INT(10) UNSIGNED DEFAULT NULL,
`lease_type_id` INT(10) UNSIGNED NOT NULL, `lease_type_id` INT(10) UNSIGNED NOT NULL,
`unit_id` INT(10) UNSIGNED NOT NULL, `unit_id` INT(10) UNSIGNED NOT NULL,
`customer_id` INT(10) UNSIGNED NOT NULL, `customer_id` INT(10) UNSIGNED NOT NULL,
`account_id` INT(10) UNSIGNED NOT NULL, `statement_id` INT(10) UNSIGNED NOT NULL,
`late_schedule_id` INT(10) UNSIGNED DEFAULT NULL, `late_schedule_id` INT(10) UNSIGNED DEFAULT NULL,
`lease_date` DATE NOT NULL, `lease_date` DATE NOT NULL,
@@ -989,21 +984,29 @@ DROP TABLE IF EXISTS `pmgr_reconciliations`;
CREATE TABLE `pmgr_reconciliations` ( CREATE TABLE `pmgr_reconciliations` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` ENUM('DEBIT', `debit_ledger_entry_id` INT(10) UNSIGNED NOT NULL,
'CREDIT') `credit_ledger_entry_id` INT(10) UNSIGNED NOT NULL,
NOT NULL, `amount` FLOAT(12,2) 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`) PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8; ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ##
-- ## MONETARY
-- ##
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- ---------------------------------------------------------------------- -- ----------------------------------------------------------------------
-- TABLE pmgr_monetary_sources -- TABLE pmgr_monetary_sources
@@ -1058,6 +1061,59 @@ UNLOCK TABLES;
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ######################################################################
-- ##
-- ## STATEMENTS
-- ##
-- ## Statements are supplementary financial information. They should
-- ## NEVER be used in financial calculations, but rather are secondary
-- ## information, to be created where needed.
-- ----------------------------------------------------------------------
-- ----------------------------------------------------------------------
-- TABLE pmgr_statements
DROP TABLE IF EXISTS `pmgr_statements`;
CREATE TABLE `pmgr_statements` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`comment` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ----------------------------------------------------------------------
-- ----------------------------------------------------------------------
-- TABLE pmgr_statement_entries
DROP TABLE IF EXISTS `pmgr_statement_entries`;
CREATE TABLE `pmgr_statement_entries` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`type` ENUM('CHARGE',
'PAYMENT')
NOT NULL,
`statement_id` INT(10) UNSIGNED NOT NULL,
`ledger_entry_id` INT(10) UNSIGNED NOT NULL,
`amount` FLOAT(12,2) NOT NULL,
`comment` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
-- ###################################################################### -- ######################################################################
-- ###################################################################### -- ######################################################################

View File

@@ -683,6 +683,13 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}} $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}
= { 'name' => "$row->{'LastName'}, $row->{'FirstName'}" }; = { 'name' => "$row->{'LastName'}, $row->{'FirstName'}" };
# Each tenants receives a statement
addRow('statements',
{ 'comment' => ("Statement for " .
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'name'}) });
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'statement_id'} =
$newdb{'tables'}{'statements'}{'autoid'};
addRow('contacts', addRow('contacts',
{ 'first_name' => $row->{'FirstName'}, { 'first_name' => $row->{'FirstName'},
'middle_name' => $row->{'MiddleName'}, 'middle_name' => $row->{'MiddleName'},
@@ -692,15 +699,11 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'} = $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'} =
$newdb{'tables'}{'contacts'}{'autoid'}; $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', addRow('customers',
{ 'name' => "$row->{'LastName'}, $row->{'FirstName'}", { 'name' => "$row->{'LastName'}, $row->{'FirstName'}",
'primary_contact_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'}, 'statement_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'statement_id'},
'account_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'account_id'} }); 'primary_contact_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'id'} });
$newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'} = $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'} =
$newdb{'tables'}{'customers'}{'autoid'}; $newdb{'tables'}{'customers'}{'autoid'};
@@ -818,19 +821,22 @@ $query = "SELECT L.*, A.TenantID FROM TenantLedger L LEFT JOIN `Access` A ON A.L
foreach $row (@{query($sdbh, $query)}) { foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}} $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}
= { 'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'} }; = { 'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'},
'customer_statement_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'statement_id'},
};
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'account_id'} # Each lease receives a statement
= $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'account_id'}; addRow('statements',
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'ledger_id'} { 'comment' => ("Statement for Lease #" . $row->{'LedgerID'}) });
= $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'ledger_id'}; $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_statement_id'} =
$newdb{'tables'}{'statements'}{'autoid'};
addRow('leases', addRow('leases',
{ 'number' => $row->{'LedgerID'}, { 'number' => $row->{'LedgerID'},
'statement_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_statement_id'},
'lease_type_id' => $newdb{'tables'}{'lease_types'}{'autoid'}, 'lease_type_id' => $newdb{'tables'}{'lease_types'}{'autoid'},
'unit_id' => $newdb{'lookup'}{'unit'}{$row->{'UnitID'}}{'id'}, 'unit_id' => $newdb{'lookup'}{'unit'}{$row->{'UnitID'}}{'id'},
'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'}, 'customer_id' => $newdb{'lookup'}{'tenant'}{$row->{'TenantID'}}{'customer_id'},
'account_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'account_id'},
'lease_date' => datefmt($row->{'DateIn'}), 'lease_date' => datefmt($row->{'DateIn'}),
'movein_date' => datefmt($row->{'DateIn'}), 'movein_date' => datefmt($row->{'DateIn'}),
'moveout_date' => datefmt($row->{'DateOut'}), 'moveout_date' => datefmt($row->{'DateOut'}),
@@ -839,6 +845,7 @@ foreach $row (@{query($sdbh, $query)}) {
$newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'} = $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'} =
$newdb{'tables'}{'leases'}{'autoid'}; $newdb{'tables'}{'leases'}{'autoid'};
} }
@@ -860,52 +867,57 @@ $newdb{'lookup'}{'charge'} = {};
$query = "SELECT * FROM Charges ORDER BY ChargeID"; $query = "SELECT * FROM Charges ORDER BY ChargeID";
foreach $row (@{query($sdbh, $query)}) { foreach $row (@{query($sdbh, $query)}) {
my $credit_ledger_id;
my $ledger_entry_id;
addRow('transactions', addRow('transactions',
{ 'stamp' => datefmt($row->{'ChargeDate'}), { 'stamp' => datefmt($row->{'ChargeDate'}),
'through_date' => datefmt($row->{'EndDate'}) }); 'through_date' => datefmt($row->{'EndDate'}) });
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}} $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}
= { 'tx' => $newdb{'tables'}{'transactions'}{'autoid'}, = { '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'}, 'amount' => $row->{'ChargeAmount'},
'tax_amount' => $row->{'TaxAmount'}, 'tax_amount' => $row->{'TaxAmount'},
'customer_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'customer_id'}, 'lease_statement_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_statement_id'},
'lease_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'lease_id'}, 'customer_statement_id' => $newdb{'lookup'}{'ledger'}{$row->{'LedgerID'}}{'customer_statement_id'},
}; };
$credit_ledger_id = $newdb{'lookup'}{'charge_type'}{$row->{'ChargeDescription'}}{'ledger_id'};
addRow('ledger_entries', addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'}, { 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'}, 'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'}, 'debit_ledger_id' => $newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'},
'credit_ledger_id' => $credit_ledger_id, 'credit_ledger_id' => $newdb{'lookup'}{'charge_type'}{$row->{'ChargeDescription'}}{'ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => $row->{'ChargeAmount'}, 'amount' => $row->{'ChargeAmount'},
'comment' => "Charge: $row->{'ChargeID'}; Ledger: $row->{'LedgerID'}" }); 'comment' => "Charge: $row->{'ChargeID'}; Ledger: $row->{'LedgerID'}" });
foreach ($newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_statement_id'},
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_statement_id'}) {
addRow('statement_entries',
{ 'type' => 'CHARGE',
'statement_id' => $_,
'ledger_entry_id' => $newdb{'tables'}{'ledger_entries'}{'autoid'},
'amount' => $row->{'ChargeAmount'} });
}
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'} $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'}; = $newdb{'tables'}{'ledger_entries'}{'autoid'};
next unless $row->{'TaxAmount'}; next unless $row->{'TaxAmount'};
$credit_ledger_id = $newdb{'lookup'}{'charge_type'}{'Tax'}{'ledger_id'};
addRow('ledger_entries', addRow('ledger_entries',
{ 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'}, { 'monetary_source_id' => $newdb{'ids'}{'monetary_source'}{'internal'},
'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'}, 'transaction_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'}, 'debit_ledger_id' => $newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'},
'credit_ledger_id' => $credit_ledger_id, 'credit_ledger_id' => $newdb{'lookup'}{'charge_type'}{'Tax'}{'ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => $row->{'TaxAmount'}, 'amount' => $row->{'TaxAmount'},
'comment' => undef }); 'comment' => undef });
foreach ($newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_statement_id'},
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_statement_id'}) {
addRow('statement_entries',
{ 'type' => 'CHARGE',
'statement_id' => $_,
'ledger_entry_id' => $newdb{'tables'}{'ledger_entries'}{'autoid'},
'amount' => $row->{'TaxAmount'} });
}
$newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tax_entry'} $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'tax_entry'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'}; = $newdb{'tables'}{'ledger_entries'}{'autoid'};
@@ -1011,14 +1023,21 @@ foreach $row (@{query($sdbh, $query)})
{ 'monetary_source_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'}, { 'monetary_source_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'monetary_source_id'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'}, 'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'},
'debit_ledger_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'}, 'debit_ledger_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'debit_ledger_id'},
'credit_ledger_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_id'}, 'credit_ledger_id' => $newdb{'lookup'}{'account'}{'A/R'}{'ledger_id'},
'customer_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_id'},
#'lease_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_id'},
'amount' => 0, 'amount' => 0,
'comment' => "Receipt: $row->{'ReceiptNum'}; " }); 'comment' => "Receipt: $row->{'ReceiptNum'}; " });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'} $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
= $newdb{'tables'}{'ledger_entries'}{'autoid'}; = $newdb{'tables'}{'ledger_entries'}{'autoid'};
addRow('statement_entries',
{ 'type' => 'PAYMENT',
'statement_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'customer_statement_id'},
'ledger_entry_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'},
'amount' => 0 });
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'statement_entry_id'}
= $newdb{'tables'}{'statement_entries'}{'autoid'};
} }
$newdb{'tables'}{'ledger_entries'}{'rows'}[ $newdb{'tables'}{'ledger_entries'}{'rows'}[
@@ -1029,6 +1048,16 @@ foreach $row (@{query($sdbh, $query)})
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'} $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'}
]{'comment'} .= 'P:'.$row->{'PaymentID'} . '->C:' . $row->{'ChargeID'} . '; '; ]{'comment'} .= 'P:'.$row->{'PaymentID'} . '->C:' . $row->{'ChargeID'} . '; ';
$newdb{'tables'}{'statement_entries'}{'rows'}[
$newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'statement_entry_id'}
]{'amount'} += $row->{'PaymentAmount'};
addRow('statement_entries',
{ 'type' => 'PAYMENT',
'statement_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'lease_statement_id'},
'ledger_entry_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{$row->{'PaymentType'}}{'ledger_entry_id'},
'amount' => $row->{'PaymentAmount'} });
# OK, now that the receipt is reconciled, update # OK, now that the receipt is reconciled, update
# payment to reference the true ledger_entry_id # payment to reference the true ledger_entry_id
$newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'} $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'}
@@ -1041,11 +1070,10 @@ foreach $row (@{query($sdbh, $query)})
# Reconcile the A/R account. Since this is from the perspective # Reconcile the A/R account. Since this is from the perspective
# of the A/R, charge is the debit, and payment is the credit # of the A/R, charge is the debit, and payment is the credit
addRow('reconciliations', addRow('reconciliations',
{ 'type' => 'DEBIT', { 'debit_ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'},
'ledger_entry_id' => $newdb{'lookup'}{'charge'}{$row->{'ChargeID'}}{'ledger_entry_id'}, 'credit_ledger_entry_id' => $newdb{'lookup'}{'payment'}{$row->{'PaymentID'}}{'ledger_entry_id'},
'transaction_id' => $newdb{'lookup'}{'receipt'}{$row->{'ReceiptNum'}}{'tx'}, 'amount' => $reconcile_amount,
'amount' => $reconcile_amount, });
});
# Update the transaction to use the memo from this payment # Update the transaction to use the memo from this payment
if ($row->{'Memo'}) { if ($row->{'Memo'}) {
@@ -1236,9 +1264,8 @@ sub fakeTesting {
foreach my $t (@{$e->{'track'}}) { foreach my $t (@{$e->{'track'}}) {
addRow('reconciliations', addRow('reconciliations',
{ 'type' => 'DEBIT', { 'debit_ledger_entry_id' => $t->{'debit'},
'ledger_entry_id' => $t->{'debit'}, 'credit_ledger_entry_id' => $e->{'id'},
'transaction_id' => $tx->{'id'},
'amount' => $t->{'amount'} 'amount' => $t->{'amount'}
}); });
} }

View File

@@ -78,6 +78,24 @@ class AppModel extends Model {
/**************************************************************************
**************************************************************************
**************************************************************************
* function: nameToID
* - Returns the ID of the named item
*/
function nameToID($name) {
$this->cacheQueries = true;
$item = $this->find('first', array
('recursive' => -1,
'conditions' => compact('name'),
));
$this->cacheQueries = false;
$item = current($item);
return $item['id'];
}
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************
************************************************************************** **************************************************************************

View File

@@ -33,7 +33,7 @@ class LedgerEntriesController extends AppController {
} }
} }
function jqGridDataCountTables(&$params, &$model) { function jqGridDataTables(&$params, &$model) {
$link = $link =
array(// Models array(// Models
'Transaction' => 'Transaction' =>
@@ -95,13 +95,8 @@ class LedgerEntriesController extends AppController {
); );
} }
if (isset($params['custom']['account_id']) || isset($params['custom']['lease_id'])) { if (isset($params['custom']['account_id'])) {
if (isset($params['custom']['account_id'])) $account_id = $params['custom']['account_id'];
$account_id = $params['custom']['account_id'];
else
$account_id =
$this->LedgerEntry->DebitLedger->Account->accountReceivableAccountID();
$link['Ledger'] = $link['Ledger'] =
array('fields' => array('id', 'sequence'), array('fields' => array('id', 'sequence'),
'conditions' => ("Ledger.id = IF(DebitLedger.account_id = $account_id," . 'conditions' => ("Ledger.id = IF(DebitLedger.account_id = $account_id," .
@@ -113,57 +108,18 @@ 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'])) { if (isset($params['custom']['reconcile_id'])) {
$ftype = $params['custom']['account_ftype']; $ftype = $params['custom']['account_ftype'];
$ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype); $ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype);
$link['ReconcilingTransaction'] = $ftype = ucfirst($ftype);
array('fields' => array('Reconciliation.amount'), $link[$ftype.'ReconciliationLedgerEntry'] =
'conditions' => array('Reconciliation.type' => $ftype), array('fields' => array('Reconciliation.amount'));
);
} }
return array('link' => $link); return array('link' => $link);
} }
function jqGridDataTables(&$params, &$model) {
return $this->jqGridDataCountTables($params, $model);
}
function jqGridDataFields(&$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']) $ledger_id = (isset($params['custom']['ledger_id'])
? $params['custom']['ledger_id'] ? $params['custom']['ledger_id']
: null); : null);
@@ -187,26 +143,20 @@ class LedgerEntriesController extends AppController {
$conditions = parent::jqGridDataConditions($params, $model); $conditions = parent::jqGridDataConditions($params, $model);
if ($params['action'] === 'ledger' && isset($ledger_id)) { if ($params['action'] === 'ledger') {
$conditions[] = $model->ledgerContextConditions($ledger_id, $account_type); $conditions[] = $model->ledgerContextConditions($ledger_id, $account_type);
} }
if (isset($params['custom']['reconcile_id'])) { if (isset($params['custom']['reconcile_id'])) {
$ftype = $params['custom']['account_ftype']; $ftype = $params['custom']['account_ftype'];
//$ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype); //$ftype = $this->LedgerEntry->DebitLedger->Account->fundamentalOpposite($ftype);
//$link['ReconcilingTransaction']['conditions'][] = array('Reconciliation.type' => $ftype); $conditions[] = array('Reconciliation.'.$ftype.'_ledger_entry_id' => $params['custom']['reconcile_id']);
$conditions[] = array('Reconciliation.ledger_entry_id' => $params['custom']['reconcile_id']);
} }
if (isset($params['custom']['account_id'])) { if (isset($params['custom']['account_id'])) {
$conditions[] = $conditions[] =
array('OR' => array('OR' =>
array(array('CreditAccount.id' => $params['custom']['account_id']), array(array('CreditAccount.id' => $params['custom']['account_id']),
array('DebitAccount.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'])) { if (isset($params['custom']['customer_id'])) {
@@ -216,10 +166,7 @@ class LedgerEntriesController extends AppController {
if (isset($params['custom']['lease_id'])) { if (isset($params['custom']['lease_id'])) {
$conditions[] = $conditions[] =
array('OR' => array array('Lease.id' => $params['custom']['lease_id']);
(array('Lease.id' => $params['custom']['lease_id']),
array('ReconciledLedgerEntry.lease_id' => $params['custom']['lease_id']),
));
} }
if (isset($params['custom']['transaction_id'])) { if (isset($params['custom']['transaction_id'])) {
@@ -327,7 +274,7 @@ class LedgerEntriesController extends AppController {
'conditions' => array('LedgerEntry.id' => $id), 'conditions' => array('LedgerEntry.id' => $id),
)); ));
//pr($entry); pr($entry);
// Because 'DebitLedger' and 'CreditLedger' both relate to 'Account', // Because 'DebitLedger' and 'CreditLedger' both relate to 'Account',
// CakePHP will not include them in the LedgerEntry->find (or so it // CakePHP will not include them in the LedgerEntry->find (or so it
@@ -357,8 +304,8 @@ class LedgerEntriesController extends AppController {
$stats['credit_amount_remaining'] = $entry['LedgerEntry']['amount'] - $stats['credit_amount_reconciled']; $stats['credit_amount_remaining'] = $entry['LedgerEntry']['amount'] - $stats['credit_amount_reconciled'];
//pr($stats); //pr($stats);
$reconciled = $this->LedgerEntry->findReconcilingTransactions($id); $reconciled = $this->LedgerEntry->findReconciledLedgerEntries($id);
//pr(compact('reconciled')); //pr($reconciled);
// Prepare to render. // Prepare to render.
$title = "Ledger Entry #{$entry['LedgerEntry']['id']}"; $title = "Ledger Entry #{$entry['LedgerEntry']['id']}";

View File

@@ -0,0 +1,116 @@
<?php
class StatementEntriesController extends AppController {
var $sidemenu_links = array();
/**************************************************************************
**************************************************************************
**************************************************************************
* override: sideMenuLinks
* - Generates controller specific links for the side menu
*/
function sideMenuLinks() {
return array_merge(parent::sideMenuLinks(), $this->sidemenu_links);
}
/**************************************************************************
**************************************************************************
**************************************************************************
* virtuals: jqGridData
* - With the application controller handling the jqGridData action,
* these virtual functions ensure that the correct data is passed
* to jqGrid.
*/
function jqGridDataTables(&$params, &$model) {
$link =
array(// Models
'LedgerEntry' =>
array('fields' => array('id'),
// Models
'Transaction' =>
array('fields' => array('id', 'stamp'),
),
'Ledger' =>
array('fields' => array('id', 'sequence'),
'conditions' => ("Ledger.id = IF(StatementEntry.type = 'CHARGE'," .
" LedgerEntry.credit_ledger_id," .
" LedgerEntry.debit_ledger_id)"),
// Models
'Account' => array('fields' => array('id', 'name'),
),
),
),
);
return array('link' => $link);
}
function jqGridDataFields(&$params, &$model) {
$fields = array('id', 'type', 'comment');
$fields[] = "IF(StatementEntry.type = 'CHARGE', StatementEntry.amount, NULL) AS 'charge'";
$fields[] = "IF(StatementEntry.type = 'PAYMENT', StatementEntry.amount, NULL) AS 'payment'";
$fields[] = "IF(StatementEntry.type = 'CHARGE', 1, -1) * StatementEntry.amount AS 'amount'";
return $fields;
}
function jqGridDataConditions(&$params, &$model) {
$conditions = parent::jqGridDataConditions($params, $model);
if (isset($params['custom']['statement_id'])) {
$conditions[] =
array('StatementEntry.statement_id' => $params['custom']['statement_id']);
}
return $conditions;
}
function jqGridRecordLinks(&$params, &$model, &$records, $links) {
$links['Transaction'] = array('id');
$links['StatementEntry'] = array('id');
$links['Account'] = array('controller' => 'accounts', 'name');
$links['LedgerEntry'] = array('id');
return parent::jqGridRecordLinks($params, $model, $records, $links);
}
function jqGridRecordsPostProcess(&$params, &$model, &$records) {
parent::jqGridRecordsPostProcess($params, $model, $records);
$subtotal = 0;
foreach ($records AS &$record) {
$amount = $record['StatementEntry']['amount'];
$record['StatementEntry']['amount'] = $amount;
$record['StatementEntry']['subtotal'] = ($subtotal += $amount);
}
}
/**************************************************************************
**************************************************************************
**************************************************************************
* action: view
* - Displays information about a specific entry
*/
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Item.', true));
$this->redirect(array('controller' => 'accounts', 'action'=>'index'));
}
// Get the StatementEntry and related fields
$entry = $this->StatementEntry->find
('first',
array('contain' => array(),
'conditions' => array('StatementEntry.id' => $id),
));
// Prepare to render.
$title = "Statement Entry #{$entry['StatementEntry']['id']}";
$this->set(compact('entry', 'title'));
}
}

View File

@@ -41,43 +41,6 @@ class TransactionsController extends AppController {
* to jqGrid. * 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) { function jqGridRecordLinks(&$params, &$model, &$records, $links) {
$links['Transaction'] = array('id'); $links['Transaction'] = array('id');
return parent::jqGridRecordLinks($params, $model, $records, $links); return parent::jqGridRecordLinks($params, $model, $records, $links);

View File

@@ -55,7 +55,7 @@ class UnitsController extends AppController {
$link = array $link = array
('link' => ('link' =>
array(// Models array(// Models
'UnitSize' => array('fields' => array('name')), 'UnitSize' => array('fields' => array('id', 'name')),
), ),
); );
@@ -93,6 +93,11 @@ class UnitsController extends AppController {
return parent::jqGridDataOrder($params, $model, $index, $direction); return parent::jqGridDataOrder($params, $model, $index, $direction);
} }
function jqGridRecordLinks(&$params, &$model, &$records, $links) {
//$links['UnitSize'] = array('name');
$links['Unit'] = array('name', 'id');
return parent::jqGridRecordLinks($params, $model, $records, $links);
}
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************

View File

@@ -82,26 +82,13 @@ class Account extends AppModel {
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************
************************************************************************** **************************************************************************
* function: accountNameToID * function: Account IDs
* - Returns the ID of the named account * - Returns the ID of the desired account
*/ */
function accountNameToID($name) {
$this->cacheQueries = true;
$account = $this->find('first', array
('recursive' => -1,
'conditions' => compact('name'),
));
$this->cacheQueries = false;
return $account['Account']['id'];
}
function securityDepositAccountID() { return $this->accountNameToID('Security Deposit'); } function securityDepositAccountID() { return $this->nameToID('Security Deposit'); }
function rentAccountID() { return $this->accountNameToID('Rent'); } function rentAccountID() { return $this->nameToID('Rent'); }
function accountReceivableAccountID() { return $this->accountNameToID('A/R'); } function accountReceivableAccountID() { return $this->nameToID('A/R'); }
function invoiceAccountID() { return $this->accountReceivableAccountID(); }
function receiptAccountID() { return $this->accountReceivableAccountID(); }
//function invoiceAccountID() { return $this->accountNameToID('Invoice'); }
//function receiptAccountID() { return $this->accountNameToID('Receipt'); }
/************************************************************************** /**************************************************************************
@@ -226,20 +213,20 @@ class Account extends AppModel {
? array($fundamental_type) ? array($fundamental_type)
: array('debit', 'credit')) AS $fund) { : array('debit', 'credit')) AS $fund) {
$ucfund = ucfirst($fund); $ucfund = ucfirst($fund);
$unreconciled[$fund]['LedgerEntry'] = $this->find $unreconciled[$fund]['entry'] = $this->find
('all', array ('all', array
('link' => array ('link' => array
('Ledger' => array ('Ledger' => array
('fields' => array(), ('fields' => array(),
'LedgerEntry' => array "LedgerEntry" => array
('class' => "{$ucfund}LedgerEntry", ('class' => "{$ucfund}LedgerEntry",
'fields' => array('id', 'amount'), 'fields' => array('id', 'amount'),
'ReconcilingTransaction' => array "ReconciliationLedgerEntry" => array
('fields' => array ('class' => "{$ucfund}ReconciliationLedgerEntry",
'fields' => array
("COALESCE(SUM(Reconciliation.amount),0) AS 'reconciled'", ("COALESCE(SUM(Reconciliation.amount),0) AS 'reconciled'",
"LedgerEntry.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'", "LedgerEntry.amount - COALESCE(SUM(Reconciliation.amount),0) AS 'balance'",
), ),
'conditions' => array('Reconciliation.type' => $fund),
), ),
), ),
), ),
@@ -251,7 +238,7 @@ class Account extends AppModel {
'fields' => array(), 'fields' => array(),
)); ));
$balance = 0; $balance = 0;
foreach ($unreconciled[$fund]['LedgerEntry'] AS &$entry) { foreach ($unreconciled[$fund]['entry'] AS &$entry) {
$entry = array_merge(array_diff_key($entry["LedgerEntry"], array(0=>true)), $entry = array_merge(array_diff_key($entry["LedgerEntry"], array(0=>true)),
$entry[0]); $entry[0]);
$balance += $entry['balance']; $balance += $entry['balance'];
@@ -279,7 +266,7 @@ class Account extends AppModel {
function reconcileNewLedgerEntry($id, $fundamental_type, $amount, $cond = null) { function reconcileNewLedgerEntry($id, $fundamental_type, $amount, $cond = null) {
$ofund = $this->fundamentalOpposite($fundamental_type); $ofund = $this->fundamentalOpposite($fundamental_type);
$unreconciled = array($ofund => array('LedgerEntry'=>array(), 'balance'=>0)); $unreconciled = array($ofund => array('entry'=>array(), 'balance'=>0));
$applied = 0; $applied = 0;
// if there is no money in the entry, it can reconcile nothing // if there is no money in the entry, it can reconcile nothing
@@ -287,14 +274,14 @@ class Account extends AppModel {
if ($amount > 0) { if ($amount > 0) {
$unreconciled = $this->findUnreconciledLedgerEntries($id, $ofund, $cond); $unreconciled = $this->findUnreconciledLedgerEntries($id, $ofund, $cond);
foreach ($unreconciled[$ofund]['LedgerEntry'] AS $i => &$entry) { foreach ($unreconciled[$ofund]['entry'] AS $i => &$entry) {
// Determine if amount is sufficient to cover the entry // Determine if amount is sufficient to cover the entry
if ($amount > $entry['balance']) if ($amount > $entry['balance'])
$apply = $entry['balance']; $apply = $entry['balance'];
elseif ($amount > 0) elseif ($amount > 0)
$apply = $amount; $apply = $amount;
else { else {
unset($unreconciled[$ofund]['LedgerEntry'][$i]); unset($unreconciled[$ofund]['entry'][$i]);
continue; continue;
} }

View File

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

View File

@@ -8,6 +8,7 @@ class Customer extends AppModel {
); );
var $belongsTo = array( var $belongsTo = array(
'Statement',
'PrimaryContact' => array( 'PrimaryContact' => array(
'className' => 'Contact', 'className' => 'Contact',
), ),
@@ -43,13 +44,26 @@ class Customer extends AppModel {
*/ */
function accountId($id) { function accountId($id) {
$this->cacheQueries = true; $this->cacheQueries = true;
$customer = $this->find('first', $item = $this->find('first',
array('contain' => false, array('contain' => false,
'fields' => array('account_id'), 'fields' => array('account_id'),
'conditions' => array(array('Customer.id' => $id)))); 'conditions' => compact('id')));
$this->cacheQueries = false; $this->cacheQueries = false;
return $customer['Customer']['account_id']; $item = current($item);
return $item['account_id'];
}
function statementID($id) {
$this->cacheQueries = true;
$item = $this->find('first', array
('recursive' => -1,
'conditions' => compact('id'),
));
$this->cacheQueries = false;
$item = current($item);
return $item['statement_id'];
} }
@@ -75,6 +89,7 @@ class Customer extends AppModel {
return $ids; return $ids;
} }
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************
************************************************************************** **************************************************************************
@@ -82,22 +97,10 @@ class Customer extends AppModel {
* - Returns an array of security deposit entries * - Returns an array of security deposit entries
*/ */
function findSecurityDeposits($id, $link = null) { function findSecurityDeposits($id, $link = null) {
/* pr(array('function' => 'Customer::findSecurityDeposits', */ return $this->Statement->findEntriesRelatedToAccount
/* 'args' => compact('id', 'link'), */ ($this->statementId($id),
/* )); */
$entries = $this->Account->findLedgerEntriesRelatedToAccount
($this->Account->invoiceAccountID(),
$this->Account->securityDepositAccountID(), $this->Account->securityDepositAccountID(),
true, array('LedgerEntry.customer_id' => $id), $link); null, $link);
/* pr(array('function' => 'Customer::findSecurityDeposits', */
/* 'args' => compact('id', 'link'), */
/* 'vars' => compact('customer'), */
/* 'return' => compact('entries'), */
/* )); */
return $entries;
} }
@@ -191,16 +194,11 @@ class Customer extends AppModel {
* - Returns summary data from the requested customer. * - Returns summary data from the requested customer.
*/ */
function stats($id = null) { function stats($id = null, $cond = null, $link = null) {
if (!$id) if (!$id)
return null; return null;
$stats = $this->Account->stats($this->Account->accountReceivableAccountID(), true, return $this->Statement->stats($this->statementID($id), $cond, $link);
array('LedgerEntry.customer_id' => $id));
// Pull to the top level and return
$stats = $stats['Ledger'];
return $stats;
} }
} }

View File

@@ -26,6 +26,7 @@ class Lease extends AppModel {
'LeaseType', 'LeaseType',
'Unit', 'Unit',
'Customer', 'Customer',
'Statement',
'LateSchedule', 'LateSchedule',
); );
@@ -40,13 +41,23 @@ class Lease extends AppModel {
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************
************************************************************************** **************************************************************************
* function: accountId * function: accessors
* - Returns the accountId of the given lease
*/ */
function accountId($id) { function accountId($id) {
return $this->Account->invoiceAccountID(); return $this->Account->invoiceAccountID();
} }
function statementID($id) {
$this->cacheQueries = true;
$item = $this->find('first', array
('recursive' => -1,
'conditions' => compact('id'),
));
$this->cacheQueries = false;
$item = current($item);
return $item['statement_id'];
}
/************************************************************************** /**************************************************************************
************************************************************************** **************************************************************************
@@ -83,21 +94,10 @@ class Lease extends AppModel {
* - Returns an array of security deposit entries * - Returns an array of security deposit entries
*/ */
function findSecurityDeposits($id, $link = null) { function findSecurityDeposits($id, $link = null) {
/* pr(array('function' => 'Lease::findSecurityDeposits', */ return $this->Statement->findEntriesRelatedToAccount
/* 'args' => compact('id', 'link'), */ ($this->statementId($id),
/* )); */
$entries = $this->Account->findLedgerEntriesRelatedToAccount
($this->accountId($id),
$this->Account->securityDepositAccountID(), $this->Account->securityDepositAccountID(),
true, array('LedgerEntry.lease_id' => $id), $link); null, $link);
/* pr(array('function' => 'Lease::findSecurityDeposits', */
/* 'args' => compact('id', 'link'), */
/* 'vars' => compact('lease'), */
/* 'return' => compact('entries'), */
/* )); */
return $entries;
} }
@@ -142,20 +142,11 @@ class Lease extends AppModel {
* - Returns summary data from the requested lease. * - Returns summary data from the requested lease.
*/ */
function stats($id = null) { function stats($id = null, $cond = null, $link = null) {
if (!$id) if (!$id)
return null; return null;
$stats = $this->Account->stats($this->Account->accountReceivableAccountID(), true, return $this->Statement->stats($this->statementID($id), $cond, $link);
array('OR' => array
(array('LedgerEntry.lease_id' => $id),
array('ReconciledLedgerEntry.lease_id' => $id),
),
));
// Pull to the top level and return
$stats = $stats['Ledger'];
return $stats;
} }
} }

View File

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

123
site/models/statement.php Normal file
View File

@@ -0,0 +1,123 @@
<?php
class Statement extends AppModel {
var $hasMany = array(
'Lease',
'Customer',
'StatementEntry',
'ChargeStatementEntry' => array(
'className' => 'StatementEntry',
'conditions' => array('type' => 'CHARGE'),
),
'PaymentStatementEntry' => array(
'className' => 'StatementEntry',
'conditions' => array('type' => 'PAYMENT'),
),
);
/**************************************************************************
**************************************************************************
**************************************************************************
* function: findStatementEntries
* - Returns an array of statement entries that belong to a given
* statement. There is extra work done... see the StatementEntry model.
*/
function findStatementEntries($id, $cond = null, $link = null) {
/* pr(array('function' => 'Statement::findStatementEntries', */
/* 'args' => compact('id', 'cond', 'link'), */
/* )); */
if (!isset($cond))
$cond = array();
$cond[] = array('Statement.id' => $id);
$entries = $this->find('all', array('link' => $link, 'conditions' => $cond));
/* pr(array('function' => 'Statement::findStatementEntries', */
/* 'args' => compact('id', 'cond', 'link'), */
/* 'return' => compact('entries'), */
/* )); */
return $entries;
}
/**************************************************************************
**************************************************************************
**************************************************************************
* function: findEntriesRelatedToAccount
* - Returns an array of statement entries that belong to the given
* account, and are related to a specific account.
*/
function findEntriesRelatedToAccount($id, $rel_ids, $cond = null, $link = null) {
/* pr(array('function' => 'Statement::findEntriesRelatedToAccount', */
/* 'args' => compact('id', 'rel_ids', 'cond', 'link'), */
/* )); */
if (!isset($cond))
$cond = array();
if (!isset($link))
$link = array();
if (!is_array($rel_ids))
$rel_ids = array($rel_ids);
$link['StatementEntry'] = array('LedgerEntry' => array('Ledger' => array('Account')));
$cond[] = array('Account.id' => $rel_ids);
$entries = $this->findStatementEntries($id, $cond, $link);
$stats = $this->stats($id, $cond, $link);
$entries = array('Entries' => $entries,
'summary' => $stats);
/* pr(array('function' => 'Statement::findEntriesRelatedToAccount', */
/* 'args' => compact('id', 'relid', 'cond', 'link'), */
/* 'return' => compact('entries'), */
/* )); */
return $entries;
}
/**************************************************************************
**************************************************************************
**************************************************************************
* function: stats
* - Returns summary data from the requested statement.
*/
function stats($id, $cond = null, $link = null) {
if (!isset($cond))
$cond = array();
if (!isset($link))
$link = array();
if (!isset($link['StatementEntry']))
$link['StatementEntry'] = array('fields' => array());
$cond[] = array('Statement.id' => $id);
$stats = $this->find
('first', array
('link' => $link,
'fields' =>
array("SUM(IF(StatementEntry.type = 'CHARGE',
StatementEntry.amount, NULL)) AS charges",
"SUM(IF(StatementEntry.type = 'PAYMENT',
StatementEntry.amount, NULL)) AS payments",
"SUM(IF(StatementEntry.type = 'CHARGE', 1, -1)
* IF(StatementEntry.amount, StatementEntry.amount, 0)
) AS balance",
"COUNT(StatementEntry.id) AS entries"),
'conditions' => $cond,
'group' => 'Statement.id',
));
// The fields are all tucked into the [0] index,
// and the rest of the array is useless (empty).
return $stats[0];
}
}
?>

View File

@@ -0,0 +1,9 @@
<?php
class StatementEntry extends AppModel {
var $belongsTo = array(
'Statement',
'LedgerEntry',
);
}

View File

@@ -14,14 +14,6 @@ class Transaction extends AppModel {
'LedgerEntry', 'LedgerEntry',
); );
var $hasAndBelongsToMany = array(
'ReconciledLedgerEntry' => array(
'className' => 'LedgerEntry',
'joinTable' => 'reconciliations',
'foreignKey' => 'ledger_entry_id',
'associationForeignKey' => 'transaction_id',
),
);
function beforeSave() { function beforeSave() {
@@ -32,40 +24,5 @@ class Transaction extends AppModel {
return true; 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

@@ -63,13 +63,12 @@ echo $this->element('leases',
/********************************************************************** /**********************************************************************
* Customer Account History * Customer Statement
*/ */
echo $this->element('ledger_entries', echo $this->element('statement_entries',
array('caption' => 'Account', array('caption' => 'Statement',
'customer_id' => $customer['Customer']['id'], 'statement_id' => $customer['Customer']['statement_id'],
'ar_account' => true,
)); ));

View File

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

View File

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

View File

@@ -0,0 +1,50 @@
<?php /* -*- mode:PHP -*- */
if (0) {
$subtotal_amount = false;
} else {
$subtotal_amount = true;
}
// Define the table columns
$cols = array();
$cols['ID'] = array('index' => 'StatementEntry.id', 'formatter' => 'id');
$cols['Entry'] = array('index' => 'LedgerEntry.id', 'formatter' => 'id');
$cols['Date'] = array('index' => 'Transaction.stamp', 'formatter' => 'date');
//$cols['Type'] = array('index' => 'StatementEntry.type', 'formatter' => 'name');
$cols['Account'] = array('index' => 'Account.name', 'formatter' => 'longname');
//$cols['Comment'] = array('index' => 'StatementEntry.comment', 'formatter' => 'comment', 'width'=>150);
//$cols['Amount'] = array('index' => 'StatementEntry.amount', 'formatter' => 'currency');
$cols['Charge'] = array('index' => 'charge', 'formatter' => 'currency');
$cols['Payment'] = array('index' => 'payment', 'formatter' => 'currency');
if ($subtotal_amount) {
$cols['Sub-Total'] = array('index' => 'subtotal', 'formatter' => 'currency', 'sortable' => false);
}
$custom_post_data = compact('statement_id');
$jqGrid_options = array('jqGridColumns' => $cols,
'controller' => 'statement_entries',
);
$jqGrid_options += compact('grid_div_id', 'grid_id', 'caption', 'grid_setup', 'limit');
if (isset($statement_entries)) {
$jqGrid_options += array('custom_ids' =>
array_map(create_function('$data',
'return $data["id"];'),
$statement_entries),
'limit' => 10);
}
else {
$jqGrid_options += array('action' => 'statement',
'limit' => 50);
}
$jqGrid_options += compact('custom_post_data');
$jqGrid_options['sort_column'] = 'Date';
echo $this->element('jqGrid', $jqGrid_options);

View File

@@ -1,38 +1,17 @@
<?php /* -*- mode:PHP -*- */ <?php /* -*- mode:PHP -*- */
if (isset($reconcile_ledger_entry_id)) {
$applied_amount = true;
} else {
$applied_amount = false;
}
$subtotal_amount = false;
// Define the table columns // Define the table columns
$cols = array(); $cols = array();
$cols['ID'] = array('index' => 'Transaction.id', 'formatter' => 'id'); $cols['ID'] = array('index' => 'Transaction.id', 'formatter' => 'id');
//$cols['Customer'] = array('index' => 'Customer.name', 'formatter' => 'longname'); //$cols['Customer'] = array('index' => 'Customer.name', 'formatter' => 'longname');
$cols['Timestamp'] = array('index' => 'Transaction.stamp', 'formatter' => 'date'); $cols['Timesamp'] = array('index' => 'Transaction.stamp', 'formatter' => 'date');
$cols['Through'] = array('index' => 'Transaction.through_date', 'formatter' => 'date'); $cols['Through'] = array('index' => 'Transaction.through_date', 'formatter' => 'date');
$cols['Due'] = array('index' => 'Transaction.due_date', 'formatter' => 'date'); $cols['Due'] = array('index' => 'Transaction.due_date', 'formatter' => 'date');
$cols['Comment'] = array('index' => 'Transaction.comment', 'formatter' => 'comment'); $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, $jqGrid_options = array('jqGridColumns' => $cols,
'controller' => 'transactions', '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)) { if (isset($transactions)) {
$jqGrid_options += array('custom_ids' => $jqGrid_options += array('custom_ids' =>
@@ -41,14 +20,8 @@ if (isset($transactions)) {
$transactions), $transactions),
'limit' => 5); 'limit' => 5);
} }
elseif (isset($reconcile_ledger_entry_id)) {
$jqGrid_options += array('limit' => 5);
}
else { else {
$jqGrid_options += array('search_fields' => array('Due', 'Comment')); $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); echo $this->element('jqGrid', $jqGrid_options);

View File

@@ -78,10 +78,9 @@ echo '<div CLASS="detail supporting">' . "\n";
* Lease Account History * Lease Account History
*/ */
echo $this->element('ledger_entries', echo $this->element('statement_entries',
array('caption' => 'Account', array('caption' => 'Statement',
'lease_id' => $lease['id'], 'statement_id' => $lease['statement_id'],
//'ar_account' => true,
)); ));

View File

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

View File

@@ -57,15 +57,14 @@ echo $this->element('leases',
/********************************************************************** /**********************************************************************
* Current Tenant Lease Account History * Current Lease Statement History
*/ */
echo $this->element('ledger_entries', echo $this->element('statement_entries',
array('caption' => ('Current Lease Account (' . array('caption' => ('Current Lease Statement (' .
$unit['CurrentLease']['Customer']['name'] $unit['CurrentLease']['Customer']['name'] .
. ')'), ')'),
'ar_account' => true, 'statement_id' => $unit['CurrentLease']['statement_id']
'lease_id' => $unit['CurrentLease']['id'],
)); ));