/lib/models/Invoice.php
PHP | 687 lines | 330 code | 127 blank | 230 comment | 24 complexity | ce2b2e024b348571858d97072518dbb6 MD5 | raw file
- <?php
- /**
- * User
- *
- * This class has been auto-generated by the Doctrine ORM Framework
- *
- * @package ##PACKAGE##
- * @subpackage ##SUBPACKAGE##
- * @author ##NAME## <##EMAIL##>
- * @version SVN: $Id: Builder.php 6508 2009-10-14 06:28:49Z jwage $
- */
- class Bal_Invoice extends Base_Bal_Invoice
- {
-
- /**
- * Apply accessors and modifiers
- * @return
- */
- public function setUp ( ) {
- parent::setUp();
- }
-
- /**
- * Create a Invoice from a template
- * @param string $template
- * @param array $data [optiona]
- * @return Invoice
- */
- public static function createFromTemplate ( $template, array $data = array() ) {
- # Prepare
- $Connection = Bal_App::getDataConnection();
- $Invoice = null;
-
- # Wrap
- try {
- # Start
- $Connection->beginTransaction();
-
- # Prepare Invoice
- $Invoice = new Invoice();
-
- # Template Invoice
- $Invoice->useTemplate($template, $data);
-
- # Save Invoice
- $Invoice->save();
-
- # Generate File
- $Invoice->generateFile();
- $Invoice->save();
-
- # Done
- $Connection->commit();
- }
- catch ( Exception $Exception ) {
- # Revert
- $Connection->rollback();
-
- # Log the Event and Continue
- $Exceptor = new Bal_Exceptor($Exception);
- $Exceptor->log();
- }
-
- # Done
- return $Invoice;
- }
-
- /**
- * Shortcut Message Creation via Codes
- * @return string
- */
- public function useTemplate ( $template, array $data = array() ) {
- # Prepare
- $Locale = Bal_App::getLocale();
- $Invoice = $this;
-
- # Merge Data
- if ( !empty($data) ) {
- foreach ( $data as $key => $value )
- $Invoice->set($key, $value);
- }
-
- # Apply Config
- $config = Bal_App::getConfig('invoice', array());
- $this->config = $config;
-
- # Apply Currency
- $this->currency_code = Bal_App::getConfig('locale.currency', 'AUD');
-
- # Apply Template
- $this->_set('template', $template, false);
-
- # Handle Template
- $function = '_template'.magic_function($template);
- if ( method_exists($this, $function) ) {
- $this->$function();
- }
-
- # Chain
- return $Invoice;
- }
-
- protected function _templateUserInvoice ( ) {
- # All properties are manually set
-
- # Chain
- return $this;
- }
-
- /**
- * Backup our Invoice into the back table
- * @throws Doctrine_Exception
- * @return InvoiceDataBackup
- */
- public function backup ( ) {
- # Check
- if ( !$this->isValid() ) {
- throw new Doctrine_Exception('Cannot backup an invalid model');
- }
-
- return;
- # Prepare
- $Invoice = $this;
- $invoice = $Invoice->toArray(true);
-
- # Create
- $InvoiceDataBackup = new InvoiceDataBackup();
- $InvoiceDataBackup->Invoice = $Invoice;
- $InvoiceDataBackup->data = $invoice;
- $InvoiceDataBackup->save();
-
- # Return InvoiceBackup
- return $InvoiceDataBackup;
- }
-
- public function getPath ( ) {
- # Prepare
- $invoices_path = Bal_App::getConfig('invoices_path') . DIRECTORY_SEPARATOR;
-
- # Handle
- $name = $this->id.'-'.md5(serialize($this->toArray(false))); // $this->id.'-'.$this->title;
- $invoice_path = $invoices_path . $name . '.pdf';
-
- # Return
- return $invoice_path;
- }
-
- public function download ( ) {
- # Prepare
- $invoice_path = $this->getPath();
-
- # Download
- become_file_download($invoice_path);
-
- # Done
- die;
- }
-
- public static function getTemplatePath ( $template ) {
- # Prepare
- $templates_path = Bal_App::getConfig('templates_path') . DIRECTORY_SEPARATOR;
- # Handle
- $template_path = $templates_path . 'invoice-'.$template.'.pdf';
- # Return path
- return $template_path;
- }
-
- public function generateFile ( ) {
- # Prepare
- $Locale = Bal_App::getLocale();
- $Invoice = $this;
- $InvoiceArray = $this->toArray(true);
- $Invoice_path = $this->getPath();
- $template_path = self::getTemplatePath($this->template);
-
- # Setup PDF + Meta
- $Pdf = Zend_Pdf::load($template_path);
- $Pdf->properties['Author'] = $Locale->translate('invoice-author');
- $Pdf->properties['Title'] = $Locale->translate('invoice-title', $Invoice);
- $Page = $Pdf->pages[0];
-
- # Font
- $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER);
- $Page->setFont($font, 9);
-
- # Handle Matrix
- $template = $this->template;
- $function = '_matrix'.magic_function($template);
- if ( method_exists($this, $function) ) {
- $matrix = $this->$function();
- }
-
- # Translate Matrix
- foreach ( $matrix as $column => $details ) {
- # Fetch value
- $key = $column;
- $column = strtolower(str_replace('.','-',$key));
- $name = delve($details,'name',$column);
- $value = array_key_exists('value',$details) ? $details['value'] : delve($Invoice,$key,'');
-
- # Fetch type
- $type = delve($details,'type');
- if ( !$type ) {
- # Get field
- $field = delve($details,'field',$column);
- $Table = empty($details['table']) ? $this->getTable() : Doctrine::getTable($details['table']);
- $definition = $Table->getColumnDefinition($field);
- $type = delve($definition,'type');
-
- # Adjust
- if ( $type === 'enum' ) {
- $type = gettype($value);
- }
- elseif ( delve($definition,'extra.currency') ) {
- $type = 'currency';
- }
- }
-
- # Translate type
- if ( empty($type) ) $type = 'translate';
- $value = $Locale->translate_default('invoice-'.$name, array(
- 'value' => $Locale->$type($value),
- 'Invoice' => $InvoiceArray
- ),$Locale->$type($value));
-
- # Check translation
- $length = delve($details,'length');
- if ( $length && strlen($value) > $length ) {
- # Trim
- $value = substr($value,0,$length-4).' ...';
- }
-
- # Draw onto the PDF
- $Page->drawText($value, $details['position'][0], $details['position'][1]);
- }
-
- # Save PDF
- $Pdf->save($Invoice_path);
-
- # Prepare File
- $File = new File();
- $File->file = $Invoice_path;
- $File->url = Bal_App::getConfig('invoices_url') . DIRECTORY_SEPARATOR . $File->name;
-
- # Reset File
- Doctrine_Query::create()
- ->delete('File m')
- ->where('m.name = ?', $File->name)
- ->execute();
-
- # Save File
- $File->save();
- $this->File = $File;
-
- # Chain
- return $this;
- }
-
-
- protected function _matrixUserInvoice ( $Invoice ) {
- # Prepare
- $InvoiceItems = delve($Invoice,'InvoiceItems');
-
- # Set Matrix
- $matrix = array(
- # Invoice
- 'id' => array(
- 'position' => array(140,713),
- 'length' => 65
- ),
- 'price_total' => array(
- 'position' => array(190,436),
- 'length' => 70
- ),
-
- # Times
- 'created' => array(
- 'position' => array(405,713),
- 'length' => 65
- ),
- 'updated' => array(
- 'position' => array(220,748),
- 'length' => 65
- )
- );
-
- # Alter Matrix Depending on Code
- switch ( $code ) {
- case 'user_invoice':
- # Add Invoice Items
- $line_height = 15;
- foreach ( $InvoiceItems as $i => $InvoiceItem ) {
- # Title
- $matrix['invoiceitem-'.$InvoiceItem->id] = array(
- 'position' => array(150,519+$line_height*$i),
- 'length' => 55,
- 'value' => $InvoiceItem->title,
- 'type' => 'string'
- );
-
- # Cost
- $matrix['invoiceitem-'.$InvoiceItem->id] = array(
- 'position' => array(300,519+$line_height*$i),
- 'length' => 55,
- 'value' => $InvoiceItem->cost,
- 'type' => 'currency'
- );
- }
-
- # Done
- break;
-
- default:
- # Unkown
- throw new Zend_Exception('error-invoice-unknown_code');
- }
-
-
- # Return
- return $matrix;
- }
-
-
- /**
- * Ensure Messages
- * @param Doctrine_Event $Event
- * @return boolean success
- * @todo on postDelete remove messages that haven't been sent
- */
- public function ensureMessages($Event, $Event_type){
- # Check
- if ( !in_array($Event_type,array('postInsert')) ) {
- # Not designed for these events
- return null;
- }
-
- # Prepare
- $save = false;
-
- # Fetch
- $Invoice = $Event->getInvoker();
-
- # --------------------------
- # Messages
-
- # Create Invoice Insert Messages
- $Receivers = array(
- delve($Invoice,'UserFor'),
- delve($Invoice,'UserBy')
- );
- foreach ( $Receivers as $Receiver ) {
- $Message = new Message();
- $Message->UserFor = $Receiver;
- $Message->useTemplate('invoice-insert');
- $Message->save();
- }
-
- # --------------------------
-
- # Return save
- return $save;
- }
-
-
- /**
- * Ensure Totals
- * @param Doctrine_Event $Event
- * @return boolean success
- */
- public function ensureTotals($Event, $Event_type){
- # Check
- if ( !in_array($Event_type,array('preSave')) ) {
- # Not designed for these events
- return null;
- }
-
- # Fetch
- $Invoice = $Event->getInvoker();
-
- # --------------------------
- # Ensure
-
- # Apply Totals
- $Invoice->applyTotals();
-
- # --------------------------
-
- # Return true
- return true;
- }
-
- /**
- * Ensure Backup
- * @param Doctrine_Event $Event
- * @return boolean success
- */
- public function ensureBackup($Event, $Event_type){
- # Check
- if ( !in_array($Event_type,array('postSave')) ) {
- # Not designed for these events
- return null;
- }
-
- # Fetch
- $Invoice = $Event->getInvoker();
-
- # --------------------------
- # Ensure
-
- # Apply Totals
- $Invoice->backup();
-
- # --------------------------
-
- # Return false
- return false; // never save again
- }
-
- /**
- * Ensure Code
- * @param Doctrine_Event $Event
- * @return boolean success
- */
- public function ensureCode($Event, $Event_type){
- # Check
- if ( !in_array($Event_type,array('preInsert')) ) {
- # Not designed for these events
- return null;
- }
-
- # Prepare
- $save = false;
-
- # Fetch
- $Invoice = $Event->getInvoker();
-
- # --------------------------
- # Ensure
-
- # Check if code is set
- if ( !$Invoice->code ) {
- $Invoice->code = 'invoice-'.time();
- }
-
- # --------------------------
-
- # Return save
- return $save;
- }
-
- /**
- * Ensure Consistency
- * @param Doctrine_Event $Event
- * @return boolean wheter or not to save
- */
- public function ensure ( $Event, $Event_type ){
- return Bal_Doctrine_Core::ensure($Event,$Event_type,array(
- 'ensureCode',
- 'ensureTotals',
- 'ensureMessages',
- 'ensureBackup'
- ));
- }
-
-
- /**
- * preSave Event
- * @param Doctrine_Event $Event
- * @return
- */
- public function preSave ( $Event ) {
- # Prepare
- $result = true;
-
- # Ensure
- if ( self::ensure($Event, __FUNCTION__) ) {
- // no need
- }
-
- # Done
- return method_exists(get_parent_class($this),$parent_method = __FUNCTION__) ? parent::$parent_method($Event) : $result;
- }
-
- /**
- * postSave Event
- * @param Doctrine_Event $Event
- * @return
- */
- public function postSave ( $Event ) {
- # Prepare
- $Invoker = $Event->getInvoker();
- $result = true;
-
- # Ensure
- if ( self::ensure($Event, __FUNCTION__) ) {
- $Invoker->save();
- }
-
- # Done
- return method_exists(get_parent_class($this),$parent_method = __FUNCTION__) ? parent::$parent_method($Event) : $result;
- }
-
- /**
- * postInsert Event
- * @param Doctrine_Event $Event
- * @return
- */
- public function postInsert ( $Event ) {
- # Prepare
- $result = true;
-
- # Ensure
- if ( self::ensure($Event, __FUNCTION__) ) {
- // no need
- }
-
- # Done
- return method_exists(get_parent_class($this),$parent_method = __FUNCTION__) ? parent::$parent_method($Event) : $result;
- }
-
-
- /**
- * preInsert Event
- * @param Doctrine_Event $Event
- * @return
- */
- public function preInsert ( $Event ) {
- # Prepare
- $result = true;
-
- # Ensure
- if ( self::ensure($Event, __FUNCTION__) ) {
- // no need
- }
-
- # Done
- return method_exists(get_parent_class($this),$parent_method = __FUNCTION__) ? parent::$parent_method($Event) : $result;
- }
-
-
- # ========================
- # Payment Helpers
-
- /**
- * Process the Payment and Save changes
- * @param Bal_Payment_Model_Invoice
- * @return true
- */
- public function processPaymentAndSave ( Bal_Payment_Model_Invoice $PaymentInvoice ) {
- # Prepare
- $Invoice = $this;
-
- # Apply Payment Data
- $Invoice->payment_status = $PaymentInvoice->payment_status;
- $Invoice->payment_fee = $PaymentInvoice->payment_fee;
- $Invoice->paid_at = doctrine_timestamp($PaymentInvoice->paid_at);
-
- # Propogate to Invoice
- switch ( $Invoice->payment_status ) {
- case 'completed':
- $Invoice->status = 'completed';
- break;
-
- default:
- break;
- }
-
- # Save Invoice
- $Invoice->save();
-
- # Return true
- return true;
- }
-
- /**
- * Convert us into the Payment Model Representation
- * @return Bal_Payment_Model_Invoice
- */
- public function generatePaymentModel ( ) {
- # Prepare
- $Invoice = $this;
- $invoice = $Invoice->toArray(false);
-
- # Prepare PaymentInvoice
- $PaymentInvoice = new Bal_Payment_Model_Invoice();
-
- # Adjust Keys
- $keys = $PaymentInvoice->getKeys(); array_keys_keep($invoice, $keys);
- $invoice['id'] = $Invoice->code;
-
- # Apply the Payer
- $invoice['Payer'] = $Invoice->UserFor->generatePaymentModel();
-
- # Apply the InvoiceItems
- $invoice['InvoiceItems'] = array();
- foreach ( $Invoice->InvoiceItems as $InvoiceItem ) {
- $invoice['InvoiceItems'][] = $InvoiceItem->generatePaymentModel();
- }
-
- # Apply the Invoice
- $PaymentInvoice->merge($invoice);
-
- # Apply the Totals
- $PaymentInvoice->applyTotals();
-
- # Validate
- $PaymentInvoice->validate();
-
- # Return the PaymentInvoice
- return $PaymentInvoice;
- }
-
- /**
- * Calculate totals for ourself
- * @return true
- */
- public function applyTotals ( ) {
- # Prepare
- $Invoice = $this;
-
- # Apply Totals
- Bal_Payment_Model_Invoice::applyTotalsModel($Invoice);
-
- # Return true
- return true;
- }
-
- # ========================
- # CRUD Helpers
-
-
- /**
- * Fetch all the records for public access
- * @version 1.0, April 12, 2010
- * @return mixed
- */
- public static function fetch ( array $params = array() ) {
- # Prepare
- Bal_Doctrine_Core::prepareFetchParams($params,array('Invoice','User','UserFor','UserFrom'));
- extract($params);
-
- # Query
- $Query = Doctrine_Query::create()
- ->select('Invoice.*, InvoiceItem.*, Media.*')
- ->from('Invoice, Invoice.InvoiceItems InvoiceItem')
- ->orderBy('Invoice.created_at ASC');
-
- # Criteria
- if ( $User ) {
- $identifier = Bal_Doctrine_Core::resolveIdentifier('User',$User);
- $Query->andWhere(
- 'Invoice.UserFor.'.$identifier['column'].' = ? OR '.
- 'Invoice.UserFrom.'.$identifier['column'].' = ?',
- array($identifier['value'],$identifier['value'])
- );
- }
- if ( $UserFor ) {
- $identifier = Bal_Doctrine_Core::resolveIdentifier('User',$UserFor);
- $Query->andWhere(
- 'Invoice.UserFor.'.$identifier['column'].' = ?',
- $identifier['value']
- );
- }
- if ( $UserFrom ) {
- $identifier = Bal_Doctrine_Core::resolveIdentifier('User',$UserFrom);
- $Query->andWhere(
- 'Invoice.UserFrom.'.$identifier['column'].' = ?',
- $identifier['value']
- );
- }
- if ( $Invoice ) {
- $identifier = Bal_Doctrine_Core::resolveIdentifier('Invoice',$Invoice);
- $Query->andWhere(
- 'Invoice.'.$identifier['column'].' = ?',
- $identifier['value']
- );
- }
-
- # Fetch
- $result = Bal_Doctrine_Core::prepareFetchResult($params,$Query,'Invoice');
-
- # Done
- return $result;
- }
-
- }