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,31 @@
all:
st_tax:
rates:
AT: {normal: 20, reduced: [13, 10, 0]}
BE: {normal: 21, reduced: [12, 6, 0]}
BG: {normal: 20, reduced: [9, 0]}
HR: {normal: 25, reduced: [13, 5, 0]}
CY: {normal: 19, reduced: [5, 0]}
CZ: {normal: 21, reduced: [15, 10, 0]}
DK: {normal: 25, reduced: [0]}
EE: {normal: 20, reduced: [9, 0]}
FI: {normal: 24, reduced: [14, 10, 0]}
FR: {normal: 20, reduced: [10, 5.5, 2.1, 0]}
DE: {normal: 19, reduced: [7, 0]}
GR: {normal: 24, reduced: [13, 6, 0]}
HU: {normal: 27, reduced: [18, 5, 0]}
IE: {normal: 23, reduced: [13.5, 9, 4.8, 0]}
IT: {normal: 22, reduced: [10, 5, 4, 0]}
LV: {normal: 21, reduced: [12, 5, 0]}
LT: {normal: 21, reduced: [9, 5, 0]}
LU: {normal: 17, reduced: [14, 8, 3, 0]}
MT: {normal: 18, reduced: [7, 5, 0]}
NL: {normal: 21, reduced: [9, 0]}
PL: {normal: 23, reduced: [8, 5, 0]}
PT: {normal: 23, reduced: [13, 6, 0]}
RO: {normal: 19, reduced: [9, 5, 0]}
SK: {normal: 20, reduced: [10, 0]}
SI: {normal: 22, reduced: [9.5, 5, 0]}
ES: {normal: 21, reduced: [10, 4, 0]}
SE: {normal: 25, reduced: [12, 6, 0]}
XI: {normal: 20, reduced: [9, 5, 0]}

View File

@@ -0,0 +1,31 @@
<?php
/**
* SOTESHOP/stTaxPlugin
*
* Ten plik należy do aplikacji stTaxPlugin opartej na licencji (Open License SOTE) Otwarta Licencja SOTE.
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stTaxPlugin
* @subpackage configs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/open (Open License SOTE) Otwarta Licencja SOTE
* @version $Id$
* @author Krzysztof Beblo <krzysztof.beblo@sote.pl>
*/
/**
* Włączanie modułów
*/
stPluginHelper::addEnableModule('stTaxBackend', 'backend');
/**
* Dodawanie routingów
*/
stPluginHelper::addRouting('stTaxPlugin', '/tax/:action/*', 'stTaxBackend', 'list', 'backend');
if (SF_APP == 'backend')
{
$dispatcher->connect('stReminderBackend.beforeReminderCount', array('stTaxListener', 'reminder'));
}

View File

@@ -0,0 +1,40 @@
---
propel:
_attributes:
defaultIdMethod: native
package: plugins.stTaxPlugin.lib.model
st_tax:
_attributes:
phpName: Tax
id:
type: INTEGER
primaryKey: true
required: true
autoIncrement: true
vat:
type: DECIMAL
size: 5
scale: 2
required: true
default: 0
is_default:
type: BOOLEAN
required: true
default: false
rates_by_country:
phpType: array
type: VARCHAR
size: 2048
is_active:
type: BOOLEAN
required: true
default: true
vat_name:
type: VARCHAR
size: 45
required: true
is_system_default:
type: BOOLEAN
required: true
default: false

View File

@@ -0,0 +1,9 @@
propel:
st_product:
_attributes: {phpName: Product}
tax_id:
type: INTEGER
required: false
foreignTable: st_tax
foreignReference: id
onDelete: setnull

View File

@@ -0,0 +1,6 @@
propel:
st_product_options_value:
_attributes: {phpName: ProductOptionsValue}
is_updated:
type: BOOLEAN
default: false

View File

@@ -0,0 +1,7 @@
propel:
st_tax:
_attributes: {phpName: Tax}
update_resume:
type: VARCHAR
size: 64
phpType: array

View File

@@ -0,0 +1,176 @@
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="urn:ec.europa.eu:taxud:vies:services:checkVat" xmlns:tns1="urn:ec.europa.eu:taxud:vies:services:checkVat:types" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:impl="urn:ec.europa.eu:taxud:vies:services:checkVat" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/">
<xsd:documentation>
Specific disclaimer for this service ----------------------------------------- The
objective of this Internet site is to allow persons involved in the intra-Community supply of
goods or of services to obtain confirmation of the validity of the VAT identification number of
any specified person, in accordance to article 27 of Council Regulation (EC) No. 1798/2003 of 7
October 2003. Any other use and any extraction and use of the data which is not in conformity
with the objective of this site is strictly forbidden. Any retransmission of the contents of
this site, whether for a commercial purpose or otherwise, as well as any more general use other
than as far as is necessary to support the activity of a legitimate user (for example: to draw
up their own invoices) is expressly forbidden. In addition, any copying or reproduction of the
contents of this site is strictly forbidden. The European Commission maintains this website to
enhance the access by taxable persons making intra-Community supplies to verification of their
customers VAT identification numbers. Our goal is to supply instantaneous and accurate
information. However the Commission accepts no responsibility or liability whatsoever with
regard to the information obtained using this site. This information: - is obtained from Member
States databases over which the Commission services have no control and for which the Commission
assumes no responsibility; it is the responsibility of the Member States to keep their databases
complete, accurate and up to date; - is not professional or legal advice (if you need specific
advice, you should always consult a suitably qualified professional); - does not in itself give
a right to exempt intra-Community supplies from Value Added Tax; - does not change any
obligations imposed on taxable persons in relation to intra-Community supplies. It is our goal
to minimise disruption caused by technical errors. However some data or information on our site
may have been created or structured in files or formats which are not error-free and we cannot
guarantee that our service will not be interrupted or otherwise affected by such problems. The
Commission accepts no responsibility with regard to such problems incurred as a result of using
this site or any linked external sites. This disclaimer is not intended to limit the liability
of the Commission in contravention of any requirements laid down in applicable national law nor
to exclude its liability for matters which may not be excluded under that law. Usage: The
countryCode input parameter must follow the pattern [A-Z]{2} The vatNumber input parameter must
follow the [0-9A-Za-z\+\*\.]{2,12} In case of problem, the returned FaultString can take the
following specific values: - INVALID_INPUT: The provided CountryCode is invalid or the VAT
number is empty; - SERVICE_UNAVAILABLE: The SOAP service is unavailable, try again later; -
MS_UNAVAILABLE: The Member State service is unavailable, try again later or with another Member
State; - TIMEOUT: The Member State service could not be reach in time, try again later or with
another Member State; - SERVER_BUSY: The service can't process your request. Try again latter.
</xsd:documentation>
<wsdl:types>
<xsd:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="urn:ec.europa.eu:taxud:vies:services:checkVat:types" xmlns="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
<xsd:element name="checkVat">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="countryCode" type="xsd:string"/>
<xsd:element name="vatNumber" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="checkVatResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="countryCode" type="xsd:string"/>
<xsd:element name="vatNumber" type="xsd:string"/>
<xsd:element name="requestDate" type="xsd:date"/>
<xsd:element name="valid" type="xsd:boolean"/>
<xsd:element maxOccurs="1" minOccurs="0" name="name" nillable="true" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="address" nillable="true" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="checkVatApprox">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="countryCode" type="xsd:string"/>
<xsd:element name="vatNumber" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderName" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCompanyType" type="tns1:companyTypeCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderStreet" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderPostcode" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCity" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="requesterCountryCode" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="requesterVatNumber" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="checkVatApproxResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="countryCode" type="xsd:string"/>
<xsd:element name="vatNumber" type="xsd:string"/>
<xsd:element name="requestDate" type="xsd:date"/>
<xsd:element name="valid" type="xsd:boolean"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderName" nillable="true" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCompanyType" nillable="true" type="tns1:companyTypeCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderAddress" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderStreet" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderPostcode" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCity" type="xsd:string"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderNameMatch" type="tns1:matchCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCompanyTypeMatch" type="tns1:matchCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderStreetMatch" type="tns1:matchCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderPostcodeMatch" type="tns1:matchCode"/>
<xsd:element maxOccurs="1" minOccurs="0" name="traderCityMatch" type="tns1:matchCode"/>
<xsd:element name="requestIdentifier" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:simpleType name="companyTypeCode">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[A-Z]{2}\-[1-9][0-9]?"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="matchCode">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="1">
<xsd:annotation>
<xsd:documentation>VALID</xsd:documentation>
</xsd:annotation>
</xsd:enumeration>
<xsd:enumeration value="2">
<xsd:annotation>
<xsd:documentation>INVALID</xsd:documentation>
</xsd:annotation>
</xsd:enumeration>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
</wsdl:types>
<wsdl:message name="checkVatRequest">
<wsdl:part name="parameters" element="tns1:checkVat">
</wsdl:part>
</wsdl:message>
<wsdl:message name="checkVatApproxResponse">
<wsdl:part name="parameters" element="tns1:checkVatApproxResponse">
</wsdl:part>
</wsdl:message>
<wsdl:message name="checkVatApproxRequest">
<wsdl:part name="parameters" element="tns1:checkVatApprox">
</wsdl:part>
</wsdl:message>
<wsdl:message name="checkVatResponse">
<wsdl:part name="parameters" element="tns1:checkVatResponse">
</wsdl:part>
</wsdl:message>
<wsdl:portType name="checkVatPortType">
<wsdl:operation name="checkVat">
<wsdl:input name="checkVatRequest" message="impl:checkVatRequest">
</wsdl:input>
<wsdl:output name="checkVatResponse" message="impl:checkVatResponse">
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="checkVatApprox">
<wsdl:input name="checkVatApproxRequest" message="impl:checkVatApproxRequest">
</wsdl:input>
<wsdl:output name="checkVatApproxResponse" message="impl:checkVatApproxResponse">
</wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="checkVatBinding" type="impl:checkVatPortType">
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="checkVat">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="checkVatRequest">
<wsdlsoap:body use="literal"/>
</wsdl:input>
<wsdl:output name="checkVatResponse">
<wsdlsoap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="checkVatApprox">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="checkVatApproxRequest">
<wsdlsoap:body use="literal"/>
</wsdl:input>
<wsdl:output name="checkVatApproxResponse">
<wsdlsoap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="checkVatService">
<wsdl:port name="checkVatPort" binding="impl:checkVatBinding">
<wsdlsoap:address location="http://ec.europa.eu/taxation_customs/vies/services/checkVatService"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

View File

@@ -0,0 +1,83 @@
default:
Tax_1:
vat: 0
vat_name: 0%
CZ:
Tax_1:
vat: 20
vat_name: 20%
Tax_2:
vat: 10
vat_name: 10%
DE:
Tax_1:
vat: 19
vat_name: 19%
Tax_2:
vat: 7
vat_name: 7%
ES:
Tax_1:
vat: 18
vat_name: 18%
Tax_2:
vat: 8
vat_name: 8%
Tax_3:
vat: 4
vat_name: 4%
FR:
Tax_1:
vat: 19.6
vat_name: 19.6%
Tax_2:
vat: 5.5
vat_name: 5.5%
Tax_3:
vat: 2.1
vat_name: 2.1%
GB:
Tax_1:
vat: 20
vat_name: 20%
Tax_2:
vat: 5
vat_name: 5%
IT:
Tax_1:
vat: 20
vat_name: 20%
Tax_2:
vat: 10
vat_name: 10%
PT:
Tax_1:
vat: 23
vat_name: 23%
Tax_2:
vat: 13
vat_name: 13%
Tax_3:
vat: 6
vat_name: 6%
RU:
Tax_1:
vat: 18
vat_name: 18%
Tax_2:
vat: 10
vat_name: 10%
SK:
Tax_1:
vat: 19
vat_name: 19%
Tax_2:
vat: 10
vat_name: 10%
Tax_3:
vat: 6
vat_name: 6%
US:
Tax_1:
vat: 0
vat_name: 0%

View File

@@ -0,0 +1,27 @@
Tax:
Tax_1:
vat: 0
vat_name: 0%
Tax_2:
vat: 5
vat_name: 5%
Tax_4:
vat: 8
vat_name: 8%
Tax_5:
vat: 23
is_default: 1
vat_name: 23%
Tax_6:
vat: 0
vat_name: ue
is_system_default: true
Tax_7:
is_active: false
vat: 0
vat_name: ex
is_system_default: true
Tax_8:
vat: 0
vat_name: zw
is_system_default: true

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;
}
}

View File

@@ -0,0 +1,297 @@
<?php
/**
* SOTESHOP/stTaxPlugin
*
* Ten plik należy do aplikacji stTaxPlugin opartej na licencji (Open License SOTE) Otwarta Licencja SOTE.
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stTaxPlugin
* @subpackage actions
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/open (Open License SOTE) Otwarta Licencja SOTE
* @version $Id$
* @author Krzysztof Bebło <krzysztof.beblo@sote.pl>
*/
/**
* stTaxBackend actions.
*
* @package stTaxPlugin
* @subpackage actions
*/
class stTaxBackendActions extends autoStTaxBackendActions
{
public function executeChangePriceType()
{
$type = $this->getRequestParameter('type');
$config = stConfig::getInstance(sfContext::getInstance(), 'stProduct');
$config->set('price_type', $type);
$config->save();
return $this->redirect($this->getRequest()->getReferer());
}
public function executeSave()
{
$tax = TaxPeer::retrieveByPK($this->getRequestParameter('id'));
if (!$tax || $tax->getVat() == $this->getRequestParameter('tax[vat]'))
{
return parent::executeSave();
}
$this->tax = $tax;
}
public function updateTaxFromRequest()
{
if ($this->hasRequestParameter('update_price') && $this->tax->getVat() != $this->getRequestParameter('tax[vat]'))
{
$this->tax->setUpdateResume(array('prev_value' => $this->tax->getVat(), 'type' => $this->getRequestParameter('update_price')));
}
parent::updateTaxFromRequest();
}
public function executeUpdatePrice()
{
$tax = TaxPeer::retrieveByPK($this->getRequestParameter('id'));
if ($params = $tax->getUpdateResume())
{
$c = new Criteria();
$c->add(ProductPeer::TAX_ID, $tax->getId());
$steps['products'] = ProductPeer::doCount($c);
$c = new Criteria();
$c->add(DeliveryPeer::TAX_ID, $tax->getId());
$steps['deliveries'] = DeliveryPeer::doCount($c);
$this->steps = $steps['products'] + $steps['deliveries'];
stTaxProgressBar::setParam('steps', $steps);
}
$params['id'] = $tax->getId();
$params['value'] = $tax->getVat();
stTaxProgressBar::setParam('tax', $params);
$this->params = $params;
$i18n = $this->getContext()->getI18n();
if (isset($params['type']))
{
$this->title = $i18n->__('Przeliczanie cen z %type% dla stawki VAT %tax%%', array(
'%type%' => $i18n->__($params['type'] == 'netto' ? 'brutto na netto' : 'netto na brutto'),
'%tax%' => $params['value']
));
}
else
{
$this->title = $i18n->__('Przeliczanie cen dla stawki VAT %tax%%', array('%tax%' => $params['value']));
}
$this->tax = $tax;
}
public function validateEdit()
{
$tax = $this->getTaxOrCreate();
$i18n = $this->getContext()->getI18N();
$request = $this->getRequest();
if ($tax->getUpdateResume())
{
$message = $i18n->__('Wykryto zmiane stawki VAT. Kliknij').' <a href="'.$this->getController()->genUrl('@stTaxPlugin?action=updatePrice&id='.$tax->getId()).'">'.$i18n->__('tutaj').'</a>, '.$i18n->__('aby dokończyć poprzednią aktualizację cen');
$request->setError('tax', $message);
}
if ($request->getMethod() == sfRequest::POST)
{
$data = $this->getRequestParameter('tax');
$config = stConfig::getInstance('stTaxBackend');
if (isset($data['is_active']) && isset($data['rates_by_country']) && $config->get('is_customer_eu_tax_enabled'))
{
$codes = stTax::getRequiredCountriesCodes();
foreach ($codes as $code)
{
if (!isset($data['rates_by_country'][$code]) || $data['rates_by_country'][$code] === "")
{
$request->setError('tax{rates_by_country}', $i18n->__('Proszę uzupełnić pole.'));
$request->setError('tax{rates_by_country}{'.$code.'}', $i18n->__('Proszę uzupełnić pole.'));
}
}
}
if (!isset($data['is_active']) && !$tax->isNew() && $tax->countProducts() > 0)
{
$request->setError('tax{is_active}', $i18n->__('Nie można wyłączyć stawki VAT "%%tax%%", ponieważ ma przypisane produkty', array('%%tax%%' => $tax->getVatName())));
}
}
return !$request->hasErrors();
}
/**
* {@inheritDoc}
*/
public function getLabels()
{
$i18n = $this->getContext()->getI18N();
$labels = parent::getLabels();
$labels['tax'] = $i18n->__('Zmiana stawki VAT');
return $labels;
}
public function handleErrorSave()
{
$this->handleErrorEdit();
$this->setTemplate('edit');
return sfView::SUCCESS;
}
public function saveTax($tax)
{
$ret = parent::saveTax($tax);
if ($this->hasRequestParameter('update_price'))
{
$con = Propel::getConnection();
$sql = sprintf('UPDATE %1$s, %2$s SET %3$s = ? WHERE %4$s = %5$s AND %6$s = ?',
ProductOptionsValuePeer::TABLE_NAME,
ProductPeer::TABLE_NAME,
ProductOptionsValuePeer::IS_UPDATED,
ProductOptionsValuePeer::PRODUCT_ID,
ProductPeer::ID,
ProductPeer::TAX_ID);
$st = $con->prepareStatement($sql);
$st->setBoolean(1, false);
$st->setInt(2, $tax->getId());
$st->executeQuery();
$this->redirect('stTaxBackend/updatePrice?id='.$tax->getId());
}
return $ret;
}
public function validateConfig()
{
$request = $this->getRequest();
if ($request->getMethod() == sfRequest::POST)
{
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$data = $this->getRequestParameter('config');
$i18n = $this->getContext()->getI18N();
if (isset($data['is_eu_tax_enabled']))
{
if (!stConfig::getInstance('stShopInfoBackend')->get('country'))
{
$error = $i18n->__('Do poprawnego działania %%name%% wymagane jest ustawienie kraju siedziby firmy w %%link%%', array(
'%%name%%' => $i18n->__('VAT UE dla firm'),
'%%link%%' => st_link_to($i18n->__('Konfiguracji informacji o sklepie'), '@stShopInfoPlugin?action=config', array('target' => '_blank'))
));
$request->setError('config{is_eu_tax_enabled}',$error);
}
}
if (isset($data['is_customer_eu_tax_enabled']))
{
$errors = array();
if (!stConfig::getInstance('stShopInfoBackend')->get('country'))
{
$errors[] = $i18n->__('Do poprawnego działania %%name%% wymagane jest ustawienie kraju siedziby firmy w %%link%%', array(
'%%name%%' => $i18n->__('VAT UE dla konsumentów'),
'%%link%%' => st_link_to($i18n->__('Konfiguracji informacji o sklepie'), '@stShopInfoPlugin?action=config', array('target' => '_blank'))
));
}
$required = stTax::getRequiredCountriesCodes();
$i18n = $this->getContext()->getI18N();
foreach (TaxPeer::doSelectActive() as $tax)
{
if ($tax->isSystemDefault())
{
continue;
}
$rates = $tax->getRatesByCountry();
foreach ($required as $code)
{
if (!isset($rates[$code]) || $rates[$code] === "")
{
$errors[] = $i18n->__('is.customer.eu.tax.enabled.help');
break 2;
}
}
}
if ($errors)
{
$request->setError('config{is_customer_eu_tax_enabled}', implode('<br>', $errors));
}
}
}
return !$request->hasErrors();
}
/**
* {@inheritDoc}
*/
protected function getTaxOrCreate($id = 'id')
{
$tax = parent::getTaxOrCreate($id);
if ($tax->isSystemDefault())
{
$this->hideField('rates_by_country');
}
return $tax;
}
protected function deleteTax($tax)
{
if ($tax->countProducts() > 0)
{
$i18n = $this->getContext()->getI18N();
throw new Exception($i18n->__('Nie można usunąć stawki VAT "%%tax%%", ponieważ ma przypisane produkty', array('%%tax%%' => $tax->getVatName())));
}
return parent::deleteTax($tax);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* SOTESHOP/stTaxPlugin
*
* Ten plik należy do aplikacji stTaxPlugin opartej na licencji (Open License SOTE) Otwarta Licencja SOTE.
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stTaxPlugin
* @subpackage actions
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/open (Open License SOTE) Otwarta Licencja SOTE
* @version $Id$
* @author Krzysztof Bebło <krzysztof.beblo@sote.pl>
*/
/**
* Klasa stTaxBackendComponents
*
* @package stTaxPlugin
* @subpackage actions
*/
class stTaxBackendComponents extends autoStTaxBackendComponents
{
public function executeRatesByCountry()
{
$rates = stTax::getEUTaxRates();
$countries = stTax::getCountriesForConsumerEuRates();
$requiredCountries = stTax::getRequiredCountriesCodes();
$requiredRates = array();
$moreRates = array();
$i18n = $this->getContext()->getI18N();
$config = stConfig::getInstance('stShopInfoBackend');
foreach ($rates as $countryCode => $rate)
{
if ($config->get('country') != $countryCode)
{
$allRates = array($rate['normal']);
$allRates = array_merge($allRates, $rate['reduced']);
$allRates = array_combine($allRates, $allRates);
$allRates = array_map(function($value) {
return $value . ' %';
}, $allRates);
$defaultRate = key($allRates);
$allRates[$defaultRate] = $allRates[$defaultRate] . ' ' . $i18n->__('Podstawowa');
if (in_array($countryCode, $requiredCountries))
{
$requiredRates[$countryCode] = $allRates;
}
else
{
$moreRates[$countryCode] = $allRates;
}
}
}
$this->requiredRates = $requiredRates;
$this->moreRates = $moreRates;
$this->countries = $countries;
$this->values = $this->tax->getRatesByCountry();
}
}

View File

@@ -0,0 +1,57 @@
generator:
class: stAdminGenerator
param:
model_class: Tax
theme: simple
head:
package: stTaxPlugin
documentation:
pl: https://www.sote.pl/docs/vat
en: https://www.soteshop.com/docs/tax
list:
title: Lista
menu:
display: [list]
fields:
list: {name: Lista stawek VAT, action: "@stTaxPlugin?action=list"}
display: [vat_name, _vat_list, is_default, is_active]
fields:
is_active: {name: Aktywna}
vat_list: {name: Domyślna stawka, sort_field: tax.vat}
vat_name: {name: Nazwa}
is_default: {name: Domyślny VAT}
actions:
_create: {name: Dodaj}
object_actions:
_edit: -
_delete: -
empty_message: Brak stawek VAT
edit:
title: Edycja stawki VAT
display:
NONE: [is_active, _edit_is_default, _vat_name, _vat, ~rates_by_country]
fields:
is_active: {name: Aktywna, required: false }
vat: {name: Domyślna stawka, help: "default.vat.rate.help"}
vat_name: {name: Nazwa}
edit_is_default: {name: Domyślny VAT, help: Domyślnie wybrana stawka VAT podczas dodawania nowego produktu lub dostawy}
rates_by_country: {name: VAT UE dla konsumentów, help: "vat.ue.for.consumer.help"}
actions:
_delete: {name: Usuń}
_list: {name: Lista}
_save: {name: Zapisz}
_save_and_add: {name: Zapisz i dodaj}
config:
menu: {use: list.menu}
title: Konfiguracja
display: [is_eu_tax_enabled, is_customer_eu_tax_enabled]
fields:
is_eu_tax_enabled: {name: "Włącz VAT UE dla firm", type: checkbox_tag}
is_customer_eu_tax_enabled: {name: "Włącz VAT UE dla konsumentów", type: checkbox_tag, help: "is.customer.eu.tax.enabled.help"}
actions:
_save: {name: Zapisz}

View File

@@ -0,0 +1,2 @@
<?php echo input_hidden_tag('tax[edit_is_default]', $tax->getIsDefault()) ?>
<?php echo st_admin_checkbox_tag('tax[edit_is_default]', 1, $tax->getIsDefault(), array('disabled' => $tax->getIsDefault())) ?>

View File

@@ -0,0 +1,39 @@
<?php if (!empty($requiredRates)): ?>
<?php echo st_admin_table_start() ?>
<thead>
<tr>
<th style="width: 200px"><?php echo __("Kraj dostawy wg konfiguracji") ?></th>
<th><?php echo __("Stawka VAT") ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($countries as $countryCode => $country):
if (!isset($requiredRates[$countryCode])) continue;
$rates = $requiredRates[$countryCode];
$value = isset($values[$countryCode]) && $values[$countryCode] !== "" ? $values[$countryCode] : null;
?>
<tr>
<td style="text-align: right"><b><?php echo $country ?></b></td>
<td><?php echo select_tag('tax[rates_by_country]['.$countryCode.']', options_for_select($rates, $value, array('include_custom' => '---')), array(
'class' => null !== $value ? 'not-required' : '',
'style' => 'width: 200px',
)) ?></td>
</tr>
<?php endforeach ?>
</tbody>
<?php echo st_admin_table_end() ?>
<?php endif ?>
<?php echo st_admin_table_start(array(
array('label' => __("Kraj"), 'options' => array('style' => 'width: 200px')),
array('label' => __("Stawka VAT")),
), array('style' => 'margin-top: 10px')) ?>
<tbody>
<?php foreach ($countries as $countryCode => $country): if (!isset($moreRates[$countryCode])) continue; $rates = $moreRates[$countryCode] ?>
<tr>
<td style="text-align: right"><?php echo $country ?></td>
<td><?php echo select_tag('tax[rates_by_country]['.$countryCode.']', options_for_select($rates, isset($values[$countryCode]) ? $values[$countryCode] : null, array('include_custom' => '---')), array('style' => 'width: 200px', 'class' => 'not-required')) ?></td>
</tr>
<?php endforeach ?>
</tbody>
<?php echo st_admin_table_end() ?>

View File

@@ -0,0 +1,13 @@
<?php
echo object_input_tag($tax, $method, array(
'size' => 7,
'control_name' => $name,
'disabled' => $tax->getIsSystemDefault(),
));
if ($tax->getIsSystemDefault())
{
echo input_hidden_tag($name, $tax->$method());
}
?> %

View File

@@ -0,0 +1 @@
<?php echo $tax->getVat() ?> %

View File

@@ -0,0 +1,12 @@
<?php
echo object_input_tag($tax, $method, array(
'size' => 14,
'control_name' => $name,
'disabled' => $tax->getIsSystemDefault(),
));
if ($tax->getIsSystemDefault())
{
echo input_hidden_tag($name, $tax->$method());
}

View File

@@ -0,0 +1,40 @@
<?php use_helper('stAdminGenerator') ?>
<?php st_include_partial('stTaxBackend/header', array('related_object' => $tax, 'title' => __('Edycja stawki VAT'), 'route' => 'stTaxBackend/edit?id='.$tax->getId())) ?>
<div id="sf_admin_content">
<div class="form-errors">
<h2><?php echo __('Wykryto zmiane stawki VAT z %from%% na %to%%. Wybierz metodę przeliczenia obecnych cen w sklepie', array('%from%' => $tax->getVat(), '%to%' => $sf_request->getParameter('tax[vat]'))) ?></h2>
</div>
<form class="admin_form" id="admin_edit_form" action="<?php echo st_url_for('stTaxBackend/edit?id='.$tax->getId()) ?>" method="post">
<fieldset>
<div class="content">
<?php
foreach ($sf_request->getParameter('tax') as $name1 => $value1)
{
if (is_array($value1))
{
foreach ($value1 as $name2 => $value2)
{
echo input_hidden_tag('tax['.$name1.']['.$name2.']', $value2);
}
}
else
{
echo input_hidden_tag('tax['.$name1.']', $value1);
}
}
?>
<?php echo st_admin_get_form_field('update_price', __('Przelicz').':', array('brutto' => __('netto na brutto'), 'netto' => __('brutto na netto')), 'select_tag', array(
'help' => __('<b>netto na brutto</b> - ceny brutto ulegną zmianie<br/><b>brutto na netto</b> - ceny netto ulegną zmianie')
.'<br /><b>'.__('przeliczeniu ulegną').':</b><ul style="list-style: circle inside"><li>'.__('ceny produktów').'</li><li>'.__('koszty dostaw').'</li></ul>')); ?>
</div>
</fieldset>
<?php echo st_get_admin_actions_head(); ?>
<?php echo st_get_admin_action('reset', __('Anuluj', null, 'stAdminGeneratorPlugin'), 'stTaxBackend/edit?id='.$tax->getId()); ?>
<?php echo st_get_admin_action('save', __('Zapisz', null, 'stAdminGeneratorPlugin')); ?>
<?php echo st_get_admin_actions_foot(); ?>
</form>
</div>
<?php st_include_partial('stTaxBackend/footer', array('related_object' => $tax)) ?>

View File

@@ -0,0 +1,10 @@
<?php use_helper('stProgressBar', 'stAdminGenerator', 'stUrl'); ?>
<?php echo st_get_admin_head('stTaxPlugin', null, __('Zarządzaj stawkami VAT'), array('stMailPlugin')) ?>
<div id="sf_admin_content">
<h2 id="st_admin_title"><?php echo __('Przeliczanie cen dla stawki VAT %tax%%', array('%tax%' => $tax->getVat())) ?></h2>
<p><?php echo __('Aktualizacja cen została zakończona pomyślnie.<br/>%return_link%', array('%return_link%' => st_link_to(__('Powróć do edycji'),'stTaxBackend/edit?id='.$this->tax['id']))); ?></p>
</div>
<br class="st_clear_all" />
<?php echo st_get_admin_foot() ?>

View File

@@ -0,0 +1,28 @@
<?php use_helper('stProgressBar', 'stAdminGenerator'); ?>
<?php st_include_partial('stTaxBackend/header', array('related_object' => $tax, 'title' => $title, 'route' => 'stTaxBackend/edit?id='.$tax->getId())) ?>
<style type="text/css">
#tax_progress_bar {
padding: 10px;
text-align: center;
width: 280px;
margin: 0 auto;
}
#tax_progress_bar .stPrograssBar-main-div {
margin: 0 auto;
}
</style>
<div id="sf_admin_content">
<div class="fieldset" id="tax_progress_bar">
<?php if (isset($params['type'])): ?>
<?php echo progress_bar('stTax', 'stTaxProgressBar', 'updateProductPrice', $steps); ?>
<?php else: ?>
<p><?php echo __('Aktualizacja cen została zakończona pomyślnie.<br/>%return_link%', array('%return_link%' => st_link_to(__('Powróć do edycji'),'stTaxBackend/edit?id='.$tax->getId()))); ?></p>
<?php endif; ?>
</div>
</div>
<?php st_include_partial('stTaxBackend/footer', array('related_object' => $tax)) ?>

View File

@@ -0,0 +1,13 @@
fields:
tax{vat}:
required:
msg: Podaj VAT
sfNumberValidator:
nan_error: VAT musi być liczbą, a części dziesiętne należy wprowadzić z kropką (.)
min: 0
min_error: VAT nie może być mniejszy niż 0 %
max: 99.99
max_error: VAT musi być mniejszy niż 100 %
tax{vat_name}:
required:
msg: Podaj nazwę stawki VAT

View File

@@ -0,0 +1,13 @@
fields:
tax{vat}:
required:
msg: Podaj VAT
sfNumberValidator:
nan_error: VAT musi być liczbą, a części dziesiętne należy wprowadzić z kropką (.)
min: 0
min_error: VAT nie może być mniejszy niż 0 %
max: 99.99
max_error: VAT musi być mniejszy niż 100 %
tax{vat_name}:
required:
msg: Podaj nazwę stawki VAT