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,30 @@
<?php
function show_paczkomaty_dropdown_list($name, $selected = '', $params = array()) {
static $machines = null;
$list = stPaczkomatyMachines::getListOfMachinesByParam(isset($params['paczkomaty']) ? $params['paczkomaty'] : array());
$machines = array();
foreach ($list as $m)
{
$machines[$m['number']] = array(
'id' => $m['number'],
'name' => $m['number'].': '.$m['street'].' '.$m['house'].', '.$m['postCode'].' '.$m['city']
);
}
if ($selected && $selected != 'NONE' && isset($machines[$selected]))
{
$defaults = array(
$machines[$selected],
);
}
else
{
$defaults = array();
}
echo st_tokenizer_input_tag($name, array_values($machines), $defaults, array('tokenizer' => array('preventDuplicates' => true, 'hintText' => __('Wpisz szukany paczkomat'), 'tokenLimit' => 1)));
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Subclass for representing a row from the 'st_paczkomaty_dispatch_order' table.
*
*
*
* @package plugins.stPaczkomatyPlugin.lib.model
*/
class PaczkomatyDispatchOrder extends BasePaczkomatyDispatchOrder
{
public function __toString()
{
return null !== $this->getDispatchOrderExternalId() ? $this->getDispatchOrderExternalId() : '';
}
public function getParcels()
{
$trackingNumbers = [];
foreach ($this->getPaczkomatyPacks() as $pack)
{
$trackingNumbers[] = $pack->getTrackingNumber();
}
return implode(', ', $trackingNumbers);
}
public function getStatusLabel()
{
return stInPostApi::getInstance()->getDispatchOrderStatusTitleByName($this->status);
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Subclass for performing query and update operations on the 'st_paczkomaty_dispatch_order' table.
*
*
*
* @package plugins.stPaczkomatyPlugin.lib.model
*/
class PaczkomatyDispatchOrderPeer extends BasePaczkomatyDispatchOrderPeer
{
public static function doSelectWithShipX(Criteria $c, $con = null)
{
/**
* @var PaczkomatyDispatchOrder[]
*/
$results = [];
$ids = [];
foreach (parent::doSelect($c, $con) as $index => $result)
{
$ids[] = $result->getDispatchOrderId();
$results[empty($result->getDispatchOrderId()) ? $index : $result->getDispatchOrderId()] = $result;
}
$api = stInPostApi::getInstance();
$response = $api->getDispatchOrders($ids);
foreach ($response->items as $item)
{
if (isset($results[$item->id]))
{
$results[$item->id]->setStatus($item->status);
$results[$item->id]->save();
}
}
return $results;
}
}

View File

@@ -0,0 +1,351 @@
<?php
class PaczkomatyPack extends BasePaczkomatyPack
{
protected $allegroTransaction = null;
protected $sendingMethod = null;
protected $dropoffPoint = null;
protected $endOfWeekCollection = false;
public function isAdminGeneratorPlainField(): bool
{
return !$this->isNew() && !in_array($this->getStatus(), array('created', 'offers_prepared', 'offer_selected'));
}
public function isAdminGeneratorActionVisible(string $name): bool
{
if ($name == 'download_label' && empty($this->getTrackingNumber()))
{
return false;
}
if ($name == 'dispatch_order' && (!stDeliveryTypeConfiguration::has('inpostk') || $this->getSendingMethod() != 'dispatch_order' || null !== $this->getDispatchOrderId() || empty($this->getTrackingNumber())))
{
return false;
}
if ($name == '_delete' && !empty($this->getStatus()) && !in_array($this->getStatus(), ['created', 'offers_prepared', 'offer_selected']))
{
return false;
}
return true;
}
public function getServiceType(): string
{
return $this->getOrder()->getOrderDelivery()->getDeliveryTypeService()->getLabel();
}
public function getOrderNumber()
{
return $this->getOrder() ? $this->getOrder()->getNumber() : null;
}
public function setOrder($order)
{
if ($this->isNew() && null === $this->aOrder)
{
parent::setOrder($order);
$userData = $order->getOrderUserDataDelivery();
$this->setCustomerEmail($order->getOptClientEmail());
$this->setCustomerPhone($userData->getPhone());
$this->setCustomerPickupPoint($order->getOrderDelivery()->getPickupPoint());
$this->setEndOfWeekCollection($order->getOrderDelivery()->getIsWeekendDelivery());
if ($this->hasCourierService())
{
$address = $userData->getAddress();
if (!empty($userData->getAddressMore()))
{
$address .= ' ' . $userData->getAddressMore();
}
$addressParser = new stAddressParser($address);
$this->setCustomerCompanyName($userData->getCompany());
$this->setCustomerName($userData->getFullName());
$this->setCustomerStreet($addressParser->getStreet());
$this->setCustomerBuildingNumber($addressParser->getBuilding(true));
$this->setCustomerCity($userData->getTown());
$this->setCustomerCountryCode($userData->getCountries()->getIsoA2());
$this->setCustomerPostCode($userData->getCode());
$this->setCustomerPhone($userData->getPhone());
}
if ($order->getOrderDelivery()->getDelivery())
{
$this->setPackType($order->getOrderDelivery()->getDelivery()->getPaczkomatySize());
}
}
}
public function getService()
{
$service = parent::getService();
if (null === $service)
{
$orderDelivery = $this->getOrder()->getOrderDelivery();
if ($this->getOrder()->isAllegroOrder())
{
$service = stInPostApi::getAllegroDeliveryToServiceMapping($orderDelivery->getOptAllegroDeliveryMethodId());
}
else
{
$service = $orderDelivery->getDeliveryTypeService()->getConfiguration()->getType() == 'inpostp' ? 'inpost_locker_standard' : 'inpost_courier_standard';
}
$this->setService($service);
}
return $service;
}
public function hasCourierService()
{
return in_array($this->getService(), stInPostApi::COURIER_SERVICES);
}
public function setCustomerPhone($v)
{
$v = str_replace(array('+48', ' ', '-'), '', $v);
return parent::setCustomerPhone($v);
}
public function setCustomerPickupPoint($v)
{
$this->setCustomerPaczkomat($v);
}
public function getCustomerPickupPoint()
{
return $this->getCustomerPaczkomat();
}
public function setDropOffPoint($v)
{
$this->dropoffPoint = $v;
}
public function getDropOffPoint()
{
return $this->dropoffPoint;
}
public function setEndOfWeekCollection($v)
{
$this->endOfWeekCollection = $v;
}
public function getEndOfWeekCollection()
{
return $this->endOfWeekCollection;
}
public function setTrackingNumber($v)
{
$this->setCode($v);
}
public function getTrackingNumber()
{
return $this->getCode();
}
public function getStatusLabel()
{
if (!$this->isAdminGeneratorPlainField())
{
return null;
}
$status = null;
$api = stInPostApi::getInstance();
if ($this->status)
{
try
{
$status = $api->getStatusTitleByName($this->status);
}
catch (stInPostApiException $e)
{
$status = null;
}
}
return $status;
}
/**
* Zwraca predefiniowany formiar paczki
*
* @return string Zwraca 'small', 'medium' or 'large'
*/
public function getParcelTemplate()
{
$templates = array(
'A' => 'small',
'B' => 'medium',
'C' => 'large',
);
return $templates[$this->getPackType()];
}
public function setParcelTemplate($template)
{
$types = array(
'small' => 'A',
'medium' => 'B',
'large' => 'C',
);
$this->setPackType($types[$template]);
}
public function delete($con = null)
{
$ret = parent::delete($con);
$delivery = $this->getOrder()->getOrderDelivery();
$delivery->setNumber(null);
$delivery->save();
return $ret;
}
public function save($con = null)
{
$orderNumberModified = $this->isColumnModified(PaczkomatyPackPeer::CODE);
$pickupPointModified = $this->isColumnModified(PaczkomatyPackPeer::CUSTOMER_PACZKOMAT);
$ret = parent::save($con);
if ($orderNumberModified)
{
$orderDelivery = $this->getOrder()->getOrderDelivery();
if ($orderDelivery)
{
$orderDelivery->setNumber($this->getTrackingNumber());
$orderDelivery->save();
}
}
if ($pickupPointModified)
{
$orderUserDataDelivery = $this->getOrder()->getOrderUserDataDelivery();
if ($orderUserDataDelivery)
{
$pickupPoint = stInPostApi::getInstance()->getPoint($this->getCustomerPickupPoint());
$address = $pickupPoint->address_details->street . ' ' . $pickupPoint->address_details->building_number;
if ($pickupPoint->address_details->flat_number)
{
$address .= '/' . $pickupPoint->address_details->flat_number;
}
$orderUserDataDelivery->setCompany('Paczkomat - ' . $pickupPoint->name);
$orderUserDataDelivery->setFullName(null);
$orderUserDataDelivery->setAddress($address);
$orderUserDataDelivery->setCode($pickupPoint->address_details->post_code);
$orderUserDataDelivery->setAddressMore(null);
$orderUserDataDelivery->setTown($pickupPoint->address_details->city);
$orderUserDataDelivery->save();
}
}
return $ret;
}
public function getCashOnDelivery($fetchFromOrder = false)
{
$amount = parent::getCashOnDelivery();
if (null === $amount && $fetchFromOrder)
{
$amount = stPrice::round($this->getOrder()->getUnpaidAmount());
if ($this->getOrder()->getOrderCurrency() != 'PLN')
{
$amount = $this->getOrder()->getOrderCurrency()->exchange($amount, true);
}
}
return $amount;
}
public function hasAllegroTransactionId()
{
return $this->getOrder()->isAllegroOrder();
}
public function hasAllegroInsurance()
{
return $this->hasAllegroTransactionId() && ($this->getOrder()->getOptTotalAmount() - $this->getOrder()->getOrderDelivery()->getCost(true) <= 5000);
}
public function getAllegroTransactionId()
{
if (null === $this->allegroTransaction)
{
if ($this->getOrder()->getOptAllegroCheckoutFormId() && !is_numeric($this->getOrder()->getOrderPayment()->getTransactionId()))
{
$api = stAllegroApi::getInstance();
$this->allegroTransaction = $api->getPaymentMapping($this->getOrder()->getOrderPayment()->getTransactionId());
}
else
{
$order = $this->getOrder();
$c = new Criteria();
$c->add(AllegroAuctionHasOrderPeer::ORDER_ID, $order->getId());
$allegroTransaction = AllegroAuctionHasOrderPeer::doSelectOne($c);
$this->allegroTransaction = $allegroTransaction ? $allegroTransaction->getTransId() : null;
}
}
return $this->allegroTransaction;
}
public function getInsurance($fetchFromOrder = false)
{
$amount = parent::getInsurance();
if (!$amount && $fetchFromOrder)
{
$amount = $this->getOrder()->getTotalAmount(true, true);
if ($this->getOrder()->getOrderCurrency() != 'PLN')
{
$amount = $this->getOrder()->getOrderCurrency()->exchange($amount, true);
}
}
return $amount;
}
public function hasCashOnDelivery()
{
if ($this->getHasCashOnDelivery())
{
return true;
}
$payment = $this->getOrder()->getOrderPayment();
return $payment && $payment->getPaymentType()->getIsCod();
}
}

View File

@@ -0,0 +1,63 @@
<?php
class PaczkomatyPackPeer extends BasePaczkomatyPackPeer {
public static function retrieveByCode($code, $con = null) {
$c = new Criteria();
$c->add(PaczkomatyPackPeer::CODE, $code);
return PaczkomatyPackPeer::doSelectOne($c, $con);
}
public static function retrieveByOrder(Order $order)
{
$c = new Criteria();
$c->add(self::ORDER_ID, $order->getId());
$c->addDescendingOrderByColumn(self::ID);
return self::doSelectOne($c);
}
public static function retrieveByPKsOrder(array $pks)
{
$c = new Criteria();
$c->add(self::ID, $pks, Criteria::IN);
$c->addOrderByField(self::ID, $pks);
return self::doSelect($c);
}
public static function doSelectWithShipX(Criteria $c, $con = null)
{
/**
* @var PaczkomatyPack[]
*/
$results = [];
$ids = [];
foreach (self::doSelectJoinAll($c) as $result)
{
$results[$result->getInpostShipmentId()] = $result;
$ids[] = $result->getInpostShipmentId();
}
$api = stInPostApi::getInstance();
$response = $api->getShipmentsById($ids);
foreach ($response->items as $item)
{
if (isset($results[$item->id]))
{
$pack = $results[$item->id];
$pack->setStatus($item->status);
if (empty($pack->getTrackingNumber()) && !empty($item->tracking_number))
{
$pack->setTrackingNumber($item->tracking_number);
}
$pack->save();
}
}
return $results;
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* This class adds structure of 'st_paczkomaty_dispatch_order' 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.stPaczkomatyPlugin.lib.model.map
*/
class PaczkomatyDispatchOrderMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stPaczkomatyPlugin.lib.model.map.PaczkomatyDispatchOrderMapBuilder';
/**
* 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_paczkomaty_dispatch_order');
$tMap->setPhpName('PaczkomatyDispatchOrder');
$tMap->setUseIdGenerator(true);
$tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('DISPATCH_ORDER_ID', 'DispatchOrderId', 'string', CreoleTypes::BIGINT, false, null);
$tMap->addColumn('DISPATCH_ORDER_EXTERNAL_ID', 'DispatchOrderExternalId', 'string', CreoleTypes::BIGINT, false, null);
$tMap->addColumn('CREATED_AT', 'CreatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('STATUS', 'Status', 'string', CreoleTypes::VARCHAR, false, 16);
} // doBuild()
} // PaczkomatyDispatchOrderMapBuilder

View File

@@ -0,0 +1,122 @@
<?php
/**
* This class adds structure of 'st_paczkomaty_pack' 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.stPaczkomatyPlugin.lib.model.map
*/
class PaczkomatyPackMapBuilder {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'plugins.stPaczkomatyPlugin.lib.model.map.PaczkomatyPackMapBuilder';
/**
* 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_paczkomaty_pack');
$tMap->setPhpName('PaczkomatyPack');
$tMap->setUseIdGenerator(true);
$tMap->addColumn('CREATED_AT', 'CreatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addColumn('UPDATED_AT', 'UpdatedAt', 'int', CreoleTypes::TIMESTAMP, false, null);
$tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('CUSTOMER_EMAIL', 'CustomerEmail', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('CUSTOMER_PHONE', 'CustomerPhone', 'string', CreoleTypes::VARCHAR, false, 24);
$tMap->addColumn('CUSTOMER_NAME', 'CustomerName', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('CUSTOMER_COMPANY_NAME', 'CustomerCompanyName', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('CUSTOMER_STREET', 'CustomerStreet', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('CUSTOMER_BUILDING_NUMBER', 'CustomerBuildingNumber', 'string', CreoleTypes::VARCHAR, false, 24);
$tMap->addColumn('CUSTOMER_CITY', 'CustomerCity', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('CUSTOMER_POST_CODE', 'CustomerPostCode', 'string', CreoleTypes::VARCHAR, false, 16);
$tMap->addColumn('CUSTOMER_COUNTRY_CODE', 'CustomerCountryCode', 'string', CreoleTypes::CHAR, false, 2);
$tMap->addColumn('CUSTOMER_PACZKOMAT', 'CustomerPaczkomat', 'string', CreoleTypes::VARCHAR, false, 48);
$tMap->addColumn('SENDING_METHOD', 'SendingMethod', 'string', CreoleTypes::VARCHAR, false, 48);
$tMap->addColumn('SENDER_PACZKOMAT', 'SenderPaczkomat', 'string', CreoleTypes::VARCHAR, false, 24);
$tMap->addColumn('USE_SENDER_PACZKOMAT', 'UseSenderPaczkomat', 'boolean', CreoleTypes::BOOLEAN, false, null);
$tMap->addColumn('PACK_TYPE', 'PackType', 'string', CreoleTypes::CHAR, false, 1);
$tMap->addColumn('INPOST_SHIPMENT_ID', 'InpostShipmentId', 'int', CreoleTypes::INTEGER, false, null);
$tMap->addColumn('INSURANCE', 'Insurance', 'double', CreoleTypes::DECIMAL, false, 10);
$tMap->addColumn('CASH_ON_DELIVERY', 'CashOnDelivery', 'double', CreoleTypes::DECIMAL, false, 10);
$tMap->addColumn('DESCRIPTION', 'Description', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('PARCELS', 'Parcels', 'array', CreoleTypes::VARCHAR, false, 8192);
$tMap->addColumn('SERVICE', 'Service', 'string', CreoleTypes::VARCHAR, false, 48);
$tMap->addColumn('CODE', 'Code', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addColumn('HAS_CASH_ON_DELIVERY', 'HasCashOnDelivery', 'boolean', CreoleTypes::BOOLEAN, false, null);
$tMap->addColumn('STATUS', 'Status', 'string', CreoleTypes::VARCHAR, false, 255);
$tMap->addForeignKey('ORDER_ID', 'OrderId', 'int', CreoleTypes::INTEGER, 'st_order', 'ID', false, null);
$tMap->addForeignKey('DISPATCH_ORDER_ID', 'DispatchOrderId', 'int', CreoleTypes::INTEGER, 'st_paczkomaty_dispatch_order', 'ID', false, null);
} // doBuild()
} // PaczkomatyPackMapBuilder

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,691 @@
<?php
/**
* Base static class for performing query and update operations on the 'st_paczkomaty_dispatch_order' table.
*
*
*
* @package plugins.stPaczkomatyPlugin.lib.model.om
*/
abstract class BasePaczkomatyDispatchOrderPeer {
/** the default database name for this class */
const DATABASE_NAME = 'propel';
/** the table name for this class */
const TABLE_NAME = 'st_paczkomaty_dispatch_order';
/** A class that can be returned by this peer. */
const CLASS_DEFAULT = 'plugins.stPaczkomatyPlugin.lib.model.PaczkomatyDispatchOrder';
/** The total number of columns. */
const NUM_COLUMNS = 5;
/** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0;
/** the column name for the ID field */
const ID = 'st_paczkomaty_dispatch_order.ID';
/** the column name for the DISPATCH_ORDER_ID field */
const DISPATCH_ORDER_ID = 'st_paczkomaty_dispatch_order.DISPATCH_ORDER_ID';
/** the column name for the DISPATCH_ORDER_EXTERNAL_ID field */
const DISPATCH_ORDER_EXTERNAL_ID = 'st_paczkomaty_dispatch_order.DISPATCH_ORDER_EXTERNAL_ID';
/** the column name for the CREATED_AT field */
const CREATED_AT = 'st_paczkomaty_dispatch_order.CREATED_AT';
/** the column name for the STATUS field */
const STATUS = 'st_paczkomaty_dispatch_order.STATUS';
/** 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', 'DispatchOrderId', 'DispatchOrderExternalId', 'CreatedAt', 'Status', ),
BasePeer::TYPE_COLNAME => array (PaczkomatyDispatchOrderPeer::ID, PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_ID, PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_EXTERNAL_ID, PaczkomatyDispatchOrderPeer::CREATED_AT, PaczkomatyDispatchOrderPeer::STATUS, ),
BasePeer::TYPE_FIELDNAME => array ('id', 'dispatch_order_id', 'dispatch_order_external_id', 'created_at', 'status', ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, )
);
/**
* 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, 'DispatchOrderId' => 1, 'DispatchOrderExternalId' => 2, 'CreatedAt' => 3, 'Status' => 4, ),
BasePeer::TYPE_COLNAME => array (PaczkomatyDispatchOrderPeer::ID => 0, PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_ID => 1, PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_EXTERNAL_ID => 2, PaczkomatyDispatchOrderPeer::CREATED_AT => 3, PaczkomatyDispatchOrderPeer::STATUS => 4, ),
BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'dispatch_order_id' => 1, 'dispatch_order_external_id' => 2, 'created_at' => 3, 'status' => 4, ),
BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, )
);
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.stPaczkomatyPlugin.lib.model.map.PaczkomatyDispatchOrderMapBuilder');
}
/**
* 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 = PaczkomatyDispatchOrderPeer::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. PaczkomatyDispatchOrderPeer::COLUMN_NAME).
* @return string
*/
public static function alias($alias, $column)
{
return str_replace(PaczkomatyDispatchOrderPeer::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(PaczkomatyDispatchOrderPeer::ID);
$criteria->addSelectColumn(PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_ID);
$criteria->addSelectColumn(PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_EXTERNAL_ID);
$criteria->addSelectColumn(PaczkomatyDispatchOrderPeer::CREATED_AT);
$criteria->addSelectColumn(PaczkomatyDispatchOrderPeer::STATUS);
if (stEventDispatcher::getInstance()->getListeners('PaczkomatyDispatchOrderPeer.postAddSelectColumns')) {
stEventDispatcher::getInstance()->notify(new sfEvent($criteria, 'PaczkomatyDispatchOrderPeer.postAddSelectColumns'));
}
}
const COUNT = 'COUNT(st_paczkomaty_dispatch_order.ID)';
const COUNT_DISTINCT = 'COUNT(DISTINCT st_paczkomaty_dispatch_order.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(PaczkomatyDispatchOrderPeer::COUNT_DISTINCT);
} else {
$criteria->addSelectColumn(PaczkomatyDispatchOrderPeer::COUNT);
}
// just in case we're grouping: add those columns to the select statement
foreach($criteria->getGroupByColumns() as $column)
{
$criteria->addSelectColumn($column);
}
$rs = PaczkomatyDispatchOrderPeer::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 PaczkomatyDispatchOrder
* @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 = PaczkomatyDispatchOrderPeer::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 PaczkomatyDispatchOrder[]
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doSelect(Criteria $criteria, $con = null)
{
return PaczkomatyDispatchOrderPeer::populateObjects(PaczkomatyDispatchOrderPeer::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;
PaczkomatyDispatchOrderPeer::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 = PaczkomatyDispatchOrderPeer::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 PaczkomatyDispatchOrderPeer::CLASS_DEFAULT;
}
/**
* Method perform an INSERT on the database, given a PaczkomatyDispatchOrder or Criteria object.
*
* @param mixed $values Criteria or PaczkomatyDispatchOrder 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('BasePaczkomatyDispatchOrderPeer:doInsert:pre') as $callable)
{
$ret = call_user_func($callable, 'BasePaczkomatyDispatchOrderPeer', $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 PaczkomatyDispatchOrder object
}
$criteria->remove(PaczkomatyDispatchOrderPeer::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('BasePaczkomatyDispatchOrderPeer:doInsert:post') as $callable)
{
call_user_func($callable, 'BasePaczkomatyDispatchOrderPeer', $values, $con, $pk);
}
return $pk;
}
/**
* Method perform an UPDATE on the database, given a PaczkomatyDispatchOrder or Criteria object.
*
* @param mixed $values Criteria or PaczkomatyDispatchOrder 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('BasePaczkomatyDispatchOrderPeer:doUpdate:pre') as $callable)
{
$ret = call_user_func($callable, 'BasePaczkomatyDispatchOrderPeer', $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(PaczkomatyDispatchOrderPeer::ID);
$selectCriteria->add(PaczkomatyDispatchOrderPeer::ID, $criteria->remove(PaczkomatyDispatchOrderPeer::ID), $comparison);
} else { // $values is PaczkomatyDispatchOrder 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('BasePaczkomatyDispatchOrderPeer:doUpdate:post') as $callable)
{
call_user_func($callable, 'BasePaczkomatyDispatchOrderPeer', $values, $con, $ret);
}
return $ret;
}
/**
* Method to DELETE all rows from the st_paczkomaty_dispatch_order 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();
PaczkomatyDispatchOrderPeer::doOnDeleteSetNull(new Criteria(), $con);
$affectedRows += BasePeer::doDeleteAll(PaczkomatyDispatchOrderPeer::TABLE_NAME, $con);
$con->commit();
return $affectedRows;
} catch (PropelException $e) {
$con->rollback();
throw $e;
}
}
/**
* Method perform a DELETE on the database, given a PaczkomatyDispatchOrder or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or PaczkomatyDispatchOrder 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(PaczkomatyDispatchOrderPeer::DATABASE_NAME);
}
if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity
} elseif ($values instanceof PaczkomatyDispatchOrder) {
$criteria = $values->buildPkeyCriteria();
} else {
// it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(PaczkomatyDispatchOrderPeer::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();
PaczkomatyDispatchOrderPeer::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 = PaczkomatyDispatchOrderPeer::doSelect($criteria, $con);
foreach($objects as $obj) {
// set fkey col in related PaczkomatyPack rows to NULL
$selectCriteria = new Criteria(PaczkomatyDispatchOrderPeer::DATABASE_NAME);
$updateValues = new Criteria(PaczkomatyDispatchOrderPeer::DATABASE_NAME);
$selectCriteria->add(PaczkomatyPackPeer::DISPATCH_ORDER_ID, $obj->getId());
$updateValues->add(PaczkomatyPackPeer::DISPATCH_ORDER_ID, null);
BasePeer::doUpdate($selectCriteria, $updateValues, $con); // use BasePeer because generated Peer doUpdate() methods only update using pkey
}
}
/**
* Validates all modified columns of given PaczkomatyDispatchOrder 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 PaczkomatyDispatchOrder $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(PaczkomatyDispatchOrder $obj, $cols = null)
{
$columns = array();
if ($cols) {
$dbMap = Propel::getDatabaseMap(PaczkomatyDispatchOrderPeer::DATABASE_NAME);
$tableMap = $dbMap->getTable(PaczkomatyDispatchOrderPeer::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(PaczkomatyDispatchOrderPeer::DATABASE_NAME, PaczkomatyDispatchOrderPeer::TABLE_NAME, $columns);
if ($res !== true) {
$request = sfContext::getInstance()->getRequest();
foreach ($res as $failed) {
$col = PaczkomatyDispatchOrderPeer::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 PaczkomatyDispatchOrder
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(PaczkomatyDispatchOrderPeer::DATABASE_NAME);
$criteria->add(PaczkomatyDispatchOrderPeer::ID, $pk);
$v = PaczkomatyDispatchOrderPeer::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 PaczkomatyDispatchOrder[]
*/
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(PaczkomatyDispatchOrderPeer::ID, $pks, Criteria::IN);
$objs = PaczkomatyDispatchOrderPeer::doSelect($criteria, $con);
}
return $objs;
}
} // BasePaczkomatyDispatchOrderPeer
// 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 {
BasePaczkomatyDispatchOrderPeer::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.stPaczkomatyPlugin.lib.model.map.PaczkomatyDispatchOrderMapBuilder');
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,773 @@
<?php
class stInPostApi
{
const ALLEGRO_DELIVERY_TO_SERVICE_MAPPING = [
'5d9c7838-e05f-4dec-afdd-58e884170ba7' => 'inpost_courier_allegro',
'85c3ad2f-4ec1-446c-866e-63473ed10e26' => 'inpost_courier_allegro',
'9081532b-5ad3-467d-80bc-9252982e9dd8' => 'inpost_letter_allegro',
'98f86f81-0018-41c5-ac83-073a56fc7021' => 'inpost_letter_allegro',
'2488f7b7-5d1c-4d65-b85c-4cbcf253fd93' => 'inpost_locker_allegro',
'b20ef9e1-faa2-4f25-9032-adbea23e5cb9' => 'inpost_locker_allegro',
'685d8b40-2571-4111-8937-9220b1710d4c' => 'inpost_locker_standard',
'2653ca13-67c8-48c3-bbf8-ff9aa3f70ed3' => 'inpost_locker_standard',
'1a228763-c17a-4b2d-88b0-63b082b04da6' => 'inpost_courier_standard',
'999f8753-6340-48a0-8eba-46096f9749aa' => 'inpost_courier_standard',
];
const COURIER_SERVICES = [
'inpost_courier_allegro',
'inpost_courier_standard',
'inpost_letter_allegro',
];
const DISPATCH_ORDER_STATUS = [
'accepted' => 'Zaakceptowane',
'canceled' => 'Anulowane',
'sent' => 'Wysłane',
'new' => 'Nowe',
'rejected' => 'Odrzucone',
'done' => 'Wykonane',
];
/**
* Singleton
*
* @var stInPostApi
*/
protected static $instance = null;
/**
* Konfiguracja inpost
*
* @var stConfig
*/
protected $config = null;
/**
* Poprawność konfiguracji api
*
* @var bool
*/
protected $isValid = null;
/**
* Ostatni błąd Api
*
* @var stdClass
*/
protected $lastError = null;
/**
* Ostatnie komunikat błędu Api
*
* @var string
*
*/
protected $lastErrorMessage = null;
/**
* Lista statusów paczki
*
* @var array
*/
protected $statuses = null;
/**
* Lista metod wysyłki
*
* @var array
*/
protected $sendingMethods = array();
const SANDBOX_ENDPOINT = 'https://sandbox-api-shipx-pl.easypack24.net/v1';
const PRODUCTION_ENDPOINT = 'https://api-shipx-pl.easypack24.net/v1';
const VALIDATION_FAILED = 'validation_failed';
const ACCESS_FORBIDDEN = 'access_forbidden';
const INVALID_PARAMETER = 'invalid_parameter';
const OFFER_EXPIRED = 'offer_expired';
const TOKEN_INVALID = 'token_invalid';
const ROUTING_NOT_FOUND = 'routing_not_found';
/**
* Zwraca instancję klasy stInPostApi
*
* @return stInPostApi
*/
public static function getInstance()
{
if (null === self::$instance)
{
self::$instance = new self();
self::$instance->initialize();
}
return self::$instance;
}
/**
* Sprawdza poprawność konfiguracji api
*
* @return bool
*/
public function isValid()
{
if ($this->config->get('token') && null === $this->isValid)
{
try
{
$this->getOrganizations();
$this->isValid = true;
}
catch(stInPostApiException $e)
{
$this->isValid = false;
}
}
return $this->isValid;
}
public function initialize()
{
$this->config = stConfig::getInstance('stPaczkomatyBackend');
}
/**
* Zwraca paczkomat
*
* @param mixed $name Nazwa paczkomatu
* @return stdClass|null
* @throws stInPostApiException
* @throws stInPostApiException
*/
public function getPoint($name)
{
return $this->callApi('get', '/points/' . $name);
}
/**
* Zwraca listę paczkomatów
*
* @param array|null $params
* @return stdClass|null
* @throws stInPostApiException
*/
public function getPoints(array $params = null)
{
return $this->callApi('get', '/points', $params);
}
/**
* Tworzy zlecenie odbioru
* @param array $shipmentIds Id przesyłek
* @return stdClass|null
* @throws stInPostApiException
*/
public function createDispatchOrders(array $shipmentIds)
{
$config = stConfig::getInstance('stPaczkomatyBackend');
return $this->callApiWithOrganization('post', '/dispatch_orders', [
'shipments' => $shipmentIds,
'address' => [
"street" => $config->get('sender_street'),
"building_number" => $config->get('sender_building'),
"city" => $config->get('sender_city'),
"post_code" => $config->get('sender_post_code'),
"country_code" => $config->get('sender_country_code'),
],
'name' => 'SOTESHOP',
'phone' => $config->get('sender_phone'),
]);
}
/**
* Zwraca zlecenie odbioru
*
* @param int $id Id zlecenia odbioru
* @return stdClass|null
* @throws stInPostApiException
*/
public function getDispatchOrder(int $id)
{
return $this->callApi('get', '/dispatch_orders/'.$id);
}
/**
* Zwraca zlecenia odbioru
*
* @param int $id Id zlecenia odbioru
* @return stdClass|null
* @throws stInPostApiException
*/
public function getDispatchOrders(array $ids)
{
return $this->callApiWithOrganization('get', '/dispatch_orders', [
'id' => implode(',', $ids),
]);
}
/**
* Usuwa zlecenie odbioru
* @param int $id Id zlecenia odbioru
* @return stdClass|null
* @throws stInPostApiException
*/
public function deleteDispatchOrder(int $id)
{
return $this->callApi('delete', '/dispatch_orders/'.$id);
}
/**
* Pobiera wydruk zlecenia odbioru
*
* @param int $id Id zlecenia odbioru
* @param string $format Format wydruku (dostępne tylko Pdf)
* @return string|null
* @throws stInPostApiException
*/
public function getDispatchOrderPrintOut(int $id, string $format = 'Pdf')
{
return $this->callApi('get', '/dispatch_orders/'.$id.'/printout', ['format' => $format]);
}
/**
* Pobiera listę statusów dla paczki
*
* @return array
* @throws stInPostApiException
*/
public function getStatuses($lang = null)
{
$lang = sfContext::getInstance()->getUser()->getCulture();
if ($lang == 'en_US')
{
$lang = 'en_GB';
}
if (!isset($this->statuses[$lang]))
{
$response = $this->callApi('get', '/statuses', array('lang' => $lang));
$statuses = array();
foreach ($response->items as $item)
{
$statuses[$item->name] = rtrim($item->title, '.');
}
$this->statuses[$lang] = $statuses;
}
return $this->statuses[$lang];
}
/**
* Pobiera etykietę dla przesyłki
*
* @param mixed $id Id przesyłki
* @return string|null
* @throws stInPostApiException
*/
public function downloadLabel($id)
{
$format = $this->config->get('label_format', 'Pdf');
$params = array(
'type' => $format != 'Pdf' ? 'A6' : $this->config->get('label_type', 'normal'),
'format' => $format,
);
return $this->callApi('get', '/shipments/' . $id . '/label', $params);
}
/**
* Zwraca tytuł zlecenia odbioru
*
* @param string $name Nazwa statusu
* @return string|null
*/
public function getDispatchOrderStatusTitleByName(string $name): ?string
{
return isset(self::DISPATCH_ORDER_STATUS[$name]) ? self::DISPATCH_ORDER_STATUS[$name] : null;
}
/**
* Pobiera tytuł statusu po jego nazwie
*
* @param string $name
* @return string
* @throws stInPostApiException
*/
public function getStatusTitleByName($name)
{
$statuses = $this->getStatuses();
return isset($statuses[$name]) ? $statuses[$name] : null;
}
/**
* Zwraca listę organizacji
*
* @param array $params
* @return stdClass|null
* @throws stInPostApiException
*/
public function getOrganizations(array $params = array())
{
$params = array_merge(array(
'sort_by' => 'name',
'sort_order' => 'asc',
),
$params
);
return $this->callApi('get', '/organizations', $params);
}
/**
* Zwraca organizację
*
* @param mixed $id Id organizacji
* @return stdClass|null
* @throws stInPostApiException
*/
public function getOrganization($id)
{
return $this->callApi('get', '/organizations/' . $id);
}
/**
* Zwraca metody nadania
*
* @param string $service Opcjonalna nazwa serwisu
* @return array
* @throws stInPostApiException
*/
public function getSendingMethods($service = null)
{
if (!isset($this->sendingMethods[$service]))
{
$response = $this->callApi('get', '/sending_methods', $service ? array('service' => $service) : null);
$methods = array();
$i18n = sfContext::getInstance()->getI18N();
foreach ($response->items as $method)
{
$methods[$method->id] = $i18n->__($method->name, null, 'stPaczkomatyBackend');
}
$this->sendingMethods[$service] = $methods;
}
return $this->sendingMethods[$service];
}
/**
* Tworzy przesyłkę
*
* @param array $params
* @return stdClass|null
* @throws stInPostApiException
*/
public function createShipment(array $params)
{
return $this->callApiWithOrganization('post', '/shipments', $params);
}
/**
* Pobiera przesyłki
* @param array $params
* @return stdClass|null
* @throws stInPostApiException
*/
public function getShipments(array $params)
{
return $this->callApiWithOrganization('get', '/shipments', $params);
}
/**
* Pobiera przesyłki po numerze id
*
* @param array $ids Id przesyłek
* @return stdClass|null
* @throws stInPostApiException
*/
public function getShipmentsById(array $ids)
{
return $this->getShipments([
'id' => implode(',', $ids),
]);
}
/**
* Usuwa przesyłkę
* @param $id
* @return stdClass|null
* @throws stInPostApiException
*/
public function deleteShipment($id)
{
return $this->callApi('delete', '/shipments/' . $id);
}
/**
* Pobiera przesyłkę
* @param $id
* @return stdClass|null
* @throws stInPostApiException
*/
public function getShipment($id)
{
return $this->callApi('get', '/shipments/' . $id);
}
/**
* Pobiera informacje o statusie przesyłki
* @param $number
* @return stdClass|null
* @throws stInPostApiException
*/
public function getTracking($number)
{
return $this->callApi('get', '/tracking/' . $number);
}
/**
* Pobiera przesyłkę po numerze trackingowym
* @param $number
* @return mixed|null
* @throws stInPostApiException
*/
public function getShipmentByTrackingNumber($number)
{
$response = $this->getShipments(array('tracking_number' => $number));
return $response->items ? $response->items[0] : null;
}
/**
* Zwraca ostatni błąd api
*
* @return stdClass
*/
public function getLastError()
{
return $this->lastError;
}
/**
* Zwraca ostatni komunikat błędu api
*
* @return string
*/
public function getLastErrorMessage()
{
return $this->lastErrorMessage;
}
public function isSandbox()
{
return $this->config->get('sandbox');
}
/**
* Wykonuje żądanie API dla danej organizacji
*
* @param string $method Metoda (post,get,put,delete)
* @param string $resource Zasób
* @param array|null $data Dodatkowe parametry
* @param int|null $organizationId Opcjonalne id orgranizacji (domyślnie brana z konfiguracji)
* @return stdClass|null
* @throws stInPostApiException
*/
public function callApiWithOrganization(string $method, string $resource, ?array $data = null, ?int $organizationId = null)
{
if (null === $organizationId)
{
$organizationId = $this->config->get('organization');
}
return $this->callApi($method, '/organizations/' . $organizationId . $resource, $data);
}
/**
* Wykonuje żądanie API
* @param $method Metoda (post,get,put,delete)
* @param $resource Zasób
* @param array|null $data Dodatkowe parametry
* @return stdClass|null
* @throws stInPostApiException
*/
public function callApi($method, $resource, array $data = null)
{
$this->lastError = null;
$this->lastErrorMessage = null;
$responseHeaders = array();
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $this->config->get('token'),
// 'Accept-Language: ' . sfContext::getInstance()->getUser()->getCulture(),
);
$ch = curl_init();
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$url = $this->getEndpoint() . $resource;
if ($method == 'post')
{
curl_setopt($ch, CURLOPT_POST, 1);
}
else
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
}
if (($method == 'post' || $method == 'put') && $data)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
elseif ($data)
{
$url = $url . '?' . http_build_query($data, '', '&');
}
// OPTIONS:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_SSLVERSION, 6);
// curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$responseHeaders)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
}
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
sfLogger::getInstance()->info("{stInPostApi} Calling: " . $url);
sfLogger::getInstance()->info("{stInPostApi} With HEADERS: " . json_encode($headers));
if (!empty($data))
{
sfLogger::getInstance()->info("{stInPostApi} With Payload: " . json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}
}
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error)
{
$this->lastErrorMessage = $error;
throw new stInPostApiException($error);
}
if (false !== strpos($responseHeaders['content-type'], 'application/json'))
{
$response = json_decode($result);
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
if (isset($response->error)) {
sfLogger::getInstance()->err("{stInPostApi} Response: " . json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
} else {
sfLogger::getInstance()->info("{stInPostApi} Response: " . json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}
}
if (isset($response->error))
{
$this->lastError = $response;
$message = self::translateErrorMessage($response->error);
if (null === $message)
{
if (isset($response->message))
{
$message = $response->message;
}
elseif (isset($response->description))
{
$message = $response->description;
}
}
$this->lastErrorMessage = $message;
throw new stInPostApiException($this->lastErrorMessage);
}
if (isset($response->transactions) && !empty($response->transactions))
{
foreach ($response->transactions as $transaction)
{
if ($transaction->status == 'failure')
{
$this->lastError = $transaction->details;
$this->lastErrorMessage = self::formatTransactionError($transaction->details);
throw new stInPostApiTransactionException($this->lastErrorMessage, $transaction->details->error);
}
}
}
}
else
{
$response = $result;
}
return $response;
}
public function getEndpoint()
{
return $this->isSandbox() ? self::SANDBOX_ENDPOINT : self::PRODUCTION_ENDPOINT;
}
/**
* Zwraca treść błędu zrozumiałą dla klienta
*
* @param string $error
* @param array $i18nMessageParams
* @return null|string
*/
public static function translateErrorMessage(string $error, array $i18nMessageParams = []): ?string
{
$i18n = sfContext::getInstance()->getI18N();
$errors = array(
'resource_not_found' => 'Szukany zasób nie został odnaleziony.',
'access_forbidden' => 'Dostęp do określonego zasobu jest zabroniony.',
'invalid_parameter' => 'Przekazano niepoprawną wartość dla określonego parametru w URI. Szczegóły dostępne pod kluczem description odpowiedzi błędu.',
'validation_failed' => 'Błąd walidacji. Dane przesłane metodą POST są niepoprawne',
'offer_expired' => 'Zakupienie oferty jest niemożliwe, ponieważ upłynął termin jej ważności.',
'token_invalid' => 'Podany token jest nieprawidłowy',
'routing_not_found' => 'Szukany zasób nie został odnaleziony.',
'invalid_end_of_week_collection' => 'Opcja "Paczka w weekend" jest dostępna tylko w określonym przedziale czasowym opisanym w informacjach ogólnych usługi',
'invalid_target_point_for_end_of_week_collection' => 'Opcja "Paczka w weekend" jest dostępna tylko dla Paczkomatów',
'invalid_allegro_for_end_of_week_collection' => 'Opcja "Paczka w weekend" nie jest dostępna dla przesyłek Allegro',
'invalid_status' => '%%subject%% <b>%%subject_id%%</b> posiada nieprawidłowy status',
'already_dispatched' => 'Zlecenie odbioru zostało już utworzone dla przesyłki <b>%%shipment%%</b>',
'various_types_of_carrier' => 'Przesyłki muszą być tego samego rodzaju',
'should_be_greater_or_equal_than_cod' => 'Wartość powinna być większa lub równa wartości pola <b>Kwota pobrania</b>',
'required' => 'Wartość dla określonego parametru jest wymagana.',
'too_short' => 'Za mała ilość znaków',
'too_small' => 'Za mała wartość',
'too_long' => 'Za duża ilość znaków',
'not_a_number' => 'Wartość nie jest liczbą',
'not_an_integer' => 'Wartość nie jest liczbą całkowitą',
'unknow_error' => 'Wystąpił nieznany błąd',
'invalid' => 'Wprowadzona wartość jest niepoprawna.',
'invalid_service_for_end_of_week_collection' => 'Przesyłka kurierska nie obsługuję Paczki w weekend',
'invalid_end_of_week_collection' => 'Usługa dostępna od czwartku od godziny 20:00 do soboty do godziny 13:00. Nie uwzględnia świąt ani dni wolnych',
'invalid_target_point_for_end_of_week_collection' => 'Usługa nie jest dostępna dla wybranego paczkomatu odbiorcy',
'invalid_target_point_247_for_end_of_week_collection' => 'Usługa nie jest dostępna dla wybranego paczkomatu odbiorcy',
'invalid_allegro_for_end_of_week_collection' => 'Usługa nie jest dostępna dla przesyłek Allegro',
'debt_collection' => 'Transakcja nie może zostać zrealizowana ze względu na saldo Twojego konta.',
'invalid_action' => 'Nie możesz usunąc przesyłki z podanym statusem',
'internal_server_error' => 'Wystąpił wewnętrzny błąd serwera InPost',
);
if (isset($errors[$error]))
{
return $i18n->__($errors[$error], $i18nMessageParams, 'stPaczkomatyBackend');
}
return $i18n->__('Wystąpił nieobsługiwany wyjątek (błąd: %error%)', ['%error%' => $error], 'stPaczkomatyBackend');
}
/**
* Zwraca sformatowaną treść błędów
*
* @param mixed $errors
* @param array $i18nMessageParams
* @return string
*/
public static function formatDetailError($errors, array $i18nMessageParams = [])
{
$message = [];
if (!is_array($errors))
{
$errors = array($errors);
}
foreach ($errors as $error)
{
if (is_object($error))
{
foreach (get_object_vars($error) as $value)
{
$message[] = self::translateErrorMessage($value, $i18nMessageParams);
}
}
else
{
$message[] = self::translateErrorMessage($error, $i18nMessageParams);
}
}
return implode("<br>", $message);
}
public static function formatTransactionError($transactionError): string
{
return $transactionError->message == $transactionError->error ? self::translateErrorMessage($transactionError->error) : $transactionError->message;
}
public static function formatUnavailableError($errors)
{
$i18n = sfContext::getInstance()->getI18N();
if (isset($errors[0]->sender) && $errors[0]->sender == 'post_code_invalid')
{
$i18n = sfContext::getInstance()->getI18N();
sfLoader::loadHelpers(array('Helper', 'stUrl'));
return $i18n->__('Nieprawidłowy kod pocztowy nadawcy. Przejdź do %link%, aby skorygować problem.', array(
'%link%' => st_link_to($i18n->__('konfiguracji'), '@stPaczkomatyPlugin?action=config', array('target' => '_blank')),
));
}
return $i18n->__('Wystąpił nieobsługiwany wyjątek (błąd: "%error%")', [
'%error%' => json_encode($errors, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
]);
}
/**
* Zwraca nazwę serwisu InPost na podstawie id dostawy allegro
*
* @param string $allegroDeliveryId Id dostawy allegro
* @return null|string
*/
public static function getAllegroDeliveryToServiceMapping(string $allegroDeliveryId): ?string
{
return isset(self::ALLEGRO_DELIVERY_TO_SERVICE_MAPPING[$allegroDeliveryId]) ? self::ALLEGRO_DELIVERY_TO_SERVICE_MAPPING[$allegroDeliveryId] : null;
}
}

View File

@@ -0,0 +1,6 @@
<?php
class stInPostApiException extends Exception
{
}

View File

@@ -0,0 +1,23 @@
<?php
class stInPostApiTransactionException extends stInPostApiException
{
/**
* Nazwa błędu
*
* @var string|null
*/
protected $error;
public function __construct(string $message, ?string $error = null)
{
parent::__construct($message);
$this->error = $error;
}
public function getError(): ?string
{
return $this->error;
}
}

View File

@@ -0,0 +1,92 @@
<?php
class stInPostParcelSizeValidator extends sfValidator
{
public function initialize($context, $parameters = array())
{
$result = parent::initialize($context, $parameters);
$this->setParameter('allegro_courier_error', 'Paczka %%number%% - Suma wymiarów paczki nie może być większa niż %%max_package_dimension_sum%%cm, maksymalna długość boku %%max_size%%cm, maksymalna waga %%max_weight%%kg');
$this->setParameter('inpost_courier_standard_error', 'Paczka %%number%% - Maksymalne wymiary paczki %%max_dimensions%%cm, maksymalna waga %%max_weight%%kg');
$this->setParameter('inpot_minimum_dimensions', 'Paczka %%number%% - Wymiary oraz waga przesyłki musi być większa od 0');
return $result;
}
public function execute(&$parcels, &$error)
{
$parcelsErrors = [];
$parcelNumber = 0;
$service = $this->getParameter('service');
$i18n = $this->getContext()->getI18N();
foreach ($parcels as $parcel)
{
$parcelNumber++;
if (empty($parcel['weight']) || empty($parcel['width']) || empty($parcel['height']) || empty($parcel['length']))
{
$parcelsErrors[] = $i18n->__($this->getParameter('inpot_minimum_dimensions'), [
'%%number%%' => '#' . $parcelNumber,
]);
continue;
}
$packageDimensionSum = $parcel['width'] + $parcel['height'] + $parcel['length'];
if ($service == 'inpost_courier_allegro' && ($parcel['weight'] > 30 || $packageDimensionSum > 160 || $parcel['width'] > 80 || $parcel['height'] > 80 || $parcel['length'] > 80))
{
$parcelsErrors[] = $i18n->__($this->getParameter('allegro_courier_error'), [
'%%number%%' => '#' . $parcelNumber,
'%%max_package_dimension_sum%%' => 160,
'%%max_size%%' => 80,
'%%max_weight%%' => 30,
]);
continue;
}
if ($service == 'inpost_letter_allegro' && ($parcel['weight'] > 10 || $packageDimensionSum > 160 || $parcel['width'] > 80 || $parcel['height'] > 80 || $parcel['length'] > 80))
{
$parcelsErrors[] = $i18n->__($this->getParameter('allegro_courier_error'), [
'%%number%%' => '#' . $parcelNumber,
'%%max_package_dimension_sum%%' => 160,
'%%max_size%%' => 80,
'%%max_weight%%' => 10,
]);
continue;
}
if ($service == 'inpost_courier_standard' && ($parcel['weight'] > 50 || $parcel['width'] > 240 || $parcel['height'] > 350 || $parcel['length'] > 240))
{
$parcelsErrors[] = $i18n->__($this->getParameter('inpost_courier_standard_error'), [
'%%number%%' => '#' . $parcelNumber,
'%%max_weight%%' => 50,
'%%max_dimensions%%' =>'240x240x350',
]);
continue;
}
if ($parcel['weight'] > 50 || $parcel['width'] > 240 || $parcel['height'] > 350 || $parcel['length'] > 240)
{
$parcelsErrors[] = $i18n->__($this->getParameter('inpost_courier_standard_error'), [
'%%number%%' => '#' . $parcelNumber,
'%%max_weight%%' => 30,
'%%max_dimensions%%' =>'240x240x350',
]);
}
}
if (!empty($parcelsErrors))
{
$error = $parcelsErrors;
return false;
}
return true;
}
}

View File

@@ -0,0 +1,37 @@
<?php
class stPaczkomaty {
public static function isActive() {
return stConfig::getInstance('stPaczkomatyBackend')->get('enabled', false);
}
public static function digestPassword($password) {
$version = phpversion();
if ($version[0] < 5)
return base64_encode(pack('H*', md5($password)));
else
return base64_encode(md5($password, true));
}
public static function convertStatus($status) {
$i18n = sfContext::getInstance()->getI18n();
switch ($status) {
case 'Created': return $i18n->__('Oczekuje na wysyłkę', array(), 'stPaczkomatyBackend');
case 'Prepared': return $i18n->__('Gotowa do wysyłki', array(), 'stPaczkomatyBackend');
case 'Sent': return $i18n->__('Przesyłka nadana', array(), 'stPaczkomatyBackend');
case 'InTransit': return $i18n->__('Przesyłka w drodze', array(), 'stPaczkomatyBackend');
case 'Stored': return $i18n->__('Oczekuje na odbiór', array(), 'stPaczkomatyBackend');
case 'Avizo': return $i18n->__('Ponowne awizo', array(), 'stPaczkomatyBackend');
case 'CustomerDelivering': return $i18n->__('Nadawana w paczkomacie', array(), 'stPaczkomatyBackend');
case 'CustomerStored': return $i18n->__('Umieszczona przez klienta', array(), 'stPaczkomatyBackend');
case 'LabelExpired': return $i18n->__('Etykieta przeterminowana', array(), 'stPaczkomatyBackend');
case 'Expired': return $i18n->__('Nie odebrana', array(), 'stPaczkomatyBackend');
case 'Delivered': return $i18n->__('Dostarczona', array(), 'stPaczkomatyBackend');
case 'RetunedToAgency': return $i18n->__('Przekazana do oddziału', array(), 'stPaczkomatyBackend');
case 'Cancelled': return $i18n->__('Anulowana', array(), 'stPaczkomatyBackend');
case 'Claimed': return $i18n->__('Przyjęto zgłoszenie reklamacyjne', array(), 'stPaczkomatyBackend');
case 'ClaimProcessed': return $i18n->__('Rozpatrzono zgłoszenie reklamacyjne', array(), 'stPaczkomatyBackend');
}
}
}

View File

@@ -0,0 +1,11 @@
<?php
class stPaczkomatyCourierDeliveryType extends stPaczkomatyDeliveryType
{
public function supportsAllegroDelivery(string $allegroDeliveryId): bool
{
$type = stInPostApi::getAllegroDeliveryToServiceMapping($allegroDeliveryId);
return null !== $type && in_array($type, stInPostApi::COURIER_SERVICES);
}
}

View File

@@ -0,0 +1,14 @@
<?php
class stPaczkomatyDeliveryType extends stDeliveryTypeAbstract
{
public function getTrackingUrl(string $number): string
{
return 'https://inpost.pl/sledzenie-przesylek?number='.$number;
}
public function checkConfiguration(): bool
{
return boolval(stConfig::getInstance('stPaczkomatyBackend')->get('enabled'));
}
}

View File

@@ -0,0 +1,202 @@
<?php
class stPaczkomatyDownloader {
protected static $instance = array();
protected $namespace = null;
public static function getInstance($namespace) {
if (!isset(self::$instance[$namespace])) {
$className = __CLASS__;
self::$instance[$namespace] = new $className();
self::$instance[$namespace]->initialize($namespace);
}
return self::$instance[$namespace];
}
public function initialize($namespace) {
$this->namespace = $namespace;
}
public function get($parameters = array(), $force = false) {
if ($force === false && ($cache = $this->getCache()) !== false)
return $cache;
$response = $this->download($parameters);
$this->saveCache($response);
return $response;
}
public function download($parameters = array()) {
return stPaczkomatyPack::call($parameters);
}
public function saveCache($content) {
file_put_contents($this->getCacheFileName(), $content);
}
public function getCache($time = 86400) {
if (file_exists($this->getCacheFileName()))
if (filemtime($this->getCacheFileName()) + $time > time())
return file_get_contents($this->getCacheFileName());
else
unlink($this->getCacheFileName());
return false;
}
public function getCacheFileName() {
$cacheDir = sfConfig::get('sf_root_dir').'/cache/frontend/'.SF_ENVIRONMENT.'/stPaczkomatyPlugin';
if (!file_exists($cacheDir))
mkdir($cacheDir, 0777, true);
$config = stConfig::getInstance('stPaczkomatyBackend');
return $cacheDir.'/'.$this->namespace.($config->get('test_mode') ? '.test' : '').'.cache';
}
}
class stPaczkomatyMachines {
protected static function parseCsv($csv) {
$content = explode("\n", $csv);
if(is_array($content))
unset($content[0]);
$keyList = array('number', 'street', 'house', 'postCode', 'city', 'latitude', 'longitude', 'cod', 'hours', 'description', 'paymentDescription', 'partnerId', '?', '??', '???', '????');
foreach ($content as $key => $value)
$content[$key] = array_combine($keyList, explode(";", $value));
return $content;
}
public static function getListOfMachines($force = false) {
$downloader = stPaczkomatyDownloader::getInstance('machines');
if ($force === false && ($cache = $downloader->getCache()) !== false) {
$list = json_decode($cache, true);
if (!empty($list))
return $list;
}
$response = $downloader->download(array('do' => 'listmachines_csv'));
$parsedResponse = self::parseCsv($response, true);
$downloader->saveCache(json_encode($parsedResponse));
stPaczkomatyCites::createCitiesList($parsedResponse);
return $parsedResponse;
}
public static function getListOfMachinesByParam($params = array()) {
$downloader = stPaczkomatyDownloader::getInstance('machines_by_param');
$response = $downloader->download(array_merge(array('do' => 'listmachines_csv'), $params));
$parsedResponse = self::parseCsv($response, true);
return $parsedResponse;
}
public static function getListOfCodMachines() {
return self::parseCsv(stPaczkomatyDownloader::getInstance('machines_cod')->get(array('do' => 'listmachines_csv', 'paymentavailable' => 't')));
}
public static function getListOfDeliveryPoints($force = false)
{
$downloader = stPaczkomatyDownloader::getInstance('delivery_points');
if ($force === false && ($cache = $downloader->getCache()) !== false) {
$list = json_decode($cache, true);
if (!empty($list))
return $list;
}
$response = $downloader->download(array('do' => 'listmachines_csv', 'pickuppoint' => 't'));
$parsedResponse = self::parseCsv($response, true);
$downloader->saveCache(json_encode($parsedResponse));
return $parsedResponse;
}
public static function getMachine($number) {
$content = self::getListOfMachines();
foreach ($content as $machine)
if ($number == $machine['number'])
return $machine;
$content = self::getListOfDeliveryPoints();
foreach ($content as $machine)
if ($number == $machine['number'])
return $machine;
return null;
}
public static function getMachineByPostCode($postCode) {
$xml = stPaczkomatyDownloader::getInstance('machine')->download(array('do' => 'findnearestmachines', 'postcode' => $postCode));
$data = simplexml_load_string($xml);
$machine = array();
if(isset($data->machine[0]))
foreach ($data->machine[0] as $key => $value)
$machine[$key] = (string) $value;
else
return array();
return $machine;
}
public static function get3MachinesByPostCode($postCode) {
return self::getMachinesByPostCode($postCode, 3);
}
public static function getMachinesByPostCode($postCode, $limit = 100) {
$xml = stPaczkomatyDownloader::getInstance('machine')->download(array('do' => 'findnearestmachines', 'postcode' => $postCode, 'limit' => $limit));
$data = simplexml_load_string($xml);
$machines = array();
if(isset($data->machine[0])) {
$i = 0;
foreach ($data->machine as $k => $m) {
foreach ($m as $key => $value)
$machines[$i][$key] = (string) $value;
$i++;
}
} else
return array();
return $machines;
}
}
class stPaczkomatyCites {
public static function getListofCities($force = false) {
$downloader = stPaczkomatyDownloader::getInstance('cities');
if ($force === false && ($cache = $downloader->getCache()) !== false) {
$list = json_decode($cache, true);
if (!empty($list))
return $list;
}
return self::createCitiesList(stPaczkomatyMachines::getListOfMachines());
}
public static function createCitiesList($machines, $namespace = 'cities') {
$cities = array();
foreach ($machines as $machine)
$cities[] = $machine['city'];
$cities = array_unique($cities);
sort($cities);
$citiesDownloader = stPaczkomatyDownloader::getInstance($namespace);
$citiesDownloader->saveCache(json_encode($cities));
return $cities;
}
}

View File

@@ -0,0 +1,32 @@
<?php
class stPaczkomatyImportExport {
public static function getProduct($object) {
$c = new Criteria();
$c->add(PaczkomatyHasProductPeer::PRODUCT_ID, $object->getId());
$c->add(PaczkomatyHasProductPeer::DISABLE_DELIVERY, 1);
$hasProductObject = PaczkomatyHasProductPeer::doSelectOne($c);
if (is_object($hasProductObject))
return 1;
return 0;
}
public function setProduct($object = null, $disableDelivery = 0) {
$c = new Criteria();
$c->add(PaczkomatyHasProductPeer::PRODUCT_ID, $object->getId());
$hasProductObject = PaczkomatyHasProductPeer::doSelectOne($c);
if (!is_object($hasProductObject)) {
$hasProductObject = new PaczkomatyHasProduct();
$hasProductObject->setProductId($object->getId());
}
if ($hasProductObject->getDisableDelivery() != $disableDelivery)
$hasProductObject->setDisableDelivery($disableDelivery);
$hasProductObject->save();
return true;
}
}

View File

@@ -0,0 +1,112 @@
<?php
class stPaczkomatyListener {
public static function smartySlotAppend(sfEvent $event, $components)
{
if (($event['slot'] == 'base-footer' || $event['slot'] == 'base_footer') && stPaczkomaty::isActive()) {
$components[] = $event->getSubject()->createComponent('stPaczkomatyFrontend', 'helper');
}
return $components;
}
public static function postExecuteAjaxDeliveryCountryUpdate(sfEvent $event)
{
$event->getSubject()->responseEvalJs("jQuery(document).trigger('paczkomaty.ajaxUpdate')");
}
public static function postExecuteIndex(sfEvent $event) {
$action = $event->getSubject();
if (!$action->getRequest()->hasErrors() && $action->getRequestParameter('user_data_billing[paczkomaty_machine_number]'))
{
$action->getRequest()->setParameter('user_data_delivery', array());
}
}
public static function postOrderConfirm(sfEvent $event) {
if (!stPaczkomaty::isActive()) return false;
$action = $event->getSubject();
$delivery = stDeliveryFrontend::getInstance($action->getUser()->getBasket())->getDefaultDelivery()->getDelivery();
self::redirect($action, $delivery);
$inpost = json_decode($action->getRequestParameter('user_data_billing[paczkomaty_machine_number]'), true);
if ($inpost && isset($inpost['name'])) {
$country = CountriesPeer::retrieveByIsoA2('PL');
$data = array('company' => 'Paczkomat - '.$inpost['name'],
'full_name' => '',
'address' => $inpost['address']['street'].' '.$inpost['address']['building_number'].($inpost['address']['flat_number'] ? '/'.$inpost['address']['flat_number'] : ''),
'code' => $inpost['address']['post_code'],
'town' => $inpost['address']['city'],
'phone' => '',
'address_more' => '',
'customer_type' => '2',
'country' => $country ? $country->getId() : null,
);
$action->user_data_delivery = array_merge($action->user_data_delivery, $data);
}
}
public static function preExecuteOrderSave(sfEvent $event) {
if (!stPaczkomaty::isActive()) return false;
$action = $event->getSubject();
$user_billing = $action->getRequest()->getParameter('user_data_billing');
$user_delivery = $action->getRequest()->getParameter('user_data_delivery');
$delivery_id = $action->getRequestParameter('delivery_id');
$delivery = DeliveryPeer::retrieveByPK($delivery_id);
self::redirect($action, $delivery);
if (!empty($user_billing['paczkomaty_machine_number'])) {
$user_delivery['company'] = $user_billing['company'];
$user_delivery['full_name'] = $user_billing['full_name'];
$user_delivery['address'] = $user_billing['address'];
$user_delivery['code'] = $user_billing['code'];
$user_delivery['town'] = $user_billing['town'];
$user_delivery['phone'] = $user_billing['phone'];
$user_delivery['customer_type'] = $user_billing['customer_type'];
$user_delivery['country'] = $user_billing['country'];
$action->getRequest()->setParameter('user_data_delivery', $user_delivery);
}
}
public static function postExecuteOrderSave(sfEvent $event) {
if (!stPaczkomaty::isActive()) return false;
$action = $event->getSubject();
$inpost = json_decode($action->getRequestParameter('user_data_billing[paczkomaty_machine_number]'), true);
if ($inpost && isset($inpost['name'])) {
$action->order->getOrderDelivery()->setPaczkomatyNumber($inpost['name']);
$country = CountriesPeer::retrieveByIsoA2('PL');
$d = $action->order->getOrderUserDataDelivery();
$d->setCompany('Paczkomat - '.$inpost['name']);
$d->setFullName(null);
$d->setAddress($inpost['address']['street'].' '.$inpost['address']['building_number'].($inpost['address']['flat_number'] ? '/'.$inpost['address']['flat_number'] : ''));
$d->setCode($inpost['address']['post_code']);
$d->setAddressMore(null);
$d->setTown($inpost['address']['city']);
$d->setCountriesId($country ? $country->getId() : null);
$d->save();
}
}
public static function redirect(stActions $action, Delivery $delivery = null)
{
$user_billing = $action->getRequest()->getParameter('user_data_billing');
if (null === $delivery || !$delivery->isType('inpostp') && isset($user_billing['paczkomaty_machine_number']) || $delivery->isType('inpostp') && (!isset($user_billing['paczkomaty_machine_number']) || !$user_billing['paczkomaty_machine_number']))
{
$action->generateSessionCheck();
return $action->redirect('@stBasket?action=index&session_expired=true');
}
}
}

View File

@@ -0,0 +1,189 @@
<?php
class stPaczkomatyPack {
const PACZKOMATY_URL = 'https://api.paczkomaty.pl/';
const PACZKOMATY_SANDBOX_URL = 'https://sandbox-api.paczkomaty.pl/';
public static function call($parameters, $postData = array(), $test_mode = null) {
$config = stConfig::getInstance('stPaczkomatyBackend');
if (null === $test_mode) {
$test_mode = $config->get('test_mode');
}
$url = $test_mode ? self::PACZKOMATY_SANDBOX_URL : self::PACZKOMATY_URL;
$url = $url.(!empty($parameters) ? '?'.http_build_query($parameters, '', '&') : '');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if ($postData) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public static function callAuth($parameters, $postData = array())
{
$config = stConfig::getInstance('stPaczkomatyBackend');
$postData = array_merge(array('email' => $config->get('username'), 'password' => $config->get('password')), $postData);
return self::call($parameters, $postData);
}
public static function getStatus($code) {
$response = self::call(array('do' => 'getpackstatus', 'packcode' => $code));
$xml = simplexml_load_string($response);
if(isset($xml->status))
return array('status' => (string)$xml->status, 'date' => (string)$xml->statusDate);
}
public static function checkAuth($login, $password, $test_mode)
{
$response = self::call(array('do' => 'pricelist'), array('email' => $login, 'password' => $password), $test_mode);
$logger = sfConfig::get('sf_debug') ? sfLogger::getInstance() : null;
if($response == false)
{
if ($logger)
{
$logger->log('{stPaczkomaty} Connection problem', SF_LOG_ERR);
}
return false;
}
$xml = simplexml_load_string($response);
if ($logger && isset($xml->error))
{
$logger->log('{stPaczkomaty} '.$xml->error, SF_LOG_ERR);
}
return !isset($xml->error);
}
public static function createPack(PaczkomatyPack $pack) {
$config = stConfig::getInstance('stPaczkomatyBackend');
$allegro = '';
try
{
if ($pack->hasAllegroTransactionId())
{
$userId = stConfig::getInstance('stAllegroBackend')->get('seller_id');
$transactionId = $pack->getAllegroTransactionId();
$allegro = '<allegro><userId>'.$userId.'</userId><transactionId>'.$transactionId.'</transactionId></allegro>';
}
}
catch (stAllegroException $e)
{
foreach (stAllegroApi::getLastErrors() as $error)
{
$messages[] = $error->userMessage;
}
$message = implode('<br>', $messages);
return array('status' => false, 'error' => $message);
}
$xml = '
<paczkomaty>
<autoLabels>0</autoLabels>
<selfSend>'.($pack->getUseSenderPaczkomat() ? 1 : 0).'</selfSend>
<pack>
<id>'.$pack->getId().'</id>
<adreseeEmail>'.$pack->getCustomerEmail().'</adreseeEmail>
<senderEmail>'.$config->get('username').'</senderEmail>
<phoneNum>'.$pack->getCustomerPhone().'</phoneNum>
<boxMachineName>'.$pack->getCustomerPaczkomat().'</boxMachineName>'.
($pack->getUseSenderPaczkomat() ? '<senderBoxMachineName>'.$pack->getSenderPaczkomat().'</senderBoxMachineName>' : '')
.'<packType>'.$pack->getPackType().'</packType>
<insuranceAmount>'.$pack->getInsurance().'</insuranceAmount>
<onDeliveryAmount>'.$pack->getCashOnDelivery().'</onDeliveryAmount>
<customerRef>'.$pack->getDescription().'</customerRef>
<senderAddress>
<companyName>'.$config->get('sender_company').'</companyName>
<name>'.$config->get('sender_name').'</name>
<surName>'.$config->get('sender_surname').'</surName>
<email>'.$config->get('sender_email').'</email>
<phoneNum>'.$config->get('sender_phone').'</phoneNum>
<street>'.$config->get('sender_street').'</street>
<buildingNo>'.$config->get('sender_building_no').'</buildingNo>
<flatNo>'.$config->get('sender_flat_no').'</flatNo>
<town>'.$config->get('sender_town').'</town>
<zipCode>'.$config->get('sender_zip_code').'</zipCode>
<province>'.$config->get('sender_province').'</province>
</senderAddress>
'.$allegro.'
</pack>
</paczkomaty>';
$post = array('content' => $xml);
$response = self::callAuth(array('do' => 'createdeliverypacks'), $post);
if($response == false)
return array('status' => false, 'error' => 'Błąd połączenia z serwerem API Paczkomaty.');
$xml = simplexml_load_string($response);
if(isset($xml->pack->error))
return array('status' => false, 'error' => (string)$xml->pack->error);
if(isset($xml->error))
return array('status' => false, 'error' => (string)$xml->error);
if(isset($xml->pack->packcode)) {
$pack->setCode((string)$xml->pack->packcode);
$pack->setCustomerDeliveringCode((string)$xml->pack->customerdeliveringcode);
$pack->save();
}
return array('status' => true);
}
public static function getSticker($code) {
$config = stConfig::getInstance('stPaczkomatyBackend');
$post = array('packcode' => $code, 'labelType' => $config->get('label_type'));
$response = self::callAuth(array('do' => 'getsticker'), $post);
if (strpos($response, 'PDF'))
return array('status' => true, 'pdf' => $response);
$xml = simplexml_load_string($response);
if(isset($xml->error))
return array('status' => false, 'error' => (string)$xml->error);
}
public static function payForPack($code) {
$config = stConfig::getInstance('stPaczkomatyBackend');
$post = array('packcode' => $code);
$response = self::callAuth(array('do' => 'payforpack'), $post);
if ($response == '1')
return array('status' => true);
$xml = simplexml_load_string($response);
if(isset($xml->error))
return array('status' => false, 'error' => (string)$xml->error);
}
}

View File

@@ -0,0 +1,45 @@
<?php
class stPaczkomatyPickupPointDeliveryType extends stPaczkomatyDeliveryType
{
public function supportsAllegroDelivery(string $allegroDeliveryId): bool
{
$type = stInPostApi::getAllegroDeliveryToServiceMapping($allegroDeliveryId);
return null !== $type && !in_array($type, stInPostApi::COURIER_SERVICES);
}
public function pickupPointUpdate(stDeliveryTypePickupPoint $pickupPoint): ?stDeliveryTypePickupPoint
{
try
{
$point = stInPostApi::getInstance()->getPoint($pickupPoint->getName());
$pickupPoint->setCod($point->payment_available);
}
catch (stInPostApiException $e)
{
}
if (empty($point) || $point->status != 'Operating')
{
return null;
}
return $pickupPoint;
}
public function validate(Delivery $selectedDelivery, PaymentType $selectedPayment, string $orderTotalAmount, array $userDataBilling, array $userDataDelivery, ?stDeliveryTypePickupPoint $pickupPoint, bool $isWeekendDelivery, bool $isExpressDelivery, array &$errors): bool
{
if (!parent::validate($selectedDelivery, $selectedPayment, $orderTotalAmount, $userDataBilling, $userDataDelivery, $pickupPoint, $isWeekendDelivery, $isExpressDelivery, $errors))
{
return false;
}
if (empty($userDataBilling['phone']))
{
$errors['user_data_billing{phone}'] = 'Brak telefonu.';
}
return empty($errors);
}
}