first commit

This commit is contained in:
2025-03-12 17:06:23 +01:00
commit 2241f7131f
13185 changed files with 1692479 additions and 0 deletions

View File

@@ -0,0 +1,190 @@
<?php
/**
* Subclass for representing a row from the 'st_tax' table.
*
*
*
* @package plugins.stTaxPlugin.lib.model
*/
class Tax extends BaseTax
{
protected $prevVat = null;
/**
* Kraj dostawy
*
* @var Countries
*/
protected $deliveryCountry = null;
public function getIsSystemDefault()
{
return parent::getIsSystemDefault() || $this->getIsDefault();
}
public function setEditIsDefault($v)
{
$this->setIsDefault($v);
}
public function isSystemDefault()
{
return parent::getIsSystemDefault();
}
public function __sleep()
{
return array_keys($this->toArray(BasePeer::TYPE_FIELDNAME));
}
public function __wakeup()
{
$this->setNew(false);
$this->resetModified();
}
public function __serialize()
{
return $this->toArray(BasePeer::TYPE_FIELDNAME);
}
public function __unserialize(array $data)
{
$this->fromArray($data, BasePeer::TYPE_FIELDNAME);
$this->setNew(false);
$this->resetModified();
}
/**
* Obsługa domyślności funkcji VAT
*
* @author Marcin Butlak <marcin.butlak@sote.pl>
*
* @param unknown_type $con
*/
public function save($con = null)
{
if (($this->isColumnModified(TaxPeer::IS_DEFAULT)) && ($this->getIsDefault()))
{
$c = new Criteria();
$c->add(TaxPeer::IS_DEFAULT, 1);
$tax = TaxPeer::doSelectOne($c);
if ($tax)
{
$tax->setIsDefault(false);
$tax->save();
}
}
$ret = parent::save($con);
TaxPeer::clearCache();
return $ret;
}
public function delete($con = null)
{
$ret = parent::delete($con);
TaxPeer::clearCache();
return $ret;
}
/**
* Zwraca stawkę VAT dla kraju dostawy
*
* @return string|null Stawka VAT [%]
*/
public function getTaxRateByCountry()
{
$country = $this->getDeliveryCountry();
$config = stConfig::getInstance('stShopInfoBackend');
if (stTax::getIsCustomerEuTaxEnabled() && null !== $country && $country->getIsoA2() != $config->get('country') && isset($this->rates_by_country[$country->getIsoA2()]))
{
return $this->rates_by_country[$country->getIsoA2()];
}
return null;
}
/**
*
* Przeciążenie metody - zapamiętywanie poprzedniej stawki VAT
*
* @param float $v Stawka VAT
*
* @author Marcin Butlak <marcin.butlak@sote.pl>
*/
public function setVat($v)
{
if (!$this->isColumnModified(TaxPeer::VAT) && !$this->isNew())
{
$this->prevVat = $this->getVat();
}
parent::setVat($v);
}
public function getDefaultTaxRate()
{
return parent::getVat();
}
public function getVat()
{
$vat = parent::getVat();
$countryTaxRate = $this->getTaxRateByCountry();
return $countryTaxRate ? $countryTaxRate : $vat;
}
/**
* Wyświetlenie nazwy zamiast id
*
* @return unknown
*/
public function __toString()
{
return $this->getVat() . '%';
}
/**
* Zwraca kraj dostawy
*
* @return Countries
*/
public function getDeliveryCountry()
{
if (null === $this->deliveryCountry && stConfig::getInstance('stTaxBackend')->get('is_customer_eu_tax_enabled'))
{
$id = sfContext::getInstance()->getUser()->getAttribute('delivery_country', null, stDeliveryFrontend::SESSION_NAMESPACE);
$this->deliveryCountry = CountriesPeer::retrieveById($id);
}
return $this->deliveryCountry;
}
/**
* Ustawia kraj dostawy
*
* @param Countries $deliveryCountry Kraj dostawy
*
* @return self
*/
public function setDeliveryCountry(Countries $deliveryCountry = null)
{
$this->deliveryCountry = $deliveryCountry;
return $this;
}
}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Subclass for performing query and update operations on the 'st_tax' table.
*
*
*
* @package plugins.stTaxPlugin.lib.model
*/
class TaxPeer extends BaseTaxPeer
{
/**
* Zwraca domyślną stawkę VAT
*
* @param Criteria $c
* @param Connection $con
* @return Tax
*/
public static function doSelectDefaultOne(Criteria $c, $con = null)
{
$c = clone $c;
$c->add(self::IS_DEFAULT, true);
$tax = self::doSelectOne($c);
return $tax ? $tax : self::doSelectOne(new Criteria());
}
/**
* Zwraca stawkę VAT po jej wartości
*
* @param string $value Wartość stawki VAT
* @return Tax
*/
public static function retrieveByTax($value)
{
return stTax::getByValue($value);
}
/**
* Zwraca listę aktywnych stawek VAT
*
* @return Tax[]
*/
public static function doSelectActive()
{
$c = new Criteria();
$c->add(self::IS_ACTIVE, true);
$rs = self::doSelectRS($c);
$results = array();
while ($rs->next())
{
$tax = new Tax();
$tax->hydrate($rs);
$results[$tax->getId()] = $tax;
}
return $results;
}
public static function clearCache()
{
$cache = new stFunctionCache('stTax');
$cache->removeAll();
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* This class adds structure of 'st_tax' table to 'propel' DatabaseMap object.
*
*
*
* These statically-built map classes are used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package plugins.stTaxPlugin.lib.model.map
*/
class TaxMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stTaxPlugin.lib.model.map.TaxMapBuilder';
/**
* The database map.
*/
private $dbMap;
/**
* Tells us if this DatabaseMapBuilder is built so that we
* don't have to re-build it every time.
*
* @return boolean true if this DatabaseMapBuilder is built, false otherwise.
*/
public function isBuilt()
{
return ($this->dbMap !== null);
}
/**
* Gets the databasemap this map builder built.
*
* @return the databasemap
*/
public function getDatabaseMap()
{
return $this->dbMap;
}
/**
* The doBuild() method builds the DatabaseMap
*
* @return void
* @throws PropelException
*/
public function doBuild()
{
$this->dbMap = Propel::getDatabaseMap('propel');
$tMap = $this->dbMap->addTable('st_tax');
$tMap->setPhpName('Tax');
$tMap->setUseIdGenerator(true);
$tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('VAT', 'Vat', 'double', CreoleTypes::DECIMAL, true, 5);
$tMap->addColumn('IS_DEFAULT', 'IsDefault', 'boolean', CreoleTypes::BOOLEAN, true, null);
$tMap->addColumn('RATES_BY_COUNTRY', 'RatesByCountry', 'array', CreoleTypes::VARCHAR, false, 2048);
$tMap->addColumn('IS_ACTIVE', 'IsActive', 'boolean', CreoleTypes::BOOLEAN, true, null);
$tMap->addColumn('VAT_NAME', 'VatName', 'string', CreoleTypes::VARCHAR, true, 45);
$tMap->addColumn('IS_SYSTEM_DEFAULT', 'IsSystemDefault', 'boolean', CreoleTypes::BOOLEAN, true, null);
$tMap->addColumn('UPDATE_RESUME', 'UpdateResume', 'array', CreoleTypes::VARCHAR, false, 64);
} // doBuild()
} // TaxMapBuilder

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,754 @@
<?php
/**
* Base static class for performing query and update operations on the 'st_tax' table.
*
*
*
* @package plugins.stTaxPlugin.lib.model.om
*/
abstract class BaseTaxPeer {
/** the default database name for this class */
const DATABASE_NAME = 'propel';
/** the table name for this class */
const TABLE_NAME = 'st_tax';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'plugins.stTaxPlugin.lib.model.Tax';
/** The total number of columns. */
const NUM_COLUMNS = 8;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the ID field */
const ID = 'st_tax.ID';
/** the column name for the VAT field */
const VAT = 'st_tax.VAT';
/** the column name for the IS_DEFAULT field */
const IS_DEFAULT = 'st_tax.IS_DEFAULT';
/** the column name for the RATES_BY_COUNTRY field */
const RATES_BY_COUNTRY = 'st_tax.RATES_BY_COUNTRY';
/** the column name for the IS_ACTIVE field */
const IS_ACTIVE = 'st_tax.IS_ACTIVE';
/** the column name for the VAT_NAME field */
const VAT_NAME = 'st_tax.VAT_NAME';
/** the column name for the IS_SYSTEM_DEFAULT field */
const IS_SYSTEM_DEFAULT = 'st_tax.IS_SYSTEM_DEFAULT';
/** the column name for the UPDATE_RESUME field */
const UPDATE_RESUME = 'st_tax.UPDATE_RESUME';
/** The PHP to DB Name Mapping */
private static $phpNameMap = null;
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('Id', 'Vat', 'IsDefault', 'RatesByCountry', 'IsActive', 'VatName', 'IsSystemDefault', 'UpdateResume', ),
BasePeer::TYPE_COLNAME => array (TaxPeer::ID, TaxPeer::VAT, TaxPeer::IS_DEFAULT, TaxPeer::RATES_BY_COUNTRY, TaxPeer::IS_ACTIVE, TaxPeer::VAT_NAME, TaxPeer::IS_SYSTEM_DEFAULT, TaxPeer::UPDATE_RESUME, ),
BasePeer::TYPE_FIELDNAME => array ('id', 'vat', 'is_default', 'rates_by_country', 'is_active', 'vat_name', 'is_system_default', 'update_resume', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/
private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'Vat' => 1, 'IsDefault' => 2, 'RatesByCountry' => 3, 'IsActive' => 4, 'VatName' => 5, 'IsSystemDefault' => 6, 'UpdateResume' => 7, ),
BasePeer::TYPE_COLNAME => array (TaxPeer::ID => 0, TaxPeer::VAT => 1, TaxPeer::IS_DEFAULT => 2, TaxPeer::RATES_BY_COUNTRY => 3, TaxPeer::IS_ACTIVE => 4, TaxPeer::VAT_NAME => 5, TaxPeer::IS_SYSTEM_DEFAULT => 6, TaxPeer::UPDATE_RESUME => 7, ),
BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'vat' => 1, 'is_default' => 2, 'rates_by_country' => 3, 'is_active' => 4, 'vat_name' => 5, 'is_system_default' => 6, 'update_resume' => 7, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, )
);
protected static $hydrateMethod = null;
protected static $postHydrateMethod = null;
public static function setHydrateMethod($callback)
{
self::$hydrateMethod = $callback;
}
public static function setPostHydrateMethod($callback)
{
self::$postHydrateMethod = $callback;
}
/**
* @return MapBuilder the map builder for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getMapBuilder()
{
return BasePeer::getMapBuilder('plugins.stTaxPlugin.lib.model.map.TaxMapBuilder');
}
/**
* Gets a map (hash) of PHP names to DB column names.
*
* @return array The PHP to DB name map for this peer
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @deprecated Use the getFieldNames() and translateFieldName() methods instead of this.
*/
public static function getPhpNameMap()
{
if (self::$phpNameMap === null) {
$map = TaxPeer::getTableMap();
$columns = $map->getColumns();
$nameMap = array();
foreach ($columns as $column) {
$nameMap[$column->getPhpName()] = $column->getColumnName();
}
self::$phpNameMap = $nameMap;
}
return self::$phpNameMap;
}
/**
* Translates a fieldname to another type
*
* @param string $name field name
* @param string $fromType One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @param string $toType One of the class type constants
* @return string translated name of the field.
*/
static public function translateFieldName($name, $fromType, $toType)
{
$toNames = self::getFieldNames($toType);
$key = isset(self::$fieldKeys[$fromType][$name]) ? self::$fieldKeys[$fromType][$name] : null;
if ($key === null) {
throw new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r(self::$fieldKeys[$fromType], true));
}
return $toNames[$key];
}
/**
* Returns an array of of field names.
*
* @param string $type The type of fieldnames to return:
* One of the class type constants TYPE_PHPNAME,
* TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
* @return array A list of field names
*/
static public function getFieldNames($type = BasePeer::TYPE_PHPNAME)
{
if (!array_key_exists($type, self::$fieldNames)) {
throw new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
}
return self::$fieldNames[$type];
}
/**
* Convenience method which changes table.column to alias.column.
*
* Using this method you can maintain SQL abstraction while using column aliases.
* <code>
* $c->addAlias("alias1", TablePeer::TABLE_NAME);
* $c->addJoin(TablePeer::alias("alias1", TablePeer::PRIMARY_KEY_COLUMN), TablePeer::PRIMARY_KEY_COLUMN);
* </code>
* @param string $alias The alias for the current table.
* @param string $column The column name for current table. (i.e. TaxPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(TaxPeer::TABLE_NAME.'.', $alias.'.', $column);
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param criteria object containing the columns to add.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria)
{
$criteria->addSelectColumn(TaxPeer::ID);
$criteria->addSelectColumn(TaxPeer::VAT);
$criteria->addSelectColumn(TaxPeer::IS_DEFAULT);
$criteria->addSelectColumn(TaxPeer::RATES_BY_COUNTRY);
$criteria->addSelectColumn(TaxPeer::IS_ACTIVE);
$criteria->addSelectColumn(TaxPeer::VAT_NAME);
$criteria->addSelectColumn(TaxPeer::IS_SYSTEM_DEFAULT);
$criteria->addSelectColumn(TaxPeer::UPDATE_RESUME);
if (stEventDispatcher::getInstance()->getListeners('TaxPeer.postAddSelectColumns')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'TaxPeer.postAddSelectColumns'));
}
}
const COUNT = 'COUNT(st_tax.ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT st_tax.ID)';
/**
* Returns the number of rows matching criteria.
*
* @param Criteria $criteria
* @param boolean $distinct Whether to select only distinct columns (You can also set DISTINCT modifier in Criteria).
* @param Connection $con
* @return int Number of matching rows.
*/
public static function doCount(Criteria $criteria, $distinct = false, $con = null)
{
// we're going to modify criteria, so copy it first
$criteria = clone $criteria;
// clear out anything that might confuse the ORDER BY clause
$criteria->clearSelectColumns()->clearOrderByColumns();
if ($distinct || in_array(Criteria::DISTINCT, $criteria->getSelectModifiers())) {
$criteria->addSelectColumn(TaxPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(TaxPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = TaxPeer::doSelectRS($criteria, $con);
if ($rs->next()) {
return $rs->getInt(1);
} else {
// no rows returned; we infer that means 0 matches.
return 0;
}
}
/**
* Method to select one object from the DB.
*
* @param Criteria $criteria object used to create the SELECT statement.
* @param Connection $con
* @return Tax
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelectOne(Criteria $criteria, $con = null)
{
$critcopy = clone $criteria;
$critcopy->setLimit(1);
$objects = TaxPeer::doSelect($critcopy, $con);
if ($objects) {
return $objects[0];
}
return null;
}
/**
* Method to do selects.
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con
* @return Tax[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return TaxPeer::populateObjects(TaxPeer::doSelectRS($criteria, $con));
}
/**
* Prepares the Criteria object and uses the parent doSelect()
* method to get a ResultSet.
*
* Use this method directly if you want to just get the resultset
* (instead of an array of objects).
*
* @param Criteria $criteria The Criteria object used to build the SELECT statement.
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return ResultSet The resultset object with numerically-indexed fields.
* @see BasePeer::doSelect()
*/
public static function doSelectRS(Criteria $criteria, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if (!$criteria->getSelectColumns()) {
$criteria = clone $criteria;
TaxPeer::addSelectColumns($criteria);
}
if (stEventDispatcher::getInstance()->getListeners('BasePeer.preDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'BasePeer.preDoSelectRs'));
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
// BasePeer returns a Creole ResultSet, set to return
// rows indexed numerically.
$rs = BasePeer::doSelect($criteria, $con);
if (stEventDispatcher::getInstance()->getListeners('BasePeer.postDoSelectRs')) {
stEventDispatcher::getInstance()->notify(new sfEvent($rs, 'BasePeer.postDoSelectRs'));
}
return $rs;
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(ResultSet $rs)
{
if (self::$hydrateMethod)
{
return call_user_func(self::$hydrateMethod, $rs);
}
$results = array();
// set the class once to avoid overhead in the loop
$cls = TaxPeer::getOMClass();
$cls = Propel::import($cls);
// populate the object(s)
while($rs->next()) {
$obj = new $cls();
$obj->hydrate($rs);
$results[] = self::$postHydrateMethod ? call_user_func(self::$postHydrateMethod, $obj) : $obj;
}
return $results;
}
/**
* Returns the TableMap related to this peer.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getDatabaseMap(self::DATABASE_NAME)->getTable(self::TABLE_NAME);
}
/**
* The class that the Peer will make instances of.
*
* This uses a dot-path notation which is tranalted into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @return string path.to.ClassName
*/
public static function getOMClass()
{
return TaxPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a Tax or Criteria object.
*
* @param mixed $values Criteria or Tax object containing data that is used to create the INSERT statement.
* @param Connection $con the connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($values, $con = null)
{
foreach (sfMixer::getCallables('BaseTaxPeer:doInsert:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseTaxPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} else {
$criteria = $values->buildCriteria(); // build Criteria from Tax object
}
$criteria->remove(TaxPeer::ID); // remove pkey col since this table uses auto-increment
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->begin();
$pk = BasePeer::doInsert($criteria, $con);
$con->commit();
} catch(PropelException $e) {
$con->rollback();
throw $e;
}
foreach (sfMixer::getCallables('BaseTaxPeer:doInsert:post') as $callable)
{
call_user_func($callable, 'BaseTaxPeer', $values, $con, $pk);
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a Tax or Criteria object.
*
* @param mixed $values Criteria or Tax object containing data that is used to create the UPDATE statement.
* @param Connection $con The connection to use (specify Connection object to exert more control over transactions).
* @return int The number of affected rows (if supported by underlying database driver).
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doUpdate($values, $con = null)
{
foreach (sfMixer::getCallables('BaseTaxPeer:doUpdate:pre') as $callable)
{
$ret = call_user_func($callable, 'BaseTaxPeer', $values, $con);
if (false !== $ret)
{
return $ret;
}
}
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$selectCriteria = new Criteria(self::DATABASE_NAME);
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(TaxPeer::ID);
$selectCriteria->add(TaxPeer::ID, $criteria->remove(TaxPeer::ID), $comparison);
} else { // $values is Tax object
$criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
}
// set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$ret = BasePeer::doUpdate($selectCriteria, $criteria, $con);
foreach (sfMixer::getCallables('BaseTaxPeer:doUpdate:post') as $callable)
{
call_user_func($callable, 'BaseTaxPeer', $values, $con, $ret);
}
return $ret;
}
/**
* Method to DELETE all rows from the st_tax table.
*
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll($con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
TaxPeer::doOnDeleteSetNull(new Criteria(), $con);
$affectedRows += BasePeer::doDeleteAll(TaxPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a Tax or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Tax object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param Connection $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(TaxPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof Tax) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(TaxPeer::ID, (array) $values, Criteria::IN);
}
// Set the correct dbName
$criteria->setDbName(self::DATABASE_NAME);
$affectedRows = 0; // initialize var to track total num of affected rows
try {
// use transaction because $criteria could contain info
// for more than one table or we could emulating ON DELETE CASCADE, etc.
$con->begin();
TaxPeer::doOnDeleteSetNull($criteria, $con);
$affectedRows += BasePeer::doDelete($criteria, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* This is a method for emulating ON DELETE SET NULL DBs that don't support this
* feature (like MySQL or SQLite).
*
* This method is not very speedy because it must perform a query first to get
* the implicated records and then perform the deletes by calling those Peer classes.
*
* This method should be used within a transaction if possible.
*
* @param Criteria $criteria
* @param Connection $con
* @return void
*/
protected static function doOnDeleteSetNull(Criteria $criteria, Connection $con)
{
// first find the objects that are implicated by the $criteria
$objects = TaxPeer::doSelect($criteria, $con);
foreach($objects as $obj) {
// set fkey col in related OrderProduct rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(OrderProductPeer::TAX_ID, $obj->getId());
$updateValues->add(OrderProductPeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related OrderDelivery rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(OrderDeliveryPeer::TAX_ID, $obj->getId());
$updateValues->add(OrderDeliveryPeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related Product rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(ProductPeer::TAX_ID, $obj->getId());
$updateValues->add(ProductPeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related Delivery rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(DeliveryPeer::TAX_ID, $obj->getId());
$updateValues->add(DeliveryPeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related AddPrice rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(AddPricePeer::TAX_ID, $obj->getId());
$updateValues->add(AddPricePeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related AddGroupPrice rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(AddGroupPricePeer::TAX_ID, $obj->getId());
$updateValues->add(AddGroupPricePeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
// set fkey col in related GroupPrice rows to NULL
$selectCriteria = new Criteria(TaxPeer::DATABASE_NAME);
$updateValues = new Criteria(TaxPeer::DATABASE_NAME);
$selectCriteria->add(GroupPricePeer::TAX_ID, $obj->getId());
$updateValues->add(GroupPricePeer::TAX_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
}
}
/**
* Validates all modified columns of given Tax object.
* If parameter $columns is either a single column name or an array of column names
* than only those columns are validated.
*
* NOTICE: This does not apply to primary or foreign keys for now.
*
* @param Tax $obj The object to validate.
* @param mixed $cols Column name or array of column names.
*
* @return mixed TRUE if all columns are valid or the error message of the first invalid column.
*/
public static function doValidate(Tax $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(TaxPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(TaxPeer::TABLE_NAME);
if (! is_array($cols)) {
$cols = array($cols);
}
foreach($cols as $colName) {
if ($tableMap->containsColumn($colName)) {
$get = 'get' . $tableMap->getColumn($colName)->getPhpName();
$columns[$colName] = $obj->$get();
}
}
} else {
}
$res = BasePeer::doValidate(TaxPeer::DATABASE_NAME, TaxPeer::TABLE_NAME, $columns);
if ($res !== true) {
$request = sfContext::getInstance()->getRequest();
foreach ($res as $failed) {
$col = TaxPeer::translateFieldname($failed->getColumn(), BasePeer::TYPE_COLNAME, BasePeer::TYPE_PHPNAME);
$request->setError($col, $failed->getMessage());
}
}
return $res;
}
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return Tax
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(TaxPeer::DATABASE_NAME);
$criteria->add(TaxPeer::ID, $pk);
$v = TaxPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return Tax[]
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(TaxPeer::ID, $pks, Criteria::IN);
$objs = TaxPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BaseTaxPeer
// static code to register the map builder for this Peer with the main Propel class
if (Propel::isInit()) {
// the MapBuilder classes register themselves with Propel during initialization
// so we need to load them here.
try {
BaseTaxPeer::getMapBuilder();
} catch (Exception $e) {
Propel::log('Could not initialize Peer: ' . $e->getMessage(), Propel::LOG_ERR);
}
} else {
// even if Propel is not yet initialized, the map builder class can be registered
// now and then it will be loaded when Propel initializes.
Propel::registerMapBuilder('plugins.stTaxPlugin.lib.model.map.TaxMapBuilder');
}

View File

@@ -0,0 +1,321 @@
<?php
class stTax
{
const SESSION_NAMESPACE = 'soteshop/stTaxPlugin';
protected static $activeCached = null;
protected static $requiredCountriesIds = null;
/**
* Lista krajów dla VAT UE Konsumenta
*
* @var Countries[]
*/
protected static $countriesForConsumerEuRates = null;
/**
* Zwraca stawkę VAT po ID
*
* @param int $id
* @return Tax
*/
public static function getById($id)
{
$taxes = self::get();
return isset($taxes[$id]) ? $taxes[$id] : null;
}
/**
* Zwraca czy VAT UE dla konsumentów jest włączony
*
* @return bool
*/
public static function getIsCustomerEuTaxEnabled($checkConfigOnly = false)
{
$config = stConfig::getInstance('stTaxBackend');
$isCustomerEuTaxEnabled = sfContext::getInstance()->getUser()->getAttribute('is_customer_eu_tax_enabled', true, self::SESSION_NAMESPACE);
return $config->get('is_customer_eu_tax_enabled') && ($isCustomerEuTaxEnabled || $checkConfigOnly);
}
/**
* Ustawia czy VAT UE dla konsumentów jest włączony
*
* @param bool $isCustomerEuTaxEnabled Czy VAT UE dla konsumentów jest włączony
*/
public static function setIsCustomerEuTaxEnabled($isCustomerEuTaxEnabled)
{
sfContext::getInstance()->getUser()->setAttribute('is_customer_eu_tax_enabled', $isCustomerEuTaxEnabled, self::SESSION_NAMESPACE);
}
/**
* Zwraca stawkę VAT po wartości
*
* @param string $value
* @return Tax
*/
public static function getByValue($value)
{
$value = stPrice::round($value);
$results = self::fetchCached();
$rates = $results['rates'];
return isset($rates[$value]) ? $results['active'][$rates[$value]] : null;
}
/**
* Zwraca listę aktywnych stawek VAT
*
* @return Tax[]
*/
public static function get()
{
$results = self::fetchCached();
return $results['active'];
}
/**
* Zwraca domyślną stawkę VAT
*
* @return void
*/
public static function getDefault()
{
$results = self::fetchCached();
return $results['default'] ? $results['active'][$results['default']] : null;
}
public static function hasEx($country_id = null)
{
/**
* @var stBasket
*/
$basket = sfContext::getInstance()->getUser()->getBasket();
/**
* @var Countries
*/
$country = stDeliveryFrontend::getInstance($basket)->getDefaultDeliveryCountry();
return null !== self::getEx() && $country && !$country->isEU() && (null === $country_id || !CountriesPeer::retrieveByPK($country_id)->isEU());
}
/**
* Zwraca stawkę EX
*
* @return Tax
*/
public static function getEx()
{
$results = self::fetchCached();
return $results['ex'] && isset($results['active'][$results['ex']]) ? $results['active'][$results['ex']] : null;
}
/**
* Zwraca stawkę EU
*
* @return Tax
*/
public static function getEu()
{
$results = self::fetchCached();
return $results['eu'] && isset($results['active'][$results['eu']]) ? $results['active'][$results['eu']] : null;
}
public static function fetchCached()
{
if (null === self::$activeCached)
{
$cache = new stFunctionCache('stTax');
self::$activeCached = $cache->cacheCall(array('stTax', 'fetch'));
}
return self::$activeCached;
}
public static function fetch()
{
$c = new Criteria();
$c->add(TaxPeer::IS_ACTIVE, true);
$rs = TaxPeer::doSelectRS($c);
$results = array();
$rates = array();
$default = null;
$ex = null;
$eu = null;
while ($rs->next())
{
$tax = new Tax();
$tax->hydrate($rs);
$results[$tax->getId()] = $tax;
if (!in_array($tax->getVatName(), ['ex', 'ue', 'zw']))
{
$rates[stPrice::round($tax->getVat())] = $tax->getId();
}
if ($tax->getIsDefault())
{
$default = $tax->getId();
}
if ($tax->getVatName() == 'ex')
{
$ex = $tax->getId();
}
if ($tax->getVatName() == 'ue')
{
$eu = $tax->getId();
}
}
return array('active' => $results, 'default' => $default, 'rates' => $rates, 'ex' => $ex, 'eu' => $eu);
}
public static function getEUTaxRates()
{
return sfConfig::get('app_st_tax_rates', array());
}
/**
* Zwraca listę krajów dla VAT UE Konsumenta
*
* @return Countries[]
* @throws PropelException
*/
public static function getCountriesForConsumerEuRates()
{
if (null === self::$countriesForConsumerEuRates)
{
$rates = self::getEUTaxRates();
$countryCodes = array_keys($rates);
$c = new Criteria();
$c->add(CountriesPeer::ISO_A2, $countryCodes, Criteria::IN);
$c->addAscendingOrderByColumn(CountriesPeer::OPT_NAME);
CountriesPeer::setHydrateMethod(function (ResultSet $rs)
{
$results = array();
$rs->setFetchmode(ResultSet::FETCHMODE_NUM);
while ($rs->next())
{
$country = new Countries();
$country->hydrate($rs);
$results[$country->getIsoA2()] = $country;
}
return $results;
});
self::$countriesForConsumerEuRates = CountriesPeer::doSelect($c);
}
return self::$countriesForConsumerEuRates;
}
/**
* Zwraca listę kodów krajów wymaganych
*
* @return array
*/
public static function getRequiredCountriesCodes()
{
if (null === self::$requiredCountriesIds)
{
$config = stConfig::getInstance('stShopInfoBackend');
$ids = array();
foreach (self::getCountriesForConsumerEuRates() as $country)
{
$ids[] = $country->getId();
}
$c = new Criteria();
$c->addSelectColumn(CountriesPeer::ID);
$c->addSelectColumn(CountriesPeer::ISO_A2);
$c->add(CountriesPeer::ID, $ids, Criteria::IN);
$c->addJoin(CountriesPeer::ID, CountriesAreaHasCountriesPeer::COUNTRIES_ID);
$c->addJoin(CountriesAreaHasCountriesPeer::COUNTRIES_AREA_ID, CountriesAreaPeer::ID);
$c->addJoin(CountriesAreaPeer::ID, DeliveryPeer::COUNTRIES_AREA_ID);
$c->add(DeliveryPeer::ACTIVE, true);
$c->addGroupByColumn(CountriesPeer::ID);
CountriesPeer::setHydrateMethod(function (ResultSet $rs) use ($config)
{
$results = array();
while ($rs->next())
{
$id = $rs->getInt(1);
$code = $rs->getString(2);
if ($config->get('country') != $code)
{
$results[$id] = $code;
}
}
return $results;
});
self::$requiredCountriesIds = CountriesPeer::doSelect($c);
}
return self::$requiredCountriesIds;
}
public static function checkRequiredCountriesTaxRateConfiguration(array $countryCodes, array &$errors = null)
{
$errors = array();
$requiredCodes = self::getEUTaxRates();
$config = stConfig::getInstance('stShopInfoBackend');
foreach (TaxPeer::doSelectActive() as $tax)
{
if ($tax->isSystemDefault())
{
continue;
}
$rates = $tax->getRatesByCountry();
foreach ($countryCodes as $code)
{
if ($config->get('country') == $code)
{
continue;
}
if (isset($requiredCodes[$code]) && (!$rates || !isset($rates[$code]) || $rates[$code] === ""))
{
$errors[$code][$tax->getId()] = $tax;
}
}
}
return empty($errors);
}
}

View File

@@ -0,0 +1,45 @@
<?php
class stTaxListener
{
public static function reminder(sfEvent $event)
{
$action = $event->getSubject();
$i18n = $action->getContext()->getI18N();
if (!($action->getModuleName() == 'stTaxBackend' && $action->getActionName() == 'updatePrice'))
{
$c = new Criteria();
$c->add(TaxPeer::UPDATE_RESUME, null, Criteria::ISNOTNULL);
$tax = TaxPeer::doSelectOne($c);
sfLoader::loadHelpers(array('Helper', 'stUrl', 'Asset', 'I18N'));
if ($tax)
{
$reminder = __('Wystąpił problem podczas aktualizacji cen dla stawki VAT', null, 'stTaxBackend').' '.$tax->getVat().' %. '.__('Kliknij', null, 'stTaxBackend').' '.st_link_to(__('tutaj', null, 'stTaxBackend'), 'stTaxBackend/updatePrice?id='.$tax->getId()).', '.__('aby dokończyć.', null, 'stTaxBackend');
stReminder::add('stTaxBackend/updatePrice', $reminder, 'warning');
}
}
if (strtotime('31.01.2011') > time())
{
if(sfContext::getInstance()->getUser()->getCulture() == 'pl_PL')
{
$docs_link = '<a href="http://www.sote.pl/trac/wiki/new_doc/tax" target="_blank">';
} else {
$docs_link = '<a href="http://www.sote.pl/trac/wiki/new_doc/en/tax" target="_blank">';
}
$info = $i18n->__('Od 01.01.2011 obowiązują nowe stawki VAT (więcej w', null, 'stTaxBackend').' '.$docs_link.$i18n->__('dokumentacji', null, 'stTaxBackend').'</a>)';
stReminder::add('stTaxBackend/taxInfo', $info);
}
}
}

View File

@@ -0,0 +1,336 @@
<?php
class stTaxProgressBar
{
protected
$steps,
$type,
$tax;
public function init()
{
stLock::lock('frontend');
}
public function __construct()
{
$this->steps = self::getParam('steps');
$this->tax = self::getParam('tax');
}
public function updateProductPrice($offset)
{
$i18n = sfContext::getInstance()->getI18N();
self::setMessage($i18n->__('Przeliczanie cen produktów w toku', null, 'stTaxBackend'));
$c = new Criteria();
$c->add(ProductPeer::TAX_ID, $this->tax['id']);
$c->setOffset($offset);
$c->setLimit(10);
$products = ProductPeer::doSelect($c);
foreach ($products as $product)
{
$product->setCulture('pl_PL');
if ($this->tax['type'] == 'netto')
{
$this->updateProductPriceNetto($product);
}
elseif ($product->getCurrencyExchange() && $product->getCurrencyExchange() != 1)
{
$this->updateProductCurrencyPrice($product);
}
else
{
$this->updateProductPriceBrutto($product);
}
$product->setOptVat($this->tax['value']);
$product->save();
}
$offset += count($products);
if ($offset >= $this->steps['products'])
{
self::setAction('updateDeliveryCost');
}
return $offset;
}
public function updateDeliveryCost($offset)
{
$i18n = sfContext::getInstance()->getI18N();
self::setMessage($i18n->__('Przeliczanie kosztów dostaw w toku', null, 'stTaxBackend'));
$c = new Criteria();
$c->setOffset($offset - $this->steps['products']);
$c->setLimit(10);
$c->add(DeliveryPeer::TAX_ID, $this->tax['id']);
$deliveries = DeliveryPeer::doSelect($c);
foreach ($deliveries as $delivery)
{
$delivery->setCulture('pl_PL');
if ($this->tax['type'] == 'netto')
{
$this->updateDeliveryCostNetto($delivery);
}
else
{
$this->updateDeliveryCostBrutto($delivery);
}
$delivery->save();
}
$offset += count($deliveries);
return $offset;
}
public function close()
{
sfContext::getInstance()->getUser()->getAttributeHolder()->removeNamespace('soteshop/stTaxProgressBar');
$tax = TaxPeer::retrieveByPK($this->tax['id']);
$tax->setUpdateResume(null);
$tax->save();
stLock::unlock('frontend');
$i18n = sfContext::getInstance()->getI18N();
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$link = st_link_to($i18n->__('Powróć do edycji', null, 'stTaxBackend'), 'stTaxBackend/edit?id='.$this->tax['id']);
self::setMessage($i18n->__('Aktualizacja cen została zakończona pomyślnie', null, 'stTaxBackend').'.<br/>'.$link);
}
public static function setParam($name, $value)
{
sfContext::getInstance()->getUser()->setAttribute($name, $value, 'soteshop/stTaxProgressBar');
}
public static function getParam($name, $default = null)
{
return sfContext::getInstance()->getUser()->getAttribute($name, $default, 'soteshop/stTaxProgressBar');
}
public static function setMessage($message)
{
sfContext::getInstance()->getUser()->setAttribute('stProgressBar-stTax', $message, 'symfony/flash');
}
protected function getCurrencyPrice($netto, $exchange)
{
$brutto = stPrice::calculate($netto, $this->tax['value']);
return stCurrency::calculateCurrencyPrice($brutto, $exchange);
}
protected function updateProductCurrencyPrice(Product $product)
{
$exchange = $product->getCurrencyExchange();
if ($product->getPriceNetto())
{
$product->setCurrencyPrice($this->getCurrencyPrice($product->getPriceNetto(), $exchange));
}
if ($product->getOldPriceNetto())
{
$product->setCurrencyoldPrice($this->getCurrencyPrice($product->getOldPriceNetto(), $exchange));
}
if ($product->getWholesaleANetto())
{
$product->setCurrencyWholesaleA($this->getCurrencyPrice($product->getWholesaleANetto(), $exchange));
}
if ($product->getWholesaleBNetto())
{
$product->setCurrencyWholesaleB($this->getCurrencyPrice($product->getWholesaleBNetto(), $exchange));
}
if ($product->getWholesaleCNetto())
{
$product->setCurrencyWholesaleC($this->getCurrencyPrice($product->getWholesaleCNetto(), $exchange));
}
foreach (self::getProductOptions($product) as $value)
{
list($price, $prefix, $postfix) = self::parseProductOptionPrice($value->getPrice());
if ($postfix != '%' && $price)
{
$price = stCurrency::calculateCurrencyPrice($price, $exchange, true);
$price = stPrice::extract($price, $this->tax['prev_value']);
$price = stPrice::calculate($price, $this->tax['value']);
$value->setPrice($prefix.stCurrency::calculateCurrencyPrice($price, $exchange));
}
$value->setIsUpdated(true);
$value->save();
}
}
protected function updateProductPriceBrutto(Product $product)
{
$product->setPriceBrutto(null);
$product->setOldPriceBrutto(null);
$product->setWholesaleABrutto(null);
$product->setWholesaleBBrutto(null);
$product->setWholesaleCBrutto(null);
foreach (self::getProductOptions($product) as $value)
{
list($price, $prefix, $postfix) = self::parseProductOptionPrice($value->getPrice());
if ($price && $postfix != '%' && $value->getPriceType() != 'netto')
{
$price = stPrice::extract($price, $this->tax['prev_value']);
$price = stPrice::calculate($price, $this->tax['value']);
$value->setPrice($prefix.$price);
}
$value->setIsUpdated(true);
$value->save();
}
}
protected function updateProductPriceNetto(Product $product)
{
$product->setPriceNetto(null);
$product->setOldPriceNetto(null);
$product->setWholesaleANetto(null);
$product->setWholesaleBNetto(null);
$product->setWholesaleCNetto(null);
foreach (self::getProductOptions($product) as $value)
{
list($price, $prefix, $postfix) = self::parseProductOptionPrice($value->getPrice());
if ($price && $postfix != '%' && $value->getPriceType() != 'brutto')
{
$price = stPrice::calculate($price, $this->tax['prev_value']);
$price = stPrice::extract($price, $this->tax['value']);
$value->setPrice($prefix.$price);
}
$value->setIsUpdated(true);
$value->save();
}
}
protected function updateDeliveryCostNetto(Delivery $delivery)
{
$tax = $this->tax['value'];
$delivery->getTax()->setVat($this->tax['prev_value']);
$delivery->setCostNetto(stPrice::extract($delivery->getCostBrutto(), $tax));
foreach ($delivery->getDeliveryHasPaymentTypes() as $payment)
{
$payment->setDelivery($delivery);
$payment->setCostNetto(stPrice::extract($payment->getCostBrutto(), $tax));
}
foreach ($delivery->getDeliverySectionss() as $section)
{
$section->setDelivery($delivery);
$section->setCostNetto(stPrice::extract($section->getCostBrutto(), $tax));
}
$delivery->getTax()->setVat($tax);
}
protected function updateDeliveryCostBrutto(Delivery $delivery)
{
$tax = $this->tax['value'];
$delivery->setCostBrutto(stPrice::calculate($delivery->getCostNetto(), $tax));
foreach ($delivery->getDeliveryHasPaymentTypes() as $payment)
{
$payment->setCostBrutto(stPrice::calculate($payment->getCostNetto(), $tax));
}
foreach ($delivery->getDeliverySectionss() as $section)
{
$section->setCostBrutto(stPrice::calculate($section->getCostNetto(), $tax));
}
}
protected static function parseProductOptionPrice($price)
{
$prefix = $price{0} == '+' || $price{0} == '-' ? $price{0} : null;
$postfix = substr($price, -1) == '%' ? '%' : '';
return array(trim($price, '-+%'), $prefix, $postfix);
}
protected static function getProductOptions(Product $product)
{
$c = new Criteria();
$c->add(ProductOptionsValuePeer::IS_UPDATED, false);
return $product->getProductOptionsValues($c);
}
protected static function setAction($action)
{
$user = sfContext::getInstance()->getUser();
$name = sfContext::getInstance()->getRequest()->getParameter('name');
$info = $user->getAttribute($name, array(), 'soteshop/stProgressBarPlugin');
$info['method'] = $action;
$user->setAttribute($name, $info, 'soteshop/stProgressBarPlugin');
}
}

View File

@@ -0,0 +1,177 @@
<?php
class stTaxVies
{
protected $client;
/**
* Wyjątek SOAP
*
* @var SoapFault|null
*/
protected $soapFault = null;
protected $logger = null;
protected static $instance = null;
public static function hasValidCountryCode($client_vat_number, $merchantCountryCode)
{
$client = self::parseVatNumber($client_vat_number);
return $client[0] != $merchantCountryCode;
}
public static function parseVatNumber($vat_number)
{
$vat_number = str_replace(array(' ', '.', '-', ',', ', '), '', trim($vat_number));
$cc = substr($vat_number, 0, 2);
$vn = substr($vat_number, 2);
return array(strtoupper($cc), $vn);
}
public static function checkVatUrl($vat_number)
{
list($cc, $vn) = self::parseVatNumber($vat_number);
return 'http://ec.europa.eu/taxation_customs/vies/vatResponse.html?action=check&check=Verify&memberStateCode='.$cc.'&number='.$vn;
}
public static function getInstance()
{
if (null === self::$instance)
{
self::$instance = new stTaxVies();
self::$instance->initialize();
}
return self::$instance;
}
/**
* Zwraca wyjątek SOAP o ile wystąpił podczas żądania
*
* @return SoapFault|null
*/
public function getSoapFault()
{
return $this->soapFault;
}
public function checkVat($vat_number)
{
$info = $this->getVatInfo($vat_number);
return $info !== false && $info->isValid();
}
public function getVatInfo($vat_number)
{
if (!$this->client)
{
return false;
}
$this->soapFault = null;
list($cc, $vn) = self::parseVatNumber($vat_number);
try
{
$result = $this->client->checkVat(array('countryCode' => $cc, 'vatNumber' => $vn));
$response = new stTaxViesResponse($result);
}
catch(SoapFault $e)
{
return $this->handleException($e);
}
if ($this->logger)
{
$this->logMessage($response);
}
return $response;
}
protected function handleException(SoapFault $e)
{
if ($this->logger)
{
$this->logMessage($e->getMessage(), SF_LOG_ERR);
}
$this->soapFault = $e;
return false;
}
protected function initialize()
{
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$this->logger = sfLogger::getInstance();
}
try
{
$this->client = new SoapClient(dirname(__FILE__).'/../data/checkVatService.wsdl');
}
catch(SoapFault $e)
{
$this->handleException($e);
}
return $this;
}
protected function logMessage($message, $level = SF_LOG_INFO)
{
$this->logger->log('{stTaxVies} ' . $message, $level);
}
}
class stTaxViesResponse
{
protected $result;
public function __toString()
{
return json_encode($this->result);
}
public function __construct(stdClass $result)
{
$this->result = $result;
}
public function getCountryCode()
{
return $this->result->countryCode;
}
public function getVatNumber()
{
return $this->result->vatNumber;
}
public function isValid()
{
return $this->result->valid;
}
public function getName()
{
return $this->result->name;
}
public function getAddress()
{
return $this->result->address;
}
}