OpenTools VirtueMart TaxReport ReportIn this tutorial, I will show how a plugin of type vmextended can be used to add your own custom view to the VirtueMart backend. As an example, we will implement a view that generates a simple tax report (for each tax rate we will show the amount of taxes charged in the selected period). In the first step, the view will not offer any configuration settings. The example contains no copyright and license statements to make it easier to read. You should add them yourself if you build upon this example. The example plugin developed here is released under the GPL v3+.

The full code for the example in this tutorial can be downloaded HERE (plg_vmextended_taxreport_v0.1.zip, 22kB).

The view will have the internal name "taxreport" and will be implemented as a Joomla plugin of type vmextended and its files are located in plugins/vmextended/taxreport. The view will be displayed in the backend when the URL administrator/index.php?option=com_virtuemart&view=taxreport is called.

 

 

OpenTools VirtueMart TaxReport FileStructure

In typical Joomla fashion, we will set up a full MVC (Model-View-Controller) structure within the plugin directory (see the file structure on the right). The corresponding code and file structure is not much different from a normal Joomla component, except that every now and then we need to tell the classes about the appropriate model/view/template pathes, since with our approach those are not in the usual places, but inside the plugin's directory.

The general structure and flow of the plugin is as follows:

  • The vmextended plugin called "taxreport" (file plugins/vmextended/taxreport/taxreport.php) provides a function onVmAdminController that is called when a view is requested that is not provided by the VM core. That function loads the corresponding controller class VirtuemartControllerTaxReport.
  • The VirtuemartControllerTaxReport controller class (file plugins/vmextended/taxreport/controllers/taxreport.php) handles all requests for the tax report view, i.e. it is the URL handler that simply relays the request to the corresponding view. The display function for the default view is already available, so we don't have to implement it ourselves. All we have to do in a first step is to set the appropriate view path to tell VM to look in the plugin directory for the taxreport view.
  • The view itself is provided in a class VirtuemartViewTaxReport (file plugins/vmextended/taxreport/views/taxreport/view.html.php) and needs to set the corresponding template path (plugins/vmextended/taxreport/views/taxreport/tmpl/) and provide a display($tmpl) function that actually renders the view.
  • The data used by the view is provided by a model class VirtuemartModelTaxReport (file plugins/vmextended/taxreport/models/taxreport.php). This is the place where the actual database queries are set up, executed and the result returned to the view. This way the view does not have to care about where the data comes from, and the model is only responsible for retrieving (and/or storing) the data.
  • The view will be added as a menu item to the VirtueMart backend so it is easily accessible. Unfortunately, VirtueMart does not yet support dynamically adding menu items to its backend, so we have to create a hardcoded database entry. Its title will not be translated (because translateions are only loaded when the view is actually called) and it wil also be shown when the plugin is disabled. 

1. The plugin itself (plugins/taxreport/taxreport.php): setting up pathes and loading the controller

The plugin is a normal VirtueMart vmextended plugin, derived from the vmExtendedPlugin class. The constructor needs to load the translations (not done automatically for vmextended plugins), and the plugin needs to implement the onVmAdminController function, which loads the corresponding Controller class. Instantiating the controller class will be done by the VM core code, the plugin just needs to make sure the class is actually defined in memory: 

  1. <?php
  2. if( !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
  3.  
  4. defined ('VMPATH_PLUGINLIBS') or define ('VMPATH_PLUGINLIBS', JPATH_VM_PLUGINS);
  5. if (!class_exists('vmExtendedPlugin')) require(VMPATH_PLUGINLIBS . DS . 'vmextendedplugin.php');
  6.  
  7. class plgVmExtendedTaxReport extends vmExtendedPlugin {
  8.  
  9. public function __construct (&amp;$subject, $config=array()) {
  10. parent::__construct($subject, $config);
  11. $this->_path = JPATH_PLUGINS.DS.'vmextended'.DS.$this->getName();
  12. JPlugin::loadLanguage('plg_vmextended_'.$this->getName());
  13. }
  14.  
  15. public function onVmAdminController ($controller) {
  16. if ($controller = $this->getName()) {
  17. VmModel::addIncludePath($this->_path . DS . 'models');
  18. // TODO: Make sure the model exists. We probably should find a better way to load this automatically!
  19. // Currently, some path config seems missing, so the model is not found by default.
  20. require_once($this->_path.DS.'models'.DS.'taxreport.php');
  21. require_once($this->_path.DS.'controllers'.DS.'taxreport.php');
  22. return true;
  23. }
  24. }
  25. }

2. The Controller (plugins/taxreport/controllers/taxreport.php)

The controller is the first thing that is called whenever VM detects that the taxreport view is requested. It's purpose is to handle the different tasks (typical tasks are save, cancel, export). The default task is already properly set up in the base class to display the taxreport view, so all we have to do is to add the proper view path, since we have the view not in the default VM location, but inside the plugin directory:

  1. <?php
  2. if( !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
  3.  
  4. defined ('VMPATH_ADMIN') or define ('VMPATH_ADMIN', JPATH_VM_ADMINISTRATOR);
  5. if(!class_exists('VmController')) require(VMPATH_ADMIN.DS.'helpers'.DS.'vmcontroller.php');
  6.  
  7. class VirtuemartControllerEuRecap extends VmController {
  8.  
  9. function __construct(){
  10. parent::__construct();
  11. // Add the proper view pathes...
  12. $this->addViewPath(JPATH_PLUGINS.DS . 'vmextended' . DS . 'taxreport' . DS . 'views');
  13. }
  14.  
  15. }

3. The tax data model (plugins/taxreport/models/taxreport.php)

Before we create the actual view, we need to design which data we want to display and how it is retrieved from the database. For the tax report, we want to display the following columns in our report:

Billing CountryTax RuleTax RateOrdersNet revenueTaxes

The corresponding information is split in the database over multiple tables, which we need to join:

  • [prefix]_virtuemart_orders: Base table for all orders
  • [prefix]_virtuemart_order_userinfos: Columns virtuemart_country_id; Joined on virtuemart_order_id column.
  • [prefix]_virtuemart_countries: Column country_name; Joined with userinfos table on column virtuemart_country_id.
  • [prefix]_virtuemart_order_items: product_priceWithoutTax, product_quantity; Joined with orders on virtuemart_order_id
  • [prefix]_virtuemart_order_calc_rules: Columns calc_rule_name, calc_kind, calc_amount, calc_value, calc_currency; Joined with orderitems on virtuemart_order_item_id

From this database structure, we can first write the SQL statement to retrieve the data in the desired format:

  1. SELECT
  2. `c`.`country_name` AS `country`,
  3. `cr`.`calc_rule_name` AS `taxrule`,
  4. `cr`.`calc_value` AS `taxrate`,
  5. COUNT(DISTINCT `o`.`virtuemart_order_id`) AS `ordercount`,
  6. SUM(`oi`.`product_quantity` * `oi`.`product_priceWithoutTax`) AS `sum_revenue_net`,
  7. SUM(`cr`.`calc_amount`) AS `sum_order_tax`
  8. FROM
  9. j25_virtuemart_orders AS o
  10. LEFT JOIN j25_virtuemart_order_userinfos AS ui ON `o`.`virtuemart_order_id` = `ui`.`virtuemart_order_id`
  11. LEFT JOIN j25_virtuemart_countries AS c ON `ui`.`virtuemart_country_id` = `c`.`virtuemart_country_id`
  12. INNER JOIN j25_virtuemart_order_items AS `oi` ON `o`.`virtuemart_order_id` = `oi`.`virtuemart_order_id`
  13. INNER JOIN j25_virtuemart_order_calc_rules AS cr ON `oi`.`virtuemart_order_item_id` = `cr`.`virtuemart_order_item_id`
  14. WHERE
  15. (`o`.`order_status` = "C" OR `o`.`order_status` = "S" )
  16. AND `ui`.`address_type` = "BT"
  17. AND DATE( o.created_on ) BETWEEN "2015-03-22 00:00:00" AND "2015-03-23 00:00:00"
  18. GROUP BY `c`.`virtuemart_country_id`, `cr`.`virtuemart_calc_id`, `cr`.`calc_currency`;

Finally, we can create the model class (plugins/taxreport/models/taxreport.php), which will extract the data from the database using the SQL derived above and return it to the view for proper display:

  1. <?php
  2. if (!defined ('_JEXEC')) die('Direct Access to ' . basename (__FILE__) . ' is not allowed.');
  3.  
  4. if (!class_exists ('VmModel')) require(VMPATH_ADMIN . DS . 'helpers' . DS . 'vmmodel.php');
  5.  
  6. class VirtuemartModelTaxReport extends VmModel {
  7. public $from_period = '';
  8. public $until_period = '';
  9.  
  10. function __construct () {
  11. parent::__construct ();
  12. $this->setMainTable ('orders');
  13.  
  14. $this->removevalidOrderingFieldName ('virtuemart_order_id');
  15. $this->addvalidOrderingFieldName (array('`country`', '`taxrule`', '`taxrate`', '`ordercount`', '`sum_revenue_net`', '`sum_order_tax`'));
  16. $this->_selectedOrdering = '`country`';
  17. }
  18.  
  19.  
  20. function correctTimeOffset(&amp;$inputDate) {
  21. $config = JFactory::getConfig();
  22. $this->siteOffset = $config->get('offset');
  23. $date = new JDate($inputDate);
  24. $date->setTimezone($this->siteTimezone);
  25. $inputDate = $date->format('Y-m-d H:i:s',true);
  26. }
  27.  
  28. function setPeriod () {
  29. $this->from_period = vRequest::getVar ('from_period');
  30. $this->until_period = vRequest::getVar ('until_period');
  31.  
  32. $config = JFactory::getConfig();
  33. $siteOffset = $config->get('offset');
  34. $this->siteTimezone = new DateTimeZone($siteOffset);
  35.  
  36. $this->correctTimeOffset($this->from_period);
  37. $this->correctTimeOffset($this->until_period);
  38. }
  39.  
  40. function getTaxes() {
  41. $user = JFactory::getUser();
  42. if($user->authorise('core.admin', 'com_virtuemart') or $user->authorise('core.manager', 'com_virtuemart')){
  43. $vendorId = vRequest::getInt('virtuemart_vendor_id');
  44. } else {
  45. $vendorId = VmConfig::isSuperVendor();
  46. }
  47. $this->setPeriod();
  48.  
  49. $orderstates = vRequest::getVar ('order_status_code', array('C','S'));
  50.  
  51. $mainTable = "`#__virtuemart_orders` AS `o`";
  52. $joins = array();
  53. $joins[] = "LEFT JOIN #__virtuemart_order_userinfos AS `ui` ON `o`.`virtuemart_order_id` = `ui`.`virtuemart_order_id` ";
  54. $joins[] = "LEFT JOIN #__virtuemart_countries AS `c` ON `ui`.`virtuemart_country_id` = `c`.`virtuemart_country_id` ";
  55. $joins[] = "INNER JOIN #__virtuemart_order_items AS `oi` ON `o`.`virtuemart_order_id` = `oi`.`virtuemart_order_id` ";
  56. $joins[] = "INNER JOIN #__virtuemart_order_calc_rules AS `cr` ON `oi`.`virtuemart_order_item_id` = `cr`.`virtuemart_order_item_id` ";
  57.  
  58. $select = array();
  59. $select[] = "`c`.`country_name` AS `country`";
  60. $select[] = "`cr`.`calc_rule_name` AS `taxrule`";
  61. $select[] = "`cr`.`calc_value` AS `taxrate`";
  62. $select[] = "COUNT(DISTINCT `o`.`virtuemart_order_id`) as `ordercount`";
  63. $select[] = "SUM(`oi`.`product_quantity` * `oi`.`product_priceWithoutTax`) AS `sum_revenue_net`";
  64. $select[] = "SUM(`cr`.`calc_amount`) AS `sum_order_tax`";
  65.  
  66. $where = array();
  67. $where[] = '`ui`.`address_type` = "BT"'; // Otherwise, amounts will be double due to summation!
  68. // Order status:
  69. $ostatus = array();
  70. foreach ($orderstates as $s) {
  71. $ostatus[] = '`o`.`order_status` = "' . $s . '"';
  72. }
  73. if ($ostatus) {
  74. $where[] = "(" . join(" OR ", $ostatus) . ")";
  75. }
  76. $where[] = ' DATE( o.created_on ) BETWEEN "' . $this->from_period . '" AND "' . $this->until_period . '" ';
  77.  
  78. $groupbys = array("`c`.`virtuemart_country_id`", "`cr`.`virtuemart_calc_id`", "`cr`.`calc_currency`");
  79.  
  80. $selectString = join(', ', $select) . ' FROM ' . $mainTable;
  81. $joinedTables = join('', $joins);
  82. $whereString = 'WHERE ' . join(' AND ', $where);
  83. $groupBy = "GROUP BY ".join(', ', $groupbys);
  84. $orderBy = $this->_getOrdering ();
  85. return $this->exeSortSearchListQuery (1, $selectString, $joinedTables, $whereString, $groupBy, $orderBy);
  86. }
  87.  
  88. }

4. The taxreport view (plugins/taxreport/views/taxreport/view.html.php)

Now that we have created the model to retrieve the data, we can finally display it in a view. Again, we have to adjust a few pathes, extract the data from the model and then simply call the template:

  1. <?php
  2. if( !defined( '_JEXEC' ) ) die('Restricted access');
  3.  
  4. if(!defined('VM_VERSION') or VM_VERSION < 3){
  5. // VM2 has class VmView instead of VmViewAdmin:
  6. if(!class_exists('VmView')) require(VMPATH_ADMIN.DS.'helpers'.DS.'vmview.php');
  7. class VmViewAdmin extends VmView {}
  8. defined ('VMPATH_PLUGINLIBS') or define ('VMPATH_PLUGINLIBS', JPATH_VM_PLUGINS);
  9. } else {
  10. if(!class_exists('VmViewAdmin')) require(VMPATH_ADMIN.DS.'helpers'.DS.'vmviewadmin.php');
  11. }
  12.  
  13. class VirtuemartViewTaxReport extends VmViewAdmin {
  14. function __construct(){
  15. parent::__construct();
  16. $this->_addPath('template', JPATH_PLUGINS.DS . 'vmextended' . DS . 'taxreport' . DS . 'views' . DS . $this->getName() . DS . 'tmpl');
  17. }
  18.  
  19. function display($tpl = null){
  20.  
  21. if (!class_exists('VmHTML')) require(VMPATH_ADMIN . DS . 'helpers' . DS . 'html.php');
  22. if (!class_exists('CurrencyDisplay')) require(VMPATH_ADMIN . DS . 'helpers' . DS . 'currencydisplay.php');
  23.  
  24. vRequest::setvar('task','');
  25. $this->SetViewTitle('TAXREPORT');
  26.  
  27. $model = VmModel::getModel();
  28. $this->addStandardDefaultViewLists($model);
  29. $myCurrencyDisplay = CurrencyDisplay::getInstance();
  30.  
  31. $taxData = $model->getTaxes();
  32. $this->assignRef('report', $taxData);
  33.  
  34. $orderstatusM =VmModel::getModel('orderstatus');
  35. $orderstates = vRequest::getVar ('order_status_code', array('C','S'));
  36. $this->lists['state_list'] = $orderstatusM->renderOSList($orderstates,'order_status_code',TRUE);
  37.  
  38. $this->lists['select_date'] = $model->renderDateSelectList();
  39.  
  40. $this->assignRef('from_period', $model->from_period);
  41. $this->assignRef('until_period', $model->until_period);
  42.  
  43. $this->pagination = $model->getPagination();
  44.  
  45. parent::display($tpl);
  46. }
  47.  
  48. }

5. The view template (plugins/vmextended/taxreport/views/taxreport/tmpl/default.php)

Finally, the view template creates the HTML code to display the view. It gets all the variables that we set in the view's display function.

  1. <?php
  2. if( !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
  3.  
  4. AdminUIHelper::startAdminArea($this);
  5.  
  6. JHtml::_('behavior.framework', true);
  7. if (!class_exists('CurrencyDisplay'))
  8. require(VMPATH_ADMIN . DS . 'helpers' . DS . 'currencydisplay.php');
  9. $myCurrencyDisplay = CurrencyDisplay::getInstance();
  10. ?>
  11.  
  12. <form action="index.php" method="post" name="adminForm" id="adminForm">
  13.  
  14. <div id="header">
  15. <h2><?php echo vmText::sprintf('VMEXT_TAXREPORT_VIEW_TITLE_DATE', vmJsApi::date( $this->from_period, 'LC',true) , vmJsApi::date( $this->until_period, 'LC',true) ); ?></h2>
  16.  
  17. <div id="filterbox">
  18. <table>
  19. <tr>
  20. <td align="left" width="100%">
  21. <?php
  22. echo vmText::_('COM_VIRTUEMART_ORDERSTATUS') . $this->lists['state_list'];
  23. echo vmText::_('COM_VIRTUEMART_REPORT_FROM_PERIOD') . vmJsApi::jDate($this->from_period, 'from_period');
  24. echo vmText::_('COM_VIRTUEMART_REPORT_UNTIL_PERIOD') . vmJsApi::jDate($this->until_period, 'until_period'); ?>
  25. <button class="btn btn-small" onclick="this.form.submit();"><?php echo vmText::_('COM_VIRTUEMART_GO'); ?>
  26. </button>
  27. </td>
  28. </tr>
  29. </table>
  30. </div>
  31. <div id="resultscounter">
  32. <?php if ($this->pagination) echo $this->pagination->getResultsCounter();?>
  33. </div>
  34. </div>
  35.  
  36. <div id="editcell">
  37. <table class="adminlist table table-striped" cellspacing="0" cellpadding="0">
  38. <thead>
  39. <tr>
  40. <th><?php echo $this->sort('`country`', 'VMEXT_TAXREPORT_COUNTRY') ; ?></th>
  41. <th><?php echo $this->sort('`taxrule`', 'VMEXT_TAXREPORT_TAXNAME') ; ?></th>
  42. <th><?php echo $this->sort('`taxrate`', 'VMEXT_TAXREPORT_TAXRATE') ; ?></th>
  43. <th><?php echo $this->sort('`ordercount`', 'VMEXT_TAXREPORT_ORDERS') ; ?></th>
  44. <th><?php echo $this->sort('`sum_revenue_net`', 'VMEXT_TAXREPORT_ORDERREVENUENET') ; ?></th>
  45. <th><?php echo $this->sort('`sum_order_tax`', 'VMEXT_TAXREPORT_ORDERTAXES') ; ?></th>
  46. </tr>
  47. </thead>
  48. <tbody>
  49. <?php
  50. $i = 0;
  51. foreach ($this->report as $r) { ?>
  52. <tr class="row<?php echo $i;?>">
  53. <td align="center"><?php echo $r['country']; ?></td>
  54. <td align="center"><?php echo $r['taxrule']; ?></td>
  55. <td align="center"><?php echo round($r['taxrate'], 4) . " %"; ?></td>
  56. <td align="center"><?php echo $r['ordercount']; ?></td>
  57. <td align="right"><?php echo $myCurrencyDisplay->priceDisplay($r['sum_revenue_net']); ?></td>
  58. <td align="right"><?php echo $myCurrencyDisplay->priceDisplay($r['sum_order_tax']); ?></td>
  59. </tr>
  60. <?php
  61. $i = 1-$i;
  62. } ?>
  63. </tbody>
  64. <tfoot>
  65. <tr>
  66. <td colspan="10">
  67. <?php if ($this->pagination) echo $this->pagination->getListFooter(); ?>
  68. </td>
  69. </tr>
  70. </tfoot>
  71. </table>
  72. </div>
  73.  
  74. <?php echo $this->addStandardHiddenToForm(); ?>
  75. </form>
  76.  
  77. <?php AdminUIHelper::endAdminArea(); ?>

6. Creating an admin menu entry in the VirtueMart Backend

Now that we have created the full plugin with the view, model and controller, we of course also want to have a menu enty in the VirtueMart backend admin area to make the view easily available. VirtueMart currently does not provide a way to dynamically add menu entries to the backend menu, so we will have to create database entries for the menu item when the plugin is installed. As a downside, the menu item will also be visible if the plugin is disabled. VirtueMart also does not load vmextended plugins and their translations, unless an unknown view is requested. So the translatable menu item is not possible, because the translation will only be loaded when the view is actually called. To solve this, we will load the translation when the plugin is installed and write the string directly into the database.

  1. <?php
  2. defined('_JEXEC') or die('Restricted access');
  3.  
  4. defined('DS') or define('DS', DIRECTORY_SEPARATOR);
  5. if (!class_exists( 'VmConfig' ))
  6. require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php');
  7.  
  8. class plgVmExtendedTaxReportInstallerScript
  9. {
  10. public function postflight ($type, $parent = null) {
  11. JPlugin::loadLanguage('plg_vmextended_taxreport');
  12. $db = JFactory::getDBO();
  13. $db->setQuery("SELECT `id` FROM `#__virtuemart_adminmenuentries` WHERE `view` = 'taxreport'");
  14. $exists = $db->loadResult();
  15. if (!$exists) {
  16. $q = "INSERT INTO `#__virtuemart_adminmenuentries` (`module_id`, `name`, `link`, `depends`, `icon_class`, `ordering`, `published`, `tooltip`, `view`, `task`) VALUES
  17. (2, '" . vmText::_('COM_VIRTUEMART_TAXREPORT') . "', '', '', 'vmicon vmicon-16-report', 25, 1, '', 'taxreport', '')";
  18. $db->setQuery($q);
  19. $db->query();
  20. }
  21. }
  22.  
  23. public function install(JAdapterInstance $adapter)
  24. {
  25. $db = JFactory::getDBO();
  26. $db->setQuery('update #__extensions set enabled = 1 where type = "plugin" and element = "taxreport" and folder = "vmextended"');
  27. $db->query();
  28. return True;
  29. }
  30.  
  31. public function uninstall(JAdapterInstance $adapter)
  32. {
  33. $db = JFactory::getDBO();
  34. $q = "DELETE FROM `#__virtuemart_adminmenuentries` WHERE `view` = 'taxreport' AND `task` = '' AND `module_id` = 2";
  35. $db->setQuery($q);
  36. $db->query();
  37. }
  38. }

 7. The final view in the VirtueMart Backend

This is how the tax report view we developed above actually looks like in the VirtueMart backend. Notice the "Tax report" menu item in the "Orders & Shoppers" section on the left.

OpenTools VirtueMart TaxReport Report

Of course, the view is not perfect and cannot be configured, but it should serve as a nice example how VirtueMart can be easily extended using normal plugins of type vmextended.

If you want to look further and see an example how configuration options can be added to such plugins, please take a look at our "EU Sales Reports" plugin.