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,7 @@
all:
navigation_bar:
display:
orders:
paczkomaty: ~
items:
paczkomaty: {label: InPost, route: "@stPaczkomatyPlugin", icon: stPaczkomatyPlugin}

View File

@@ -0,0 +1,22 @@
<?php
if (IS_PHP7)
{
stDeliveryTypeConfiguration::register('inpostp', stPaczkomatyPickupPointDeliveryType::class, 'InPost - Odbiór w punkcie', [
'pickup_point' => true,
]);
}
if (SF_APP == 'backend')
{
stPluginHelper::addEnableModule('stPaczkomatyBackend', 'backend');
stPluginHelper::addRouting('stPaczkomatyPlugin', '/paczkomaty/:action/*', 'stPaczkomatyBackend', 'list', 'backend');
stPluginHelper::addRouting('stPaczkomatyCreatePack', '/paczkomaty/create/*', 'stPaczkomatyBackend', 'create', 'backend');
stConfiguration::addModule(['label' => 'InPost', 'route' => '@stPaczkomatyPlugin?action=config', 'icon' => 'stPaczkomatyPlugin'], 'deliveries');
}
elseif (SF_APP == 'frontend')
{
stPluginHelper::addEnableModule('stPaczkomatyFrontend', 'frontend');
stPluginHelper::addRouting('stPaczkomatyPlugin', '/paczkomaty/:action/*', 'stPaczkomatyFrontend', 'index', 'frontend');
stPluginHelper::addRouting('stPaczkomatyShowMap', '/paczkomaty/showMap/:deliveryId', 'stPaczkomatyFrontend', 'showMap', 'frontend');
}

View File

@@ -0,0 +1,5 @@
edit:
display:
"Paczkomaty": [_paczkomaty]
fields:
paczkomaty: {name: Paczkomaty, i18n: stPaczkomatyBackend, hide_label: true}

View File

@@ -0,0 +1,118 @@
---
propel:
_attributes:
defaultIdMethod: native
package: plugins.stPaczkomatyPlugin.lib.model
st_paczkomaty_pack:
_attributes:
phpName: PaczkomatyPack
created_at:
type: timestamp
updated_at:
type: timestamp
id:
type: INTEGER
primaryKey: true
required: true
autoIncrement: true
customer_email:
type: VARCHAR
size: 255
customer_phone:
type: VARCHAR
size: 24
customer_name:
type: VARCHAR
size: 255
customer_company_name:
type: VARCHAR
size: 255
customer_street:
type: VARCHAR
size: 255
customer_building_number:
type: VARCHAR
size: 24
customer_city:
type: VARCHAR
size: 255
customer_post_code:
type: VARCHAR
size: 16
customer_country_code:
type: CHAR
size: 2
customer_paczkomat:
type: VARCHAR
size: 48
sending_method:
type: VARCHAR
size: 48
sender_paczkomat:
type: VARCHAR
size: 24
use_sender_paczkomat:
type: BOOLEAN
default: false
pack_type:
type: CHAR
size: 1
required: false
inpost_shipment_id:
type: INTEGER
insurance:
type: DECIMAL
size: 10
scale: 2
cash_on_delivery:
type: DECIMAL
size: 10
scale: 2
description:
type: VARCHAR
size: 255
parcels:
type: VARCHAR
size: 8192
phpType: array
service:
type: VARCHAR
size: 48
required: false
code:
type: VARCHAR
size: 255
has_cash_on_delivery:
type: BOOLEAN
required: false
status:
type: VARCHAR
size: 255
order_id:
type: INTEGER
foreignTable: st_order
foreignReference: id
onDelete: setnull
dispatch_order_id:
type: INTEGER
foreignTable: st_paczkomaty_dispatch_order
foreignReference: id
onDelete: setnull
st_paczkomaty_dispatch_order:
_attributes:
phpName: PaczkomatyDispatchOrder
id:
type: INTEGER
primaryKey: true
required: true
autoIncrement: true
dispatch_order_id:
type: BIGINT
dispatch_order_external_id:
type: BIGINT
created_at:
type: timestamp
status:
type: VARCHAR
size: 16

View File

@@ -0,0 +1,10 @@
propel:
st_delivery:
_attributes:
phpName: Delivery
paczkomaty_type:
type: VARCHAR
size: 5
paczkomaty_size:
type: VARCHAR
size: 5

View File

@@ -0,0 +1,7 @@
propel:
st_order_delivery:
_attributes:
phpName: OrderDelivery
paczkomaty_number:
type: VARCHAR
size: 20

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

View File

@@ -0,0 +1,966 @@
<?php
class stPaczkomatyBackendActions extends autostPaczkomatyBackendActions
{
public function preExecute()
{
parent::preExecute();
if (!in_array($this->getActionName(), ['config', 'easypackWidget']) && !stConfig::getInstance('stPaczkomatyBackend')->get('enabled'))
{
$this->setFlash('error', $this->getContext()->getI18N()->__('app.requires.configuration'), false);
return $this->forward('stPaczkomatyBackend', 'config');
}
}
public function executeDispatchOrderPrintOut()
{
$i18n = $this->getContext()->getI18N();
$id = $this->getRequestParameter('id');
$dispatchOrder = PaczkomatyDispatchOrderPeer::retrieveByPK($id);
$api = stInPostApi::getInstance();
if (null === $dispatchOrder)
{
$this->setFlash('error', $i18n->__('Wybrane zlecenie odbioru nie istnieje.'));
return $this->redirect($this->getRequest()->getReferer());
}
try
{
$response = $api->getDispatchOrderPrintOut($dispatchOrder->getDispatchOrderId());
}
catch (stInPostApiException $e)
{
$message = [$i18n->__('Wystąpił błąd podczas drukowania zlecenia odbioru') . ':'];
if (!empty($api->getLastError()->details))
{
$error = $api->getLastError()->details;
}
elseif (!empty($api->getLastError()->message))
{
$error = $api->getLastError()->message;
}
else
{
$error = $e->getMessage();
}
$message[] = $error;
$this->setFlash('error', implode('<br>', $message));
return $this->redirect($this->getRequest()->getReferer());
}
return $this->downloadDocument($response, stPropelSeoUrlBehavior::makeSeoFriendly($i18n->__('Zlecenie odbioru')).'-'.$dispatchOrder->getDispatchOrderExternalId());
}
public function executeDispatchOrder()
{
if (!stDeliveryTypeConfiguration::has('inpostk'))
{
return $this->redirect($this->getRequest()->getReferer());
}
$i18n = $this->getContext()->getI18N();
if ($this->getRequest()->getMethod() == sfRequest::POST)
{
$ids = $this->getRequestParameter('paczkomaty_pack[selected]');
}
else
{
$ids = [$this->getRequestParameter('id')];
}
$shipmentIds = [];
$packs = PaczkomatyPackPeer::retrieveByPKsOrder(array_values($ids));
if (empty($packs))
{
$this->setFlash('error', $i18n->__('Przesyłki o id %%id%% nie istnieją.', [
'%%id%%' => implode(', ', $ids),
]));
return $this->redirect($this->getRequest()->getReferer());
}
$api = stInPostApi::getInstance();
$errors = [];
foreach ($packs as $pack)
{
if (null !== $pack->getDispatchOrderId())
{
$errors[] = $i18n->__('Dla przesyłki <b>%%shipment%%</b> zostało już utworzone zlecenie odbioru.', [
'%%shipment%%' => $pack->getTrackingNumber(),
]);
continue;
}
if ($pack->getSendingMethod() != 'dispatch_order')
{
$errors[] = $i18n->__('Przesyłka <b>%%shipment%%</b> ma nieprawidłową metodę wysyłki', [
'%%shipment%%' => $pack->getTrackingNumber(),
]);
continue;
}
$shipmentIds[] = $pack->getInpostShipmentId();
}
if (!empty($errors))
{
$errors = array_merge([$i18n->__('Wystąpił błąd podczas tworzenia zlecenia odbioru') . ':'], $errors);
$this->setFlash('error', implode('<br>', $errors));
return $this->redirect($this->getRequest()->getReferer());
}
try
{
$response = $api->createDispatchOrders($shipmentIds);
}
catch (stInPostApiException $e)
{
$error = $api->getLastError();
$message = [$i18n->__('Wystąpił błąd podczas tworzenia zlecenia odbioru') . ':'];
if (isset($error->details->shipments))
{
foreach ($error->details->shipments as $index => $shipmentError)
{
$message[] = stInPostApi::translateErrorMessage($shipmentError, [
'%%subject%%' => $i18n->__('Przesyłka'),
'%%subject_id%%' => $packs[$index]->getTrackingNumber(),
]);
}
$this->setFlash('error', implode('<br>', $message));
}
else
{
$this->setFlash('error', $e->getMessage());
}
return $this->redirect($this->getRequest()->getReferer());
}
while (!isset($response->external_id))
{
sleep(5);
$response = stInPostApi::getInstance()->getDispatchOrder($response->id);
}
$dispatchOrder = new PaczkomatyDispatchOrder();
$dispatchOrder->setDispatchOrderId($response->id);
$dispatchOrder->setDispatchOrderExternalId($response->external_id);
$dispatchOrder->setStatus($response->status);
$dispatchOrder->save();
foreach ($packs as $pack)
{
$pack->setPaczkomatyDispatchOrder($dispatchOrder);
$pack->save();
}
return $this->redirect($this->getRequest()->getReferer());
}
/**
* Undocumented function
*
* @param PaczkomatyPack $paczkomaty_pack
* @return void
*/
protected function deletePaczkomatyPack($paczkomaty_pack)
{
$api = stInPostApi::getInstance();
$i18n = $this->getContext()->getI18N();
try
{
$api->deleteShipment($paczkomaty_pack->getInpostShipmentId());
}
catch (stInPostApiException $e)
{
throw new Exception($i18n->__('Przesyłka dla zamówienia "%%order%%": %%message%%', [
'%%order%%' => $paczkomaty_pack->getOrder()->getNumber(),
'%%message%%' => $e->getMessage(),
]));
}
parent::deletePaczkomatyPack($paczkomaty_pack);
}
/**
* {@inheritDoc}
* @return PaczkomatyPack
*/
protected function getPaczkomatyPackOrCreate($id = 'id')
{
if (!isset($this->paczkomaty_pack))
{
$pack = parent::getPaczkomatyPackOrCreate($id);
$order = $pack->getOrder();
if ($pack->hasCourierService() && !stDeliveryTypeConfiguration::has('inpostk'))
{
return $this->redirect('@stOrder?action=edit&id=' . $order->getId());
}
if ($pack->isNew())
{
$packs = $order->getPaczkomatyPacks();
if ($packs)
{
return $this->redirect('@stPaczkomatyPlugin?action=edit&id=' . $packs[0]->getId() . '&order_id=' . $order->getId());
}
}
$i18n = $this->getContext()->getI18N();
if ($pack->isNew())
{
$config = stConfig::getInstance('stPaczkomatyBackend');
$pack->setSendingMethod($config->get('sending_method'));
$pack->setDropOffPoint($config->get('dropoff_point'));
$pack->setDescription($i18n->__('Zamówienie ' . $pack->getOrder()->getNumber()));
if ($pack->hasCourierService() && $pack->hasCashOnDelivery())
{
$pack->setInsurance($pack->getCashOnDelivery(true));
}
}
else
{
$api = stInPostApi::getInstance();
try
{
$response = $api->getShipment($pack->getInpostShipmentId());
$pack->setSendingMethod($response->custom_attributes->sending_method);
if (isset($response->custom_attributes->target_point))
{
$pack->setCustomerPickupPoint($response->custom_attributes->target_point);
}
if (isset($response->custom_attributes->dropoff_point))
{
$pack->setDropOffPoint($response->custom_attributes->dropoff_point);
}
if (!$pack->getTrackingNumber())
{
$pack->setTrackingNumber($response->tracking_number);
}
if (isset($response->parcels[0]->template))
{
$pack->setParcelTemplate($response->parcels[0]->template);
}
$pack->setStatus($response->status);
$pack->setEndOfWeekCollection($response->end_of_week_collection);
$pack->setCashOnDelivery(isset($response->cod) && $response->cod && $response->cod->amount ? $response->cod->amount : 0);
$pack->setInsurance(isset($response->insurance) && $response->insurance && $response->insurance->amount ? $response->insurance->amount : 0);
}
catch (stInPostApiException $e)
{
$this->getRequest()->setError('api', $e->getMessage());
}
}
if ($pack->hasCourierService())
{
$this->removeField('customer_pickup_point');
$this->removeField('pack_type');
}
else
{
$this->removeField('parcels');
$this->removeField('customer_country_code');
$this->removeField('customer_name');
$this->removeField('customer_company_name');
$this->removeField('customer_post_code');
$this->removeField('customer_city');
$this->removeField('customer_street');
$this->removeField('customer_building_number');
}
if (!$pack->isAdminGeneratorPlainField())
{
$this->hideAction('download_sticker');
$this->removeField('status_label');
$this->removeField('tracking_number');
}
else
{
$this->hideAction('_save');
}
}
return $this->paczkomaty_pack;
}
public function executeList()
{
if (!stDeliveryTypeConfiguration::has('inpostk'))
{
$this->hideField('dispatch_order_id');
}
if ($this->getRequestParameter('order_id'))
{
return $this->redirect('@stOrder?action=edit&id=' . $this->getRequestParameter('order_id'));
}
try
{
$result = parent::executeList();
$this->pager->getResults();
return $result;
}
catch (stInPostApiException $e)
{
$i18n = $this->getContext()->getI18N();
$this->setFlash('error', $i18n->__('Wystąpił podczas próby nawiązania połączenia z API (błąd: %%error%%)', [
'%%error%%' =>$e->getMessage()
]));
return $this->redirect('@stPaczkomatyPlugin?action=config');
}
}
public function executeDownloadLabel()
{
$pack = PaczkomatyPackPeer::retrieveByPK($this->getRequestParameter('id'));
$api = stInPostApi::getInstance();
$i18n = $this->getContext()->getI18N();
try
{
if ($pack->getInpostShipmentId())
{
$id = $pack->getInpostShipmentId();
}
else
{
$shipment = $api->getShipmentByTrackingNumber($pack->getTrackingNumber());
$id = $shipment->id;
}
$response = $api->downloadLabel($id);
return $this->downloadDocument($response, $i18n->__('etykieta').'-'.$pack->getTrackingNumber(), stConfig::getInstance('stPaczkomatyBackend')->get('label_format'));
}
catch (stInPostApiException $e)
{
$i18n = $this->getContext()->getI18N();
if (!empty($api->getLastError()->details))
{
$error = $api->getLastError()->details;
}
elseif (!empty($api->getLastError()->message))
{
$error = $api->getLastError()->message;
}
else
{
$error = $e->getMessage();
}
$this->getRequest()->setError('api', $i18n->__('Wystąpił bład podczas pobierania etykiety (Błąd: "%error%")', array('%error%' => $error)));
return $this->forward('stPaczkomatyBackend', 'edit');
}
}
public function validateEdit()
{
$request = $this->getRequest();
if ($request->getMethod() == sfRequest::POST)
{
$this->related_object = OrderPeer::retrieveByPK($this->getRequestParameter('order_id'));
$pack = $this->getPaczkomatyPackOrCreate();
$this->updatePaczkomatyPackFromRequest();
$api = stInPostApi::getInstance();
$i18n = $this->getContext()->getI18N();
$config = stConfig::getInstance('stPaczkomatyBackend');
$required = ['customer_email', 'customer_phone', 'customer_pickup_point'];
$data = $this->getRequestParameter('paczkomaty_pack');
if ($pack->hasCourierService())
{
$required = ['customer_street', 'customer_building_number', 'customer_post_code', 'customer_city', 'customer_country_code', 'customer_email', 'customer_phone', 'parcels'];
}
if (in_array($pack->getSendingMethod(), array('parcel_locker')))
{
$required[] = 'dropoff_point';
}
foreach ($required as $fieldName)
{
if (!isset($data[$fieldName]) || empty($data[$fieldName]))
{
$request->setError('paczkomaty_pack{' . $fieldName . '}', $i18n->__('Proszę uzupełnić pole.'));
}
}
if ($pack->hasCourierService() && empty($data['customer_name']) && empty($data['customer_company_name']))
{
$request->setError('paczkomaty_pack{customer_name}', $i18n->__('Musisz podać nazwę firmy lub imię i nazwisko odbiorcy'));
$request->setError('paczkomaty_pack{customer_company_name}', $i18n->__('Musisz podać nazwę firmy lub imię i nazwisko odbiorcy'));
}
if ($pack->hasCourierService() && isset($data['parcels']))
{
$this->validateParcelSize($pack, $data['parcels']);
}
if ($request->hasErrors())
{
return false;
}
$shipmentRequest = array(
'receiver' => array(
'email' => $pack->getCustomerEmail(),
'phone' => $pack->getCustomerPhone(),
),
'sender' => array(
"company_name" => !empty($config->get('sender_company')) ? $config->get('sender_company') : null,
"first_name" => !empty($config->get('sender_name')) ? $config->get('sender_name') : null,
"last_name" => !empty($config->get('sender_surname')) ? $config->get('sender_surname') : null,
"email" => trim($config->get('sender_email')),
"phone" => str_replace(array('+48', ' ', '-'), '', $config->get('sender_phone')),
"address" => array(
"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'),
),
),
'custom_attributes' => array(
'target_point' => $pack->getCustomerPickupPoint(),
'sending_method' => $pack->getSendingMethod(),
),
'service' => $pack->getService(),
'reference' => $pack->getDescription(),
'only_choice_of_offer' => false,
);
if (!$pack->hasCourierService())
{
$shipmentRequest['parcels'] = [
['template' => $pack->getParcelTemplate()],
];
}
else
{
$parcels = [];
list($firstName, $lastName) = explode(' ', $pack->getCustomerName(), 2);
foreach (array_values($pack->getParcels()) as $index => $parcel)
{
$parcels[] = [
'id' => $index + 1,
'dimensions' => [
'width' => $parcel['width'] * 10,
'height' => $parcel['height'] * 10,
'length' => $parcel['length'] * 10,
'unit' => 'mm',
],
'weight' => [
'amount' => $parcel['weight'],
'unit' => 'kg',
]
];
}
$shipmentRequest['parcels'] = $parcels;
$shipmentRequest['receiver'] = array_merge($shipmentRequest['receiver'], [
'company_name' => !empty($pack->getCustomerCompanyName()) ? $pack->getCustomerCompanyName() : null,
'first_name' => !empty($firstName) ? $firstName : null,
'last_name' => !empty($lastName) ? $lastName : null,
'address' => [
'street' => $pack->getCustomerStreet(),
'building_number' => $pack->getCustomerBuildingNumber(),
'post_code' => $pack->getCustomerPostCode(),
'city' => $pack->getCustomerCity(),
'country_code' => $pack->getCustomerCountryCode(),
],
]);
}
if ($pack->getInsurance() > 0)
{
$shipmentRequest['insurance'] = array(
'amount' => $pack->getInsurance(),
'currency' => 'PLN',
);
}
if ($pack->getEndOfWeekCollection())
{
$shipmentRequest['end_of_week_collection'] = true;
}
if ($pack->getCashOnDelivery() > 0)
{
$shipmentRequest['cod'] = array(
'amount' => $pack->getCashOnDelivery(),
'currency' => 'PLN',
);
}
if (in_array($pack->getSendingMethod(), array('parcel_locker')))
{
$shipmentRequest['custom_attributes']['dropoff_point'] = $pack->getDropOffPoint();
}
if (!$request->hasErrors())
{
try
{
$response = $api->createShipment($shipmentRequest);
$count = 0;
while ((null === $response->tracking_number || $response->status != 'confirmed') && $count <= 5)
{
sleep(5);
$result = $api->getShipment($response->id);
if ($result && is_object($result))
{
$response = $result;
}
if (!empty($response->offers) && $response->offers[0]->status == 'unavailable')
{
$request->setError('api', stInPostApi::formatUnavailableError($response->offers[0]->unavailability_reasons));
break;
}
$count++;
}
$request->setParameter('create_shipment', $response, 'soteshop/stInPostApi');
}
catch (stInPostApiException $e)
{
$error = $api->getLastError();
if ($error && $error->error == stInPostApi::VALIDATION_FAILED)
{
if (isset($error->details->cod))
{
$request->setError('paczkomaty_pack{cash_on_delivery}', stInPostApi::formatDetailError($error->details->cod));
}
if (isset($error->details->insurance))
{
$request->setError('paczkomaty_pack{insurance}', stInPostApi::formatDetailError($error->details->insurance));
}
if (isset($error->details->custom_attributes))
{
foreach ($error->details->custom_attributes as $item)
{
if (isset($item->dropoff_point) && $item->dropoff_point[0] == "dropoff_and_target_points_must_be_different")
{
$request->setError('paczkomaty_pack{dropoff_point}', $i18n->__('Paczkomat nadawcy nie może być taki sam jak paczkomat odbiorcy'));
}
}
}
if (isset($error->details->receiver[0]->email))
{
$request->setError('paczkomaty_pack{customer_email}', stInPostApi::formatDetailError($error->details->receiver[0]->email));
}
if (isset($error->details->receiver[0]->address[0]->post_code))
{
$request->setError('paczkomaty_pack{customer_post_code}', stInPostApi::formatDetailError($error->details->receiver[0]->address[0]->post_code));
}
if (isset($error->details->sender[0]->phone))
{
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$request->setError('api', $i18n->__('Numer nadawcy jest nieprawidłowy. Numer musi być podany w formacie 9 cyfrowym bez spacji oraz myślników. Przejdź do %link%, aby skorygować problem.', array(
'%link%' => st_link_to($i18n->__('konfiguracji'), '@stPaczkomatyPlugin?action=config', array('target' => '_blank')),
)));
}
if (isset($error->details->sender[0]->address[0]->post_code))
{
sfLoader::loadHelpers(array('Helper', 'stUrl'));
$request->setError('api', $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')),
)));
}
if (isset($error->details->service))
{
$request->setError('api', stInPostApi::formatDetailError($error->details->service));
}
if (!$request->hasErrors())
{
$request->setError('api', $i18n->__("Wystąpił nieobsługiwany wyjątek (błąd: %error%)", array('%error%' => json_encode($error->details))));
}
}
else
{
$request->setError('api', $e->getMessage());
}
}
}
}
return !$request->hasErrors();
}
/**
* Zapisuje model PaczkomatyPack
*
* @param PaczkomatyPack $pack
* @return void
*/
protected function savePaczkomatyPack($pack)
{
$response = $this->getRequest()->getParameter('create_shipment', null, 'soteshop/stInPostApi');
if (!$pack->isNew() && $pack->getInpostShipmentId())
{
$api = stInPostApi::getInstance();
$api->deleteShipment($pack->getInpostShipmentId());
}
$pack->setInpostShipmentId($response->id);
$pack->setStatus($response->status);
$pack->setTrackingNumber($response->tracking_number);
$parcels = $pack->getParcels();
foreach ($response->parcels as $index => $parcel)
{
$parcels[$index]['number'] = $parcel->tracking_number;
}
$pack->setParcels($parcels);
$isNew = $pack->isNew();
$result = parent::savePaczkomatyPack($pack);
if ($isNew)
{
$this->updateOrderStatus($pack->getOrder());
}
return $result;
}
public function executeEasypackWidget()
{
$this->setLayout(false);
if (!$this->getRequestParameter('sandbox'))
{
$this->endpoint = 'https://api-pl-points.easypack24.net/v1';
}
else
{
$this->endpoint = 'https://stage-api-pl-points.easypack24.net/v1';
}
$this->scope = $this->getRequestParameter('scope');
}
public function validateConfig()
{
$request = $this->getRequest();
$this->config = stConfig::getInstance('stPaczkomatyBackend');
$api = stInPostApi::getInstance();
$i18n = $this->getContext()->getI18N();
if ($request->getMethod() == sfRequest::POST)
{
$this->updateConfigFromRequest();
if ($this->config->get('enabled'))
{
if (!$this->config->get('token'))
{
$request->setError('config{token}', $i18n->__('Proszę uzupełnić pole.'));
}
if (!$request->hasErrors())
{
if ($api->isValid())
{
if (!$this->config->get('sending_method'))
{
$request->setError('config{sending_method}', $i18n->__('Proszę uzupełnić pole.'));
}
elseif ($this->config->get('sending_method') == 'parcel_locker' && !$this->config->get('dropoff_point'))
{
$request->setError('config{dropoff_point}', $i18n->__('Proszę uzupełnić pole.'));
}
$required = array('sender_email', 'sender_country_code', 'sender_street', 'sender_building', 'sender_city', 'sender_post_code');
if (!$this->config->get('sender_company') && (!$this->config->get('sender_company') || !$this->config->get('sender_company')))
{
$required = array_merge(array('sender_name', 'sender_surname'), $required);
}
foreach ($required as $field)
{
if (!$this->config->get($field))
{
$request->setError('config{' . $field . '}', $i18n->__('Proszę uzupełnić pole.'));
}
}
}
try
{
$organizations = $api->getOrganizations();
$request->setParameter('organizations', $organizations, 'soteshop/stInPostApi');
}
catch (stInPostApiException $e)
{
$request->setError('api', $e->getMessage());
}
}
}
}
if ($this->config->get('enabled') && $this->config->get('token') && !$request->hasErrors() && !$api->isValid())
{
$request->setError('api', $api->getLastErrorMessage());
}
return !$request->hasErrors();
}
protected function updateConfigFromRequest()
{
parent::updateConfigFromRequest();
$this->updateSenderFromOrganization();
}
protected function updateOrderStatus(Order $order)
{
$config = stConfig::getInstance('stPaczkomatyBackend');
if ($config->get('order_status') && $order->getOrderStatusId() != $config->get('order_status'))
{
$order->setOrderStatusId($config->get('order_status'));
$order->save();
if ($order->getOrderStatus()->getHasMailNotification())
{
$orderNotification = new stOrderMailNotification($this->getContext());
$orderNotification->sendStatusChangeNotification($order);
}
}
}
protected function saveConfig()
{
$ret = parent::saveConfig();
stTheme::clearSmartyCache(true);
return $ret;
}
protected function updateSenderFromOrganization()
{
$organizations = $this->getRequest()->getParameter('organizations', null, 'soteshop/stInPostApi');
if ($organizations && !$this->config->get('organization'))
{
$organization = $organizations->items[0];
$this->config->set('organization', $organization->id);
$this->config->set('sender_company', $organization->name);
$this->config->set('sender_street', $organization->address->street);
$this->config->set('sender_building', $organization->address->building_number);
$this->config->set('sender_post_code', $organization->address->post_code);
$this->config->set('sender_country_code', $organization->address->country_code);
$this->config->set('sender_city', $organization->address->city);
$this->config->set('sender_email', $organization->contact_person->email);
$this->config->set('sender_phone', $organization->contact_person->phone);
$this->config->set('sender_name', $organization->contact_person->first_name);
$this->config->set('sender_surname', $organization->contact_person->last_name);
$this->config->set('services', $organization->services);
}
}
protected function updatePaczkomatyPackFromRequest()
{
parent::updatePaczkomatyPackFromRequest();
$data = $this->getRequestParameter('paczkomaty_pack');
foreach (array('customer_email', 'customer_phone', 'customer_paczkomat', 'use_sender_paczkomat', 'sender_paczkomat', 'pack_type', 'insurance', 'cash_on_delivery', 'description') as $v)
{
if (isset($data[$v]))
{
call_user_func(array($this->paczkomaty_pack, sfInflector::camelize('set_' . $v)), $data[$v]);
}
}
if (!isset($data['insurance']))
{
$this->paczkomaty_pack->setInsurance(null);
}
if (!isset($data['cash_on_delivery']))
{
$this->paczkomaty_pack->setCashOnDelivery(null);
}
}
protected function getLabels()
{
$labels = parent::getLabels();
$labels['api'] = 'InPost';
return $labels;
}
protected function getConfigLabels()
{
$labels = parent::getConfigLabels();
$labels['api'] = 'InPost';
return $labels;
}
protected function addFiltersCriteria($c)
{
parent::addFiltersCriteria($c);
if (isset($this->filters['dispatch_order']) && !empty($this->filters['dispatch_order']))
{
$c->add(PaczkomatyDispatchOrderPeer::DISPATCH_ORDER_EXTERNAL_ID, $this->filters['dispatch_order']);
}
if (isset($this->filters['service_type']) && !empty($this->filters['service_type']))
{
$c->addJoin(OrderPeer::ORDER_DELIVERY_ID, OrderDeliveryPeer::ID);
$c->addJoin(OrderDeliveryPeer::DELIVERY_ID, DeliveryPeer::ID);
$c->addJoin(DeliveryPeer::TYPE_ID, DeliveryTypePeer::ID);
$c->add(DeliveryTypePeer::TYPE, $this->filters['service_type']);
}
}
protected function deleteDispatchOrderPaczkomatyDispatchOrder($dispatchOrder)
{
$i18n = $this->getContext()->getI18N();
if (!in_array($dispatchOrder->getStatus(), ['sent', 'new']))
{
throw new Exception($i18n->__('Zlecenie odbioru %%dispatch_order%% posiada nieprawidłowy status.', ['%%dispatch_order%%' => $dispatchOrder->getDispatchOrderExternalId()]));
}
$api = stInPostApi::getInstance();
try
{
$api->deleteDispatchOrder($dispatchOrder->getDispatchOrderId());
}
catch (stInPostApiException $e)
{
throw new Exception($i18n->__('Zlecenie odbioru "%%dispatch_order%%": %%message%%', [
'%%dispatch_order%%' => $dispatchOrder->getDispatchOrderExternalId(),
'%%message%%' => $e->getMessage(),
]));
}
return parent::deleteDispatchOrderPaczkomatyDispatchOrder($dispatchOrder);
}
protected function downloadDocument(string $content, string $filename, string $type = 'Pdf')
{
$types = [
'Pdf' => 'application/pdf',
'Zpl' => 'application/octet-stream',
'Epl' => 'application/octet-stream',
];
if (!isset($types[$type]))
{
throw new Exception(sprintf('Przekazany typ plik nie jest obsługiwany (dostępne: %s)', implode(', ', array_keys($types))));
}
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->setHttpHeader('Content-Type', $types[$type]);
$this->getResponse()->setHttpHeader('Content-Disposition', 'attachment;filename=' . $filename . '.' . lcfirst($type));
return $this->renderText($content);
}
protected function validateParcelSize(PaczkomatyPack $pack, array $parcels)
{
$errors = [];
$validator = new stInPostParcelSizeValidator();
$validator->initialize($this->getContext(), [
'service' => $pack->getService(),
]);
if (!$validator->execute($parcels, $errors))
{
$this->getRequest()->setError('paczkomaty_pack{parcels}', implode('<br>', $errors));
}
}
protected function getActionSelectControlOptions()
{
$options = parent::getActionSelectControlOptions();
if (!stDeliveryTypeConfiguration::has('inpostk'))
{
array_pop($options['NONE']);
}
return $options;
}
}

View File

@@ -0,0 +1,14 @@
<?php
class stPaczkomatyBackendComponents extends autostPaczkomatyBackendComponents
{
public function addListMenuItems(array $items)
{
if (!stDeliveryTypeConfiguration::has('inpostk'))
{
unset($items['@stPaczkomatyPlugin?action=dispatchOrderList']);
}
return $items;
}
}

View File

@@ -0,0 +1,156 @@
generator:
class: stAdminGenerator
param:
model_class: PaczkomatyPack
dispatch_order_model_class: PaczkomatyDispatchOrder
theme: simple
head:
package: stPaczkomatyPlugin
documentation:
pl: "https://www.sote.pl/docs/paczkomaty"
en: "https://www.soteshop.com/docs/paczkomaty"
custom_actions:
list: [dispatch_order]
fields:
created_at: {name: Data utworzenia}
sender_paczkomat: {name: Paczkomat nadawcy}
use_sender_paczkomat: {name: Użyj Paczkomaty}
pack_type: {name: Rozmiar, type: plain}
insurance: {name: Kwota ubezpieczenia, type: plain}
cash_on_delivery: {name: Kwota pobrania, type: plain}
description: {name: Kod referencyjny, type: plain}
code: {name: Numer trackingowy przesyłki}
status_label: {name: Status, type: plain}
status_changed_at: {name: Aktualizacja statusu w systemie Paczkomaty.pl}
order_number: {name: Numer zamówienia}
tracking_number: {name: Numer trackingowy przesyłki, type: plain}
list:
use_helper: [stPaczkomatyBackend]
forward_parameters: [order_id]
menu:
display: [list, dispatch_order_list, config]
fields:
list: {name: Przesyłki, action: "@stPaczkomatyPlugin"}
dispatch_order_list: {name: Zlecenia odbioru, action: "@stPaczkomatyPlugin?action=dispatchOrderList"}
config: {name: Konfiguracja, action: "@stPaczkomatyPlugin?action=config"}
title: Przesyłki
description: Zarządzanie paczkami
display: [created_at, order_number, code, service_type, _sending_method, status_label, _dispatch_order_id]
sort: [created_at, desc]
fields:
order_number: {sort_field: order.number}
dispatch_order_id: {name: Zlecenie odbioru}
sending_method: {name: Metoda wysyłki, params: truncate_text=true}
status_label: {params: truncate_text=true}
service_type: {name: Rodzaj, params: truncate_text=true}
filters:
sending_method: {partial: sending_method_filter}
dispatch_order_id: {partial: dispatch_order_filter}
service_type: {partial: service_type_filter}
peer_method: doSelectWithShipX
actions: []
object_actions:
dispatch_order: {name: Zlecenie odbioru, action: dispatchOrder, icon: courier, params: show_preloader=true}
download_label: {name: Pobierz etykietę, action: downloadLabel, i18n: stPaczkomatyBackend, icon: download}
_edit: {name: "Edycja"}
_delete: -
select_actions:
display:
"NONE": [dispatch_order]
actions:
_delete: -
dispatch_order: {name: "Zleć odbiór", action: dispatchOrder}
create:
title: Dodaj nową paczkę
edit:
use_helper: [stPaczkomatyBackend, stPrice, stDelivery, Countries]
title: Przesyłka
display:
"NONE": [service_type, status_label, tracking_number]
"Dane odbiorcy": [customer_company_name, customer_name, customer_street, customer_building_number, customer_post_code, customer_city, _customer_country_code, customer_email, customer_phone, _customer_pickup_point]
"Dane nadawcy": [_sending_method, _dropoff_point]
"Zawartość": [_parcels]
"Dodatkowe informacje": [_pack_type, _insurance, _cash_on_delivery, _end_of_week_collection, _description]
fields:
service_type: {name: Rodzaj, type: plain}
customer_street: {name: Ulica, plain_on_edit: true, required: true}
customer_building_number: {name: Numer budynku/lokalu, plain_on_edit: true, required: true}
customer_country_code: {name: Kraj, required: true, params: iso=true, plain_on_edit: true}
customer_post_code: {name: Kod pocztowy, required: true, plain_on_edit: true}
customer_city: {name: Miasto, required: true, plain_on_edit: true}
customer_name: {name: Imię i nazwisko, plain_on_edit: true}
customer_company_name: {name: Nazwa firmy, plain_on_edit: true}
customer_email: {name: Adres e-mail, plain_on_edit: true, required: true}
customer_phone: {name: Numer telefonu, plain_on_edit: true, required: true}
sending_method: {name: Metoda wysyłki, type: plain}
dropoff_point: {name: Paczkomat nadawcy, required: true, type: custom}
customer_pickup_point: {name: Paczkomat odbiorcy, required: true, type: custom}
end_of_week_collection: {name: Paczka w weekend, type: checkbox_tag, plain_on_edit: true}
parcels: {name: Paczki}
actions:
download_sticker: {name: Pobierz etykietę, action: downloadLabel, i18n: stPaczkomatyBackend, icon: download}
_save: {name: Utwórz i opłać paczkę, i18n: stPaczkomatyBackend}
dispatch_order_list:
title: Zlecenia odbioru
display: [created_at, dispatch_order_external_id, parcels, status_label]
fields:
created_at: {name: Utworzone}
dispatch_order_external_id: {name: Numer}
status: {name: Status, sort_field: status}
parcels: {name: Przesyłki, params: truncate_text=true truncate_text_lines=2}
peer_method: doSelectWithShipX
actions: []
object_actions:
dispatch_order_printout: {name: "Pobierz wydruk", action: dispatchOrderPrintOut, icon: download}
_delete: -
config:
use_helper: [stPaczkomatyBackend, Countries]
use_javascript: [/plugins/stPaczkomatyPlugin/js/backend.js]
menu: {use: list.menu}
title: Konfiguracja
display:
"NONE": [enabled, sandbox, token, _organization, _order_status]
"Domyślne ustawienia": [label_type, label_format, sending_method, dropoff_point]
"Informacje o nadawcy na paczce": [sender_company, sender_name, sender_surname, sender_email, sender_phone, sender_country_code, sender_street, sender_building, sender_city, sender_post_code]
fields:
sandbox: {name: Tryb testowy, type: checkbox}
enabled: {name: Włącz, type: checkbox}
organization: {name: Organizacja, required: true}
token: {name: Token, type: password, params: size=80 autocomplete=off, required: true}
order_status: {name: Zmień status zamówienia na, help: "Zmienia status zamówienia po utworzeniu paczki"}
sending_method: {name: Metoda wysyłki, callback: st_inpost_sending_method_select_tag, params: service=inpost_locker_standard target=".row_dropoff_point", required: true}
dropoff_point: {name: Paczkomat nadawcy, callback: st_inpost_point_select_tag, required: true, type: plain}
label_type:
name: Typ etykiety
type: select
display: [a4, a6]
options:
a4: {name: A4, value: normal}
a6: {name: A6, value: A6}
label_format:
name: Format etykiety
type: select
options:
Epl: {name: EPL}
Pdf: {name: PDF}
Zpl: {name: ZPL}
sender_name: {name: Imię}
sender_company: {name: Nazwa firmy}
sender_surname: {name: Nazwisko}
sender_email: {name: E-mail, required: true}
sender_phone: {name: Numer telefonu, required: true}
sender_street: {name: Ulica, required: true}
sender_building: {name: Numer budynku / lokalu, params: size=7, required: true}
sender_city: {name: Miasto, required: true}
sender_post_code: {name: Kod pocztowy, params: size=7, required: true}
sender_country_code: {name: Kraj, callback: st_countries_select_tag, params: iso=true, required: true}
actions:
_save: {name: Zapisz}

View File

@@ -0,0 +1,251 @@
<?php
function st_inpost_organization_select_tag($name, $value, array $params = array())
{
$api = stInPostApi::getInstance();
$organizations = sfContext::getInstance()->getRequest()->getParameter('organizations', null, 'soteshop/stInPostApi');
if (null === $organizations)
{
try
{
$organizations = $api->getOrganizations();
}
catch(stInPostApiException $e)
{
}
}
if ($organizations)
{
foreach ($organizations->items as $organization)
{
$options[$organization->id] = $organization->name;
}
}
else
{
$options = array();
}
return select_tag($name, options_for_select($options, $value), $params);
}
function st_inpost_sending_method_select_tag($name, $value, array $params = array())
{
$api = stInPostApi::getInstance();
$service = null;
if (isset($params['service']))
{
$service = $params['service'];
unset($params['service']);
}
$target = null;
if (isset($params['target']))
{
$target = $params['target'];
}
$includeCustom = __('Wybierz');
if (isset($params['include_custom']))
{
$includeCustom = $params['include_custom'];
}
$options = array();
try
{
$options = $api->getSendingMethods($service);
}
catch (stInPostApiException $e)
{
}
$content = select_tag($name, options_for_select($options, $value, array('include_custom' => $includeCustom)), $params);
if ($target)
{
$id = get_id_from_name($name);
$content .=<<<HTML
<script>
jQuery(function($) {
\$('#$id').change(function() {
var select = \$(this);
if (select.val() == 'parcel_locker') {
$('$target').show();
} else {
$('$target').hide();
}
}).change();
});
</script>
HTML;
}
return $content;
}
function st_inpost_point_select_tag($name, $value, array $params = array())
{
static $init = false;
$config = stConfig::getInstance('stPaczkomatyBackend');
$api = stInPostApi::getInstance();
$i18n = sfContext::getInstance()->getI18N();
$label = $i18n->__('Wybierz punkt');
$id = get_id_from_name($name);
$title = isset($params['title']) ? __($params['title']) : __('Wybierz punkt');
$disabled = isset($params['disabled']) && $params['disabled'];
$js = '';
$trigger = '';
if (!$disabled)
{
if (!$init)
{
$easypackWidgetUrl = st_url_for('@stPaczkomatyPlugin?action=easypackWidget&sandbox=' . $api->isSandbox());
$js =<<<HTML
<div id="inpost-easypack-modal" class="popup_window" style="width: 800px">
<div class="close"><img src="/images/backend/beta/gadgets/close.png" alt="" /></div>
<h2></h2>
<div class="content"></div>
</div>
<script>
jQuery(function($) {
$('body').append($('#inpost-easypack-modal'));
$('.inpost-easypack-widget').overlay({
closeOnClick: false,
closeOnEsc: false,
top: "5%",
speed: 'fast',
oneInstance: true,
fixed: false,
mask: {
color: '#444',
loadSpeed: 'fast',
opacity: 0.5,
zIndex: 30000
},
target: '#inpost-easypack-modal',
onClose: function() {
},
onBeforeLoad: function() {
var api = this;
var content = this.getOverlay().children('.content');
var title = this.getOverlay().children('h2');
var overlay = this.getOverlay();
var scope = this.getTrigger().data('related')
title.html(this.getTrigger().data('title'));
content.html('<iframe src="$easypackWidgetUrl?scope='+scope+'" style="width: 100%; height: 536px; border: none;"></iframe>');
overlay.css("top", Math.max(28, $(window).scrollTop() + 60) + "px");
overlay.css("left", Math.max(0, (($(window).width() - overlay.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
},
onLoad: function() {
var overlay = this.getOverlay();
overlay.css("top", Math.max(28, $(window).scrollTop() + 60) + "px");
overlay.css("left", Math.max(0, (($(window).width() - overlay.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
}
});
});
/*
window.easyPackAsyncInit = function () {
var defaults = {
defaultLocale: 'pl',
apiEndpoint: '',
mapType: 'osm',
searchType: 'osm',
display: {
showTypesFilters: false
},
points: {
types: ['parcel_locker', 'pop']
},
map: {
initialTypes: ['parcel_locker', 'pop']
}
}
jQuery(function($) {
easyPack.init(defaults);
var link = null;
var map = null;
$('.inpost-easypack-widget').click(function() {
link = $(this);
if (link.data('selected')) {
map.searchLockerPoint(link.data('selected'));
}
map = easyPack.modalMap(function(point, modal) {
var scope = '#' + link.data('related');
$(scope + '_label').html(point.name + '<p>' + point.address.line1 + ', ' + point.address.line2 + '</p>');
link.data('selected', point.name);
$(scope).val(point.name);
modal.closeModal();
}, { width: 500, height: 600 });
return false;
});
});
};
*/
</script>
HTML;
}
$trigger = st_get_admin_button('default', $label, '#', array(
'id' => $id.'_trigger',
'class' => 'inpost-easypack-widget bs-mt-1',
'data-title' => $title,
'data-related' => $id,
'size' => 'small',
));
// $trigger = '<a href="#" id="'.$id.'_trigger" class="inpost-easypack-widget" data-title="'. $title .'" data-related="' . $id . '">' . $label . '</a>';
$init = true;
}
$selected = __('Brak wybranego punktu');
if ($value)
{
try
{
$point = $api->getPoint($value);
$selected = $point->name . '<p>' . $point->address->line1 . ', ' . $point->address->line2 . '</p>';
}
catch(stInPostApiException $e)
{
}
}
return input_hidden_tag($name, $value) . '<div id="' . $id . '_label">' . $selected . '</div>' . $trigger . $js;
}

View File

@@ -0,0 +1,28 @@
<?php
class stPaczkomatyBackendBreadcrumbsBuilder extends autoStPaczkomatyBackendBreadcrumbsBuilder
{
public function getDefaultBreadcrumbs()
{
if ($this->relatedObject instanceof Order)
{
if (null === $this->defaultBreadcrumbs)
{
stAdminGeneratorHelper::generate('stOrder');
if (isset($this->forwardParameters['order_id']))
{
unset($this->forwardParameters['order_id']);
}
$orderBreadcrumbsBuilder = new stOrderBreadcrumbsBuilder($this->context, $this->breadcrumbs, null, $this->forwardParameters);
$this->defaultBreadcrumbs = $orderBreadcrumbsBuilder->getEditBreadcrumbs($this->relatedObject);
$this->defaultBreadcrumbs->add($this->appTitle, $this->appRoute);
}
return $this->defaultBreadcrumbs;
}
return parent::getDefaultBreadcrumbs();
}
}

View File

@@ -0,0 +1,79 @@
<?php use_javascript('stPrice.js') ?>
<?php if($paczkomaty_pack->isNew()):?>
<div class="row">
<label for="paczkomaty_pack_pack_type">
<?php echo __('Rozmiar', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo select_tag('paczkomaty_pack[pack_type]', options_for_select(array('A' => 'A (8 x 38 x 64 cm)', 'B' => 'B (19 x 38 x 64 cm)', 'C' => 'C (41 x 38 x 64 cm)'), !$sf_request->hasParameter('paczkomaty_pack[pack_type]') ? $paczkomaty_pack->getPackType() : $sf_request->getParameter('paczkomaty_pack[pack_type]')));?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_insurance">
<?php echo __('Kwota ubezpieczenia', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo st_admin_optional_input('paczkomaty_pack[insurance]', $paczkomaty_pack->getInsurance() ? $paczkomaty_pack->getInsurance() : $paczkomaty_pack->getInsurance(true), array('size' => 7, 'disabled' => !$paczkomaty_pack->getInsurance() && !$paczkomaty_pack->hasAllegroInsurance())); ?> PLN
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_cash_on_delivery">
<?php echo __('Kwota pobrania', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo st_admin_optional_input('paczkomaty_pack[cash_on_delivery]', $paczkomaty_pack->getCashOnDelivery() ? $paczkomaty_pack->getCashOnDelivery() : $paczkomaty_pack->getCashOnDelivery(true), array('size' => 7, 'disabled' => !$paczkomaty_pack->getCashOnDelivery() && ($sf_request->getMethod() == sfRequest::POST || !$paczkomaty_pack->hasCashOnDelivery()))); ?> PLN
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_description">
<?php echo __('Numer referencyjny', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo input_tag('paczkomaty_pack[description]', !$sf_request->hasParameter('paczkomaty_pack[description]') ? $paczkomaty_pack->getDescription() : $sf_request->getParameter('paczkomaty_pack[description]'), array('size' => 80));?>
<div class="clr"></div>
</div>
<script type="text/javascript" language="javascript">
jQuery(function($) {
$(document).ready(function() {
$('#paczkomaty_pack_insurance').change(function() {
$(this).val(stPrice.fixNumberFormat($(this).val()));
});
$('#paczkomaty_pack_cash_on_delivery').change(function() {
$(this).val(stPrice.fixNumberFormat($(this).val()));
});
});
});
</script>
<?php else:?>
<div class="row">
<label for="paczkomaty_pack_pack_type">
<?php echo __('Rozmiar', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo $paczkomaty_pack->getPackType();?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_insurance">
<?php echo __('Kwota ubezpieczenia', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo stPrice::round($paczkomaty_pack->getInsurance()); ?> PLN
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_cash_on_delivery">
<?php echo __('Kwota pobrania', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo stPrice::round($paczkomaty_pack->getCashOnDelivery()); ?> PLN
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_description">
<?php echo __('Numer referencyjny', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo $paczkomaty_pack->getDescription();?>
<div class="clr"></div>
</div>
<?php endif;?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @var PaczkomatyPack $paczkomaty_pack
*/
$currency = 'PLN';
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
$cashOnDelivery = $paczkomaty_pack->getCashOnDelivery() ? $paczkomaty_pack->getCashOnDelivery() : $paczkomaty_pack->getCashOnDelivery(true);
echo st_admin_optional_input('paczkomaty_pack[cash_on_delivery]', st_price_format($cashOnDelivery), array(
'size' => 7,
'disabled' => !$paczkomaty_pack->getCashOnDelivery() && ($sf_request->getMethod() == sfRequest::POST || !$paczkomaty_pack->hasCashOnDelivery())
)) . ' ' . $currency;
}
else
{
echo stPrice::round($paczkomaty_pack->getCashOnDelivery()) . ' ' . $currency;
}
?>
<script type="text/javascript" language="javascript">
jQuery(function($) {
$('#paczkomaty_pack_cash_on_delivery').change(function() {
$(this).val(stPrice.fixNumberFormat($(this).val()));
});
});
</script>

View File

@@ -0,0 +1,78 @@
<?php
use_helper('stPaczkomaty');
$paczkomaty_params = array();
if ($paczkomaty_pack->hasAllegroTransactionId())
{
$paczkomaty_params['function'] = 'AllegroParcelCollect';
}
else
{
$paczkomaty_params['function'] = 'ParcelCollect';
}
if ($paczkomaty_pack->hasCashOnDelivery())
{
$paczkomaty_params['paymentavailable'] = 't';
}
?>
<?php if($paczkomaty_pack->isNew()):?>
<?php echo input_hidden_tag('order', $sf_request->getParameter('order'));?>
<div class="row">
<label for="paczkomaty_pack_customer_email">
<?php echo __('Adres e-mail odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<div class="field<?php if ($sf_request->hasError('paczkomaty_pack{customer_email}')):?> form-error<?php endif; ?>">
<?php if ($sf_request->hasError('paczkomaty_pack{customer_email}')):?>
<?php echo form_error('paczkomaty_pack{customer_email}', array('class' => 'form-error-msg'));?>
<?php endif;?>
<?php echo input_tag('paczkomaty_pack[customer_email]', !$sf_request->hasParameter('paczkomaty_pack[customer_email]') ? $paczkomaty_pack->getCustomerEmail() : $sf_request->getParameter('paczkomaty_pack[customer_email]'), array('size' => 30));?>
<div class="clr"></div>
</div>
</div>
<div class="row">
<label for="paczkomaty_pack_customer_phone">
<?php echo __('Numer komórkowy odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<div class="field<?php if ($sf_request->hasError('paczkomaty_pack{customer_phone}')): ?> form-error<?php endif;?>">
<?php if ($sf_request->hasError('paczkomaty_pack{customer_phone}')):?>
<?php echo form_error('paczkomaty_pack{customer_phone}', array('class' => 'form-error-msg'));?>
<?php endif;?>
<?php echo input_tag('paczkomaty_pack[customer_phone]', !$sf_request->hasParameter('paczkomaty_pack[customer_phone]') ? $paczkomaty_pack->getCustomerPhone() : $sf_request->getParameter('paczkomaty_pack[customer_phone]'), array('size' => 15));?>
<div class="clr"></div>
</div>
</div>
<div class="row">
<label for="paczkomaty_pack_customer_paczkomat">
<?php echo __('Paczkomat odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<?php show_paczkomaty_dropdown_list('paczkomaty_pack[customer_paczkomat]', $paczkomaty_pack->getCustomerPaczkomat(), array('paczkomaty' => $paczkomaty_params));?>
<div class="clr"></div>
</div>
<?php else:?>
<div class="row">
<label for="paczkomaty_pack_customer_email">
<?php echo __('Adres e-mail odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo $paczkomaty_pack->getCustomerEmail();?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_customer_phone">
<?php echo __('Numer komórkowy odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo $paczkomaty_pack->getCustomerPhone();?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_customer_paczkomat">
<?php echo __('Paczkomat odbiorcy', array(), 'stPaczkomatyBackend');?>:
</label>
<div id="st-paczkomaty-customer-machine">
<img src="/images/backend/icons/indicator.gif" alt="loading..." />
</div>
<div class="clr"></div>
</div>
<?php endif;?>

View File

@@ -0,0 +1,9 @@
<?php
if (!$value->isAdminGeneratorPlainField())
{
echo st_countries_select_tag($name, $value->$method(), $options);
}
else
{
echo $value->$method() ? CountriesPeer::retrieveByIsoA2($value->$method()) : '-';
}

View File

@@ -0,0 +1,10 @@
<?php
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo input_tag('paczkomaty_pack[customer_email]', $paczkomaty_pack->getCustomerEmail(), array('size' => 80));
}
else
{
echo $paczkomaty_pack->getCustomerEmail();
}
?>

View File

@@ -0,0 +1,10 @@
<?php
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo input_tag('paczkomaty_pack[customer_phone]', $paczkomaty_pack->getCustomerPhone(), array('size' => 80));
}
else
{
echo $paczkomaty_pack->getCustomerPhone();
}
?>

View File

@@ -0,0 +1,4 @@
<?php echo st_inpost_point_select_tag('paczkomaty_pack[customer_pickup_point]', $paczkomaty_pack->getCustomerPickupPoint(), array (
'title' => 'Paczkomat odbiorcy',
'disabled' => $paczkomaty_pack->isAdminGeneratorPlainField()
)); ?>

View File

@@ -0,0 +1,2 @@
<?php use_helper('stPaczkomaty');
echo show_paczkomaty_dropdown_list('config[default_sender_paczkomat]', !$sf_request->hasParameter('config[default_sender_paczkomat]') ? $config->get('default_sender_paczkomat') : $sf_request->getParameter('config[default_sender_paczkomat]'), array('paczkomaty' => array('function' => 'ParcelSend')));

View File

@@ -0,0 +1,10 @@
<?php
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo input_tag('paczkomaty_pack[description]', !$sf_request->hasParameter('paczkomaty_pack[description]') ? $paczkomaty_pack->getDescription() : $sf_request->getParameter('paczkomaty_pack[description]'), array('size' => 80));
}
else
{
echo $paczkomaty_pack->getDescription();
}
?>

View File

@@ -0,0 +1,2 @@
<?php
echo input_tag('filters[dispatch_order]', isset($filters['dispatch_order']) ? $filters['dispatch_order'] : null, ['id' => 'filters_dispatch_order_id', 'size' => 14]);

View File

@@ -0,0 +1,6 @@
<?php
/**
* @var PaczkomatyPack $paczkomaty_pack
*/
echo $paczkomaty_pack->getPaczkomatyDispatchOrder();

View File

@@ -0,0 +1,4 @@
<?php echo st_inpost_point_select_tag('paczkomaty_pack[dropoff_point]', $paczkomaty_pack->getDropoffPoint(), array (
'title' => 'Paczkomat nadawcy',
'disabled' => $paczkomaty_pack->isAdminGeneratorPlainField()
)); ?>

View File

@@ -0,0 +1,10 @@
<?php
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo st_admin_checkbox_tag('paczkomaty_pack[end_of_week_collection]', true, $paczkomaty_pack->getEndOfWeekCollection());
}
else
{
echo $paczkomaty_pack->getEndOfWeekCollection() ? __("Tak", null, "stAdminGeneratorPlugin") : __("Nie", null, "stAdminGeneratorPlugin");
}
?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @var PaczkomatyPack $paczkomaty_pack
*/
$currency = 'PLN';
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
$insuranceAmount = $paczkomaty_pack->getInsurance() ? $paczkomaty_pack->getInsurance() : $paczkomaty_pack->getInsurance(true);
echo st_admin_optional_input('paczkomaty_pack[insurance]', st_price_format($insuranceAmount), array(
'size' => 7,
'disabled' => !$paczkomaty_pack->getInsurance() && !$paczkomaty_pack->hasAllegroInsurance()
)) . ' ' . $currency;
}
else
{
echo stPrice::round($paczkomaty_pack->getInsurance()) . ' ' . $currency;
}
?>
<script type="text/javascript" language="javascript">
jQuery(function($) {
$('#paczkomaty_pack_insurance').change(function() {
$(this).val(stPrice.fixNumberFormat($(this).val()));
});
});
</script>

View File

@@ -0,0 +1,7 @@
<div>
<?php if ($pp): ?>
<a href="<?php echo $pp->getTrackingUrl() ?>" target="_blank" style="display: inline-block; padding-right: 15px; background: #444; color: #fafafa; text-decoration: none"><img src="/images/backend/icons/inpost-zolte-tlo.png" style="line-height: 0; vertical-align: middle; padding-right: 15px"; /><span style="vertical-align: middle;"><?php echo __('Śledź przesyłkę') ?></span></a>
<?php else: ?>
<a href="<?php echo url_for('@stPaczkomatyCreatePack?order='.$order->getId());?>" style="display: inline-block; padding-right: 15px; background: #444; color: #fafafa; text-decoration: none"><img src="/images/backend/icons/inpost-zolte-tlo.png" style="line-height: 0; vertical-align: middle; padding-right: 15px"; /><span style="vertical-align: middle;"><?php echo __('Wyślij paczkę') ?></span></a>
<?php endif ?>
</div>

View File

@@ -0,0 +1,3 @@
<?php use_helper('stOrder') ?>
<?php echo st_order_status_select_tag('config[order_status]', $config->get('order_status'), array('include_custom' => true)) ?>

View File

@@ -0,0 +1 @@
<?php echo st_inpost_organization_select_tag('config[organization]', $config->get('organization')); ?>

View File

@@ -0,0 +1,73 @@
<?php if(!$paczkomaty_pack->isNew()):?>
<div class="row">
<label for="paczkomaty_pack_code">
<?php echo __('Numer paczki', array(), 'stPaczkomatyBackend');?>:
</label>
<?php echo $paczkomaty_pack->getCode();?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_status">
<?php echo __('Status paczki', array(), 'stPaczkomatyBackend');?>:
</label>
<div id="st-paczkomaty-status">
<img src="/images/backend/icons/indicator.gif" alt="loading..." />
</div>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_status_changed_at">
<?php echo __('Aktualizacja statusu w systemie Paczkomaty.pl', array(), 'stPaczkomatyBackend');?>:
</label>
<div id="st-paczkomaty-status-date">
<img src="/images/backend/icons/indicator.gif" alt="loading..." />
</div>
<div class="clr"></div>
</div>
<script type="text/javascript" language="javascript">
jQuery(function ($) {
$(document).ready(function() {
$.getJSON('/backend.php/paczkomaty/getPackStatus?code=<?php echo $paczkomaty_pack->getCode();?>', function(data) {
$('#st-paczkomaty-status').html(data.clientStatus);
$('#st-paczkomaty-status-date').html(data.date);
<?php if($paczkomaty_pack->getStatus() == 'Created'):?>
if (data.status != 'Created') {
$('.action-pay_for_pack').hide();
$('.action-download_sticker input').attr('value', 'Pobierz etykiete');
$('.action-download_sticker input').css('background-image', 'url(/images/backend/icons/download_sticker.png)');
}
<?php endif;?>
});
$.getJSON('/paczkomaty/getMachine?number=<?php echo $paczkomaty_pack->getCustomerPaczkomat();?>', function(data) {
$('#st-paczkomaty-customer-machine').html(data.number + ', ' + data.street + ' ' + data.house + ', ' + data.postCode + ' ' + data.city);
});
<?php if($paczkomaty_pack->getUseSenderPaczkomat()):?>
$.getJSON('/paczkomaty/getMachine?number=<?php echo $paczkomaty_pack->getSenderPaczkomat();?>', function(data) {
$('#st-paczkomaty-sender-machine').html(data.number + ', ' + data.street + ' ' + data.house + ', ' + data.postCode + ' ' + data.city);
});
<?php endif;?>
$('.action-save').hide();
<?php if(!is_null($paczkomaty_pack->getStatus()) && $paczkomaty_pack->getStatus() != 'Created'):?>
$('.action-pay_for_pack').hide();
$('.action-download_sticker input').attr('value', 'Pobierz etykiete');
<?php else:?>
$('.action-download_sticker input').css('background-image', 'url(/images/backend/icons/pay_and_download.png)');
<?php endif;?>
});
});
</script>
<?php else:?>
<script type="text/javascript" language="javascript">
jQuery(function($) {
$(document).ready(function() {
$('#sf_fieldset_informacje_o_paczce').hide();
$('.action-pay_for_pack').hide();
$('.action-download_sticker').hide();
$('.action-list').hide();
});
});
</script>
<?php endif;?>

View File

@@ -0,0 +1,12 @@
<?php
$options = array('A' => 'A (8 x 38 x 64 cm)', 'B' => 'B (19 x 38 x 64 cm)', 'C' => 'C (41 x 38 x 64 cm)');
if (!$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo select_tag('paczkomaty_pack[pack_type]', options_for_select($options, !$sf_request->hasParameter('paczkomaty_pack[pack_type]') ? $paczkomaty_pack->getPackType() : $sf_request->getParameter('paczkomaty_pack[pack_type]')));
}
else
{
echo $options[$paczkomaty_pack->getPackType()];
}
?>

View File

@@ -0,0 +1 @@
<?php echo select_tag('delivery_dimension[paczkomaty_size]', options_for_select(array('NONE' => '-', 'A' => 'A (8 x 38 x 64 cm)', 'B' => 'B (19 x 38 x 64 cm)', 'C' => 'C (41 x 38 x 64 cm)'), !$sf_request->hasParameter('delivery_dimension[paczkomaty_size]') ? $delivery_dimension->getPaczkomatySize() : $sf_request->getParameter('delivery_dimension[paczkomaty_size]')));

View File

@@ -0,0 +1 @@
<?php echo select_tag('delivery[paczkomaty_type]', options_for_select(array('NONE' => __('Wyłączone'), 'ALL' => __('Wszystkie'), 'COD' => __('Z płatnością przy odbiorze')), $delivery->getPaczkomatyType()));

View File

@@ -0,0 +1,63 @@
<?php
/**
* @var PaczkomatyPack $paczkomaty_pack
*/
if ($type == 'list')
{
$trackingNumbers = [];
foreach ($paczkomaty_pack->getParcels() as $parcel)
{
$trackingNumbers[] = $parcel['number'];
}
echo implode(', ', $trackingNumbers);
}
else
{
echo delivery_parcels_manager_tag('paczkomaty_pack[parcels]', $paczkomaty_pack->getParcels(), [
'fields' => [
'weight' => [
'label' => __('Waga [kg]'),
'type' => !$paczkomaty_pack->isAdminGeneratorPlainField() ? 'input_tag' : 'plain',
'options' => [
'data-format' => 'decimal',
'data-format-min-value' => 0.1,
'size' => 8
],
],
'width' => [
'label' => __('Szerokość [cm]'),
'type' => !$paczkomaty_pack->isAdminGeneratorPlainField() ? 'input_tag' : 'plain',
'options' => [
'data-format' => 'integer',
'data-format-min-value' => 1,
'size' => 8,
'class' => 'app-dpd-size'
],
],
'height' => [
'label' => __('Wysokość [cm]'),
'type' => !$paczkomaty_pack->isAdminGeneratorPlainField() ? 'input_tag' : 'plain',
'options' => [
'data-format' => 'integer',
'data-format-min-value' => 1,
'size' => 8,
'class' => 'app-dpd-size'
],
],
'length' => [
'label' => __('Długość [cm]'),
'type' => !$paczkomaty_pack->isAdminGeneratorPlainField() ? 'input_tag' : 'plain',
'options' => [
'data-format' => 'integer',
'data-format-min-value' => 1,
'size' => 8,
'class' => 'app-dpd-size'
],
],
],
'disabled' => $paczkomaty_pack->isAdminGeneratorPlainField(),
]);
}
?>

View File

@@ -0,0 +1,65 @@
<?php use_helper('stPaczkomaty');?>
<?php if($paczkomaty_pack->isNew()):
$paczkomaty_params = array();
if ($paczkomaty_pack->hasAllegroTransactionId())
{
$paczkomaty_params['function'] = 'ParcelSend,AllegroParcelSend';
}
else
{
$paczkomaty_params['function'] = 'ParcelSend';
}
?>
<div class="row">
<label for="paczkomaty_pack_use_sender_paczkomat">
<?php echo __('Użyj Paczkomatu', array(), 'stPaczkomatyBackend');?>
</label>
<?php $useSenderPaczkomat = !$sf_request->hasParameter('paczkomaty_pack[use_sender_paczkomat]') ? $paczkomaty_pack->getUseSenderPaczkomat() : $sf_request->getParameter('paczkomaty_pack[use_sender_paczkomat]');?>
<?php echo checkbox_tag('paczkomaty_pack[use_sender_paczkomat]', 1, $useSenderPaczkomat);?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_sender_paczkomat">
<?php echo __('Paczkomat nadawcy', array(), 'stPaczkomatyBackend');?>
</label>
<?php show_paczkomaty_dropdown_list('paczkomaty_pack[sender_paczkomat]', $paczkomaty_pack->getSenderPaczkomat(), array('disabled' => !$useSenderPaczkomat, 'paczkomaty' => array('function' => 'ParcelSend')));?>
<div class="clr"></div>
</div>
<script type="text/javascript" language="javascript">
jQuery(function($) {
$(document).ready(function() {
$('#paczkomaty_pack_use_sender_paczkomat').change(function() {
$('#paczkomaty_pack_sender_paczkomat').prop('disabled', !$(this).prop('checked'));
});
});
});
</script>
<?php else:?>
<div class="row">
<label for="paczkomaty_pack_customer_email">
<?php echo __('Użyj Paczkomatu', array(), 'stPaczkomatyBackend');?>:
</label>
<?php if ($paczkomaty_pack->getUseSenderPaczkomat()):?>
<img src="/images/backend/beta/icons/16x16/tick.png" alt="loading..." />
<?php else:?>
<img src="/images/backend/beta/icons/16x16/cancel.png" alt="loading..." />
<?php endif;?>
<div class="clr"></div>
</div>
<div class="row">
<label for="paczkomaty_pack_sender_paczkomat">
<?php echo __('Paczkomat nadawcy', array(), 'stPaczkomatyBackend');?>:
</label>
<?php if ($paczkomaty_pack->getUseSenderPaczkomat()):?>
<div id="st-paczkomaty-sender-machine">
<img src="/images/backend/icons/indicator.gif" alt="loading..." />
</div>
<?php else:?>
-
<?php endif;?>
<div class="clr"></div>
</div>
<?php endif;?>

View File

@@ -0,0 +1,27 @@
<?php
/**
* @var PaczkomatyPack $paczkomaty_pack
*/
if ($type == 'edit' && !$paczkomaty_pack->isAdminGeneratorPlainField())
{
echo st_inpost_sending_method_select_tag('paczkomaty_pack[sending_method]', $paczkomaty_pack->getSendingMethod(), array (
'service' => $paczkomaty_pack->getService(),
'target' => '.row_dropoff_point',
));
}
else
{
$api = stInPostApi::getInstance();
$methods = $api->getSendingMethods();
echo $methods[$paczkomaty_pack->getSendingMethod()];
}
?>
<?php if ($type == 'edit' && $paczkomaty_pack->isAdminGeneratorPlainField() && $paczkomaty_pack->getSendingMethod() != 'parcel_locker'): ?>
<script>
jQuery(function($) {
$('.row_dropoff_point').hide();
});
</script>
<?php endif ?>

View File

@@ -0,0 +1,3 @@
<?php
echo st_inpost_sending_method_select_tag($name, $value, ['include_custom' => '---']);

View File

@@ -0,0 +1,16 @@
<?php
$selectOptions = [];
foreach (['inpostp', 'inpostk'] as $type)
{
if (stDeliveryTypeConfiguration::has($type))
{
$service = stDeliveryTypeService::get($type);
$selectOptions[$service->getType()] = $service->getLabel();
}
}
echo select_tag($name, $selectOptions, [
'include_custom' => '---',
'selected' => isset($filters['service_type']) ? $filters['service_type'] : null
]);

View File

@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="pl" style="height: 100%;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta http-equiv="x-ua-compatible" content="IE=11"/>
<title>Geowidget v4 - Example - Search Locker Point</title>
<script src="https://geowidget.easypack24.net/js/sdk-for-javascript.js"></script>
<script type="text/javascript">
window.easyPackAsyncInit = function () {
easyPack.init({
instance: 'pl',
mapType: 'osm',
apiEndpoint: '<?php echo $endpoint ?>',
searchType: 'osm',
points: {
types: ['pop', 'parcel_locker'],
},
display: {
showTypesFilters: false
},
map: {
useGeolocation: true,
initialTypes: ['parcel_locker']
}
});
var scope = '#<?php echo $scope ?>';
$ = window.parent.jQuery;
var selected = $(scope);
var map = easyPack.mapWidget('easypack-map', function(point) {
$(scope + '_label').html(point.name + '<p>' + point.address.line1 + ', ' + point.address.line2 + '</p>');
selected.val(point.name);
$(scope + '_trigger').data('overlay').close();
});
if (selected.val()) {
map.searchLockerPoint(selected.val());
}
// setTimeout(function() {
// var modal = window.parent.jQuery('#inpost-easypack-modal');
// modal.find('iframe').height(window.document.body.scrollHeight);
// console.log('test');
// }, 2000);
}
</script>
<link rel="stylesheet" href="https://geowidget.easypack24.net/css/easypack.css"/>
</head>
<body>
<div id="easypack-map"></div>
</body>
</html>

View File

@@ -0,0 +1,18 @@
<?php use_helper('I18N', 'stAdminGenerator', 'Validation');?>
<?php echo st_get_admin_head('stPaczkomatyPlugin', __('Konfiguracja', array()), __('',array()),array('stPayment', 'stProduct','stDeliveryPlugin'));?>
<div id="sf_admin_content">
<div id="sf_admin_content_config">
<form>
<fieldset>
<div class="st_fieldset-content">
<div class="form-row">
<a href="<?php echo get_7_link();?>" target="_blank">Zamów aktualizację do wersji 7</a>
<br class="st_clear_all" />
</div>
</div>
</fieldset>
</form>
</div>
</div>
<br class="st_clear_all" />
<?php echo st_get_admin_foot();?>

View File

@@ -0,0 +1,8 @@
fields:
config{sender_phone}:
required:
msg: Proszę uzupełnić pole.
sfRegexValidator:
match: Yes
match_error: Podany numer jest nieprawidłowy. Numer musi być podany w formacie 9 cyfrowym bez spacji oraz myślników.
pattern: /^\d{9}$/

View File

@@ -0,0 +1,11 @@
fields:
paczkomaty_pack{customer_email}:
required:
msg: Proszę uzupełnić pole.
paczkomaty_pack{customer_phone}:
required:
msg: Proszę uzupełnić pole.
sfRegexValidator:
match: Yes
match_error: Podany numer jest nieprawidłowy. Numer musi być podany w formacie 9 cyfrowym bez spacji oraz myślników.
pattern: /^\d{9}$/

View File

@@ -0,0 +1,93 @@
<?php
class stPaczkomatyFrontendActions extends stActions
{
public function executeChooseDeliveryPoint()
{
$delivery_id = $this->getRequestParameter('delivery_id');
$points = $this->getUser()->getAttribute('delivery_point', array(), 'soteshop/stPaczkomatyPlugin');
$points[$delivery_id] = $this->getRequestParameter('point');
$this->getUser()->setAttribute('delivery_point', $points, 'soteshop/stPaczkomatyPlugin');
return sfView::HEADER_ONLY;
}
public function executeShowMap() {
$this->smarty = new stSmarty('stPaczkomatyFrontend');
$this->setLayout(false);
$this->config = stConfig::getInstance('stPaczkomatyBackend');
$this->cities = stPaczkomatyCites::getListofCities();
$delivery = DeliveryPeer::retrieveByPK($this->getRequestParameter('deliveryId'));
if (is_object($delivery))
$this->machinesNamespace = $delivery->getPaczkomatyType();
}
public function executeGetMachines() {
$i18n = $this->getContext()->getI18n();
if ($this->getRequestParameter('machinesNamespace', 'ALL') == 'COD') {
$data = stPaczkomatyMachines::getListOfCodMachines();
} else {
$data = stPaczkomatyMachines::getListOfMachines();
}
return $this->renderJSON($data);
}
public function executeGetMachine() {
return $this->renderJSON(stPaczkomatyMachines::getMachine($this->getRequestParameter('number')));
}
public function executeGetMachineByPostCode() {
return $this->renderJSON(stPaczkomatyMachines::getMachineByPostCode($this->getRequestParameter('post_code')));
}
public function executeGetMachinesByPostCode()
{
return $this->renderJSON(stPaczkomatyMachines::getMachinesByPostCode($this->getRequestParameter('post_code'), $this->getRequestParameter('limit')));
}
public function executeGet3MachinesByPostCode() {
return $this->renderJSON(stPaczkomatyMachines::get3MachinesByPostCode($this->getRequestParameter('post_code')));
}
public function executeEasyPackShow()
{
$config = stConfig::getInstance('stPaczkomatyBackend');
$pickupPoint = stDeliveryTypePickupPoint::createFromJson($this->getRequestParameter('pickup_point'));
$smarty = new stSmarty('stPaczkomatyFrontend');
$smarty->assign('sandbox', $config->get('sandbox'));
$smarty->assign('delivery_id', $this->getRequestParameter('delivery_id'));
$smarty->assign('pickup_point_name', null !== $pickupPoint ? $pickupPoint->getName() : null);
if (!$config->get('sandbox'))
{
$smarty->assign('api_endpoint', 'https://api-pl-points.easypack24.net/v1');
}
else
{
$smarty->assign('api_endpoint', 'https://stage-api-pl-points.easypack24.net/v1');
}
sfConfig::set('sf_web_debug', false);
return $this->renderText($smarty->fetch('easy_pack_show.html'));
}
}

View File

@@ -0,0 +1,50 @@
<?php
class stPaczkomatyFrontendComponents extends sfComponents {
public function executeBasketTerms() {
if(stPaczkomaty::isActive() == false)
return sfView::NONE;
$this->smarty = new stSmarty('stPaczkomatyFrontend');
$this->number = htmlspecialchars($this->getRequestParameter('user_data_billing[paczkomaty_machine_number]'));
}
public function executeDeliveryOnBasketList() {
if(stPaczkomaty::isActive() == false || !$this->delivery->getPaczkomatyType() || $this->delivery->getPaczkomatyType() == 'NONE')
return sfView::NONE;
$this->smarty = new stSmarty('stPaczkomatyFrontend');
$point = json_decode($this->getRequestParameter('user_data_billing[paczkomaty_machine_number]'), true);
$this->smarty->assign('point', $point);
$this->smarty->assign('id', $this->delivery->getId());
}
public function executeHelper()
{
if ($this->getModuleName() != 'stBasket')
{
return sfView::NONE;
}
$ids = [];
$smarty = new stSmarty('stPaczkomatyFrontend');
foreach (PaymentTypePeer::doSelectCached() as $payment)
{
if ($payment->getIsCod())
{
$ids[] = $payment->getId();
}
}
$smarty->assign('payments', json_encode($ids));
$smarty->assign('endpoint', stInPostApi::getInstance()->getEndpoint());
return $smarty;
}
}

View File

@@ -0,0 +1,3 @@
<?php
$smarty->assign('number', $number);
$smarty->display('paczkomaty_basket_terms.html');

View File

@@ -0,0 +1,2 @@
<?php
$smarty->display('paczkomaty_delivery_on_basket_list.html');

View File

@@ -0,0 +1 @@
<?php $smarty->display('easy_pack_show.html') ?>

View File

@@ -0,0 +1,11 @@
<?php
$smarty->assign('machinesNamespace', $machinesNamespace);
$messages = array(__('Wybierz Paczkomat'),
__('Zmień Paczkomat'),
__('Dostawa Paczkomaty'),
__('Proszę wybrać Paczkomat.'),
__('Paczkomat'),
);
$smarty->assign('messages', json_encode($messages));
$smarty->assign('configMapGroupPoints', $config->get('map_group_points'));
$smarty->display('paczkomaty_show_map.html');

View File

@@ -0,0 +1,60 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{__ text="Wybierz paczkomat"}</title>
<link rel="stylesheet" type="text/css" href="https://geowidget.easypack24.net/css/easypack.css?v2">
<script async src="https://geowidget.easypack24.net/js/sdk-for-javascript.js?v2"></script>
<script src="/js/jquery-1.8.3.min.js"></script>
</head>
<body style="position: absolute; height: 100%; width: 100%; padding: 0; margin: 0;">
<div id="easypack-map" style="position: absolute; width: 100%; height: 100%;"></div>
{literal}
<script type="text/javascript">
window.easyPackAsyncInit = function () {
var googleKey = "{/literal}{$google_api_key}{literal}";
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
function init(position) {
var point = getUrlParameter('point');
easyPack.init({
defaultLocale: 'pl',
points: {
types: ['parcel_locker']
},
map: {
useGeolocation: position ? true : false,
defaultLocation: position ? [position.coords.latitude, position.coords.longitude] : [51.9194, 19.1451],
initialZoom: position || point ? 13 : 6,
}
});
var map = easyPack.mapWidget('easypack-map', function(point) {
window.parent.jQuery(window.parent.document).trigger('paczkomaty.updatePoint', point);
window.parent.jQuery('#paczkomaty_overlay').data('overlay').close();
}, function(map) {
if (point) {
map.searchLockerPoint(point);
}
});
}
if (window.location.protocol === 'https:' && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(init, function() { init(); });
} else {
init();
}
};
</script>
{/literal}
</body>
</html>

View File

@@ -0,0 +1,173 @@
<div id="st_paczkomaty">
<div id="paczkomaty_overlay">
<div class="paczkomaty_overlay_content"></div>
</div>
</div>
{literal}
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
{/literal}
var url = "{urlfor internal='@stPaczkomatyPlugin?action=easyPackShow'}";
var is_authenticated = {$sf_user->isAuthenticated()|string_format:"%d"};
var shopping_cart_delivery = $('#st_basket-delivery');
var current = shopping_cart_delivery.find('input[type="radio"]:checked');
var selected = current.parent().find('.inpost-easypack-trigger').length > 0;
var payments = {$payments};
{literal}
$(document).on("delivery.change.started", function() {
current = $(this);
selected = $(this).parent().find('.inpost-easypack-trigger').length > 0;
update();
});
var i18n = {
{/literal}
choose_delivery_point: '{__ text="Wybierz punkt odbioru"}',
change_delivey_point: '{__ text="Wybrany punkt nie obsługuje płatności przy odbiorze.<br>Zmień płatność lub wybierz inny punkt odbioru."}',
{literal}
}
$('#paczkomaty_overlay').overlay({
oneInstance: false,
onLoad: function() {
var point = current.parent().find('.inpost-easypack').data('inpost-point');
if (point) {
var src = url.indexOf('?') > -1 ? url+'&point='+point : url+'?point='+point;
} else {
var src = url;
}
var wrap = this.getOverlay().find('.paczkomaty_overlay_content');
wrap.html('<iframe src="'+src+'" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; border: none" allowfullscreen></iframe>');
},
onClose: function () {
var wrap = this.getOverlay().find('.paczkomaty_overlay_content');
wrap.html('');
},
load: false
});
var modal = $('#paczkomaty_overlay').data('overlay');
$.fn.paczkomatyEqualHeight = function() {
tallest = 0;
this.each(function() {
$(this).css("height","auto");
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
this.height(tallest);
}
function updateHeight() {
$(".frame").paczkomatyEqualHeight();
$(".data_frame").paczkomatyEqualHeight();
}
function showMessage(message) {
window.alert(message);
}
function update() {
var different_delivery = $('#different_delivery');
shopping_cart_delivery.find('.inpost-easypack-address').hide();
if (selected) {
current.parent().find('.inpost-easypack-address').show();
$('#paczkomaty_machine_number').prop('disabled', false);
updateHeight();
if (different_delivery.prop('checked')) {
different_delivery.get(0).click();
}
different_delivery.prop('disabled', true);
if (is_authenticated) {
$('#order_form_delivery').hide();
$('#order_form_billing').parent().addClass('col-sm-push-6');
}
} else {
different_delivery.prop('disabled', false);
$('#paczkomaty_machine_number').prop('disabled', true);
updateHeight();
if (is_authenticated) {
$('#order_form_delivery').show();
$('#order_form_billing').parent().removeClass('col-sm-push-6');
}
}
}
function validateDeliveryPoint() {
if (selected) {
var payment_id = $('#st_basket-payment input[type=radio]:checked').val();
if (current.parent().find('.inpost-easypack-address').is(':empty')) {
showMessage(i18n.choose_delivery_point);
return false;
}
var cod = current.parent().find('.inpost-easypack').data('inpost-cod');
if (!cod && (payments.indexOf(payment_id) > -1 || payments.indexOf(Number(payment_id)) > -1)) {
showMessage(i18n.change_delivey_point);
return false;
}
}
return true;
}
function addressFormat(point) {
var address = [];
var ad = point.address_details;
address.push('<b>'+point.name+'</b>');
address.push(ad.street+' '+ad.building_number+(ad.flat_number ? '/'+ad.flat_number : ''));
address.push(ad.post_code+' '+ad.city);
return address.join('<br>');
}
update();
$('#user_delivery_form').submit(validateDeliveryPoint);
$(document).on('delivery.change.started', function(e, delivery) {
current = $(delivery);
selected = current.parent().find('.inpost-easypack-trigger').length > 0;
update();
});
$(document).on('paczkomaty.updatePoint', function(event, point) {
var address = addressFormat(point);
var cod = point.name.indexOf('POP-') === -1;
current.get(0).click();
current.parent().find('.inpost-easypack-address').html(addressFormat(point));
current.parent().find('.inpost-easypack').data('inpost-point', point.name).data('inpost-cod', cod);
$('#paczkomaty_machine_number').val(JSON.stringify({ name: point.name, address: point.address_details, "cod": cod }));
updateHeight();
});
shopping_cart_delivery.on('click', '.inpost-easypack-trigger', function() {
current = $(this).closest('li').find('input[type="radio"]');
modal.load();
});
});
});
</script>
{/literal}

View File

@@ -0,0 +1 @@
<input type="hidden" id="paczkomaty_machine_number" name="user_data_billing[paczkomaty_machine_number]" value="{$number}"/>

View File

@@ -0,0 +1,14 @@
{use_stylesheet src="stPaczkomatyPlugin.css"}
<div data-delivery-id="{$id}" class="inpost-easypack"{if $point} data-inpost-point="{$point.name}" data-inpost-cod="{$point.cod}"{/if}>
<a href="#" class="inpost-easypack-trigger">{__ text="Wybierz Paczkomat"}</a>
{if $point}
<div class="inpost-easypack-address">
<b>{$point.name}</b><br>
{$point.address.street} {$point.address.building_number}{if $point.address.flat_number} / {$point.address.flat_number}{/if}<br>
{$point.address.post_code} {$point.address.city}
</div>
{else}
<div class="inpost-easypack-address" style="display: none;"></div>
{/if}
</div>

View File

@@ -0,0 +1,62 @@
<div id="st_paczkomaty">
<div id="paczkomaty_overlay">
<div class="paczkomaty_overlay_content"></div>
</div>
</div>
{literal}
<script type="text/javascript" src="{/literal}{$mapJsUrl}{literal}"></script>
<script type="text/javascript" language="javascript">
jQuery(function ($) {
var messages = {/literal}{$messages}{literal}
$(document).ready(function() {
{/literal}
{if $number != ''}
$.paczkomatySelectMachine('{$number}', messages);
{/if}
{literal}
$('.st_delivery-default').click(function() {
$.paczkomatyRestoreBasket(messages);
});
$('.st_delivery-label').click(function() {
$.paczkomatyRestoreBasket(messages);
});
$('#user_delivery_form').submit(function() {
var deliveryIdChecked = $('input.st_delivery-default:checked').val();
if($('#st_paczkomaty_delivery-' + deliveryIdChecked).length && !$('#st_paczkomaty_delivery_address-' + deliveryIdChecked).is(':visible')) {
alert(messages[3]);
return false;
}
});
$('#st_basket-delivery').on('click', '.paczkomaty_active_overlay', function() {
$.paczkomatyRestoreBasket(messages);
var deliveryId = $(this).data('delivery-id');
$("#delivery_default_delivery-" + deliveryId).prop('checked', true);
$("#delivery_default_delivery-" + deliveryId).trigger('click');
$('#paczkomaty_overlay').data('overlay', '');
$('#paczkomaty_overlay').overlay({
oneInstance: false,
onBeforeLoad: function() {
var wrap = this.getOverlay().find('.paczkomaty_overlay_content');
$.get('{/literal}{$mapUrl}{literal}/' + deliveryId, function(data) {
wrap.html(data);
});
},
onClose: function () {
var wrap = this.getOverlay().find('.paczkomaty_overlay_content');
wrap.html('');
},
load: true
});
});
});
});
</script>
{/literal}

View File

@@ -0,0 +1,238 @@
<div id="st_paczkomaty_map_content_loading">
<img src="/images/frontend/theme/default2/loading.gif" alt=""/>
</div>
<div id="st_paczkomaty_map_content">
<div id="st_paczkomaty_map_post_code">
<h3>{__ text="Podaj kod pocztowy"}</h3>
<div class="clear"></div>
<div id="st_paczkomaty_map_post_code_error">
<img src="{image_path image='exclamation.png'}" title="{__ text="Podany kod pocztowy jest nieprawidłowy."}" alt="{__ text="Podany kod pocztowy jest nieprawidłowy."}">
</div>
<input id="st_paczkomaty_map_post_code_input" name="st_paczkomaty_map_post_code_input" type="text" placeholder="__-___">
<input id="st_paczkomaty_map_post_code_button" type="button" value="{__ text="Szukaj"}">
</div>
<div id="st_paczkomaty_map_cities_box">
<h3>{__ text="Wybierz miasto"}</h3>
<div class="clear"></div>
<select id="st_paczkomaty_map_cities_list">
<option value="NONE">-- {__ text="wszystkie lokalizacje"} --</option>
</select>
</div>
<div id="st_paczkomaty_map_list_box">
<h3>{__ text="Wybierz Paczkomat"}</h3>
<div class="clear"></div>
<div id="st_paczkomaty_map_machines_list_div">
<ul id="st_paczkomaty_map_machines_list">
</ul>
</div>
</div>
</div>
<div id="map_canvas" style="height: 95%; position: absolute; right: 1%; top: 3%; width: 69%;"/>
{literal}
<script type="text/javascript" language="javascript">
function selectMachine(number) {
jQuery(function ($) {
if ($('#paczkomaty_overlay').data('overlay'))
$('#paczkomaty_overlay').data('overlay').close();
var messages = {/literal}{$messages}{literal}
$.paczkomatySelectMachine(number, messages);
});
};
jQuery(function ($) {
function createMachine(marker) {
return '<li class="st_paczkomaty_map_machines_list_element" ' +
' data-maps-city="' + marker.city +
'" data-maps-machine-name="' + marker.number +
'" data-maps-latitude="' + marker.latitude +
'" data-maps-longitude="' + marker.longitude + '">' +
'<b>' + marker.number + '</b>, ' + marker.street + ' ' + marker.house + ',<br />' +
marker.postCode + ' ' + marker.city +
'</li>';
}
$(document).ready(function () {
var messages = {/literal}{$messages}{literal}
var allMarkers = [];
var allMachines = [];
var machinesNames = {};
$('#st_paczkomaty_map_post_code_input').mask('00-000');
$("#st_paczkomaty_map_content_loading img").css('margin-top', $("#st_paczkomaty_map_content").height()/2);
var machines_list = $('#st_paczkomaty_map_machines_list');
$.getJSON('/paczkomaty/getMachines/machinesNamespace/{/literal}{$machinesNamespace}{literal}', function(data) {
$('#map_canvas').gmap({'center': "52,20"}).bind('init', function(ev, map) {
$('#map_canvas').gmap('option', 'zoom', 6);
var cities = [];
var results = '';
$.each(data, function(i, marker) {
if (marker.city == 'Bielsko Biała') {
marker.city = 'Bielsko-Biała';
} else if (marker.city == 'Bialystok') {
marker.city = 'Białystok';
}
if ($.inArray(marker.city, cities) === -1) {
$('#st_paczkomaty_map_cities_list').append($('<option>', {
value: marker.city,
text: marker.city
}));
cities.push(marker.city);
}
results += createMachine(marker);
allMachines[i] = marker;
machinesNames[marker.number] = i;
m = $('#map_canvas').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'icon': '/images/frontend/theme/default2/stPaczkomatyPlugin/marker-' + marker.cod + '.png',
'bounds': true
});
allMarkers[i] = m;
m.click(function() {
var content = "<div id=\"st_paczkomaty_map_machine\">" +
" <p id=\"st_paczkomaty_map_machine_name\">" + messages[4] + " " + marker.number + "</p>" +
" <div id=\"st_paczkomaty_map_machine_address\">" +
" " + marker.street + ' ' + marker.house + "<br />" +
" " + marker.postCode + ' ' + marker.city + "<br />" +
" </div>" +
" <div id=\"st_paczkomaty_map_machine_button\" class=\"buttons\">" +
" <a href=\"#st_basket-delivery\" onClick=\"selectMachine('" + marker.number + "');\" class=\"buttons\">" + messages[0] + "</a>" +
" </div>" +
"</div>";
$('#map_canvas').gmap('openInfoWindow', { 'content': content }, this);
});
});
machines_list.html(results);
{/literal}{if $configMapGroupPoints}{literal}
var clusterStyles = [{
url: '/images/frontend/theme/default2/stPaczkomatyPlugin/markerClusterer.png',
height: 36,
width: 26,
anchorText: [12, 0]
}, {
url: '/images/frontend/theme/default2/stPaczkomatyPlugin/markerClusterer.png',
height: 36,
width: 26,
anchorText: [12, 0]
}, {
url: '/images/frontend/theme/default2/stPaczkomatyPlugin/markerClusterer.png',
height: 36,
width: 26,
anchorText: [12, 0]
}
];
var mcOptions = {
gridSize: 50,
styles: clusterStyles,
};
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map, $(this).gmap('get', 'markers'), mcOptions));
{/literal}{/if}{literal}
$('#st_paczkomaty_map_content').show();
$('#st_paczkomaty_map_content_loading').hide();
machines = $('#st_paczkomaty_map_machines_list_div li');
});
});
$('#st_paczkomaty_map_cities_list').change(function() {
var selected= $(this).val();
$('#st_paczkomaty_map_post_code_input').val('');
var results = '';
if (selected == 'NONE') {
$('#map_canvas').gmap('get', 'map').setCenter({lat: 52.12, lng: 18.9});
$('#map_canvas').gmap('option', 'zoom', 6);
$.each(allMachines, function() {
if (this.number) {
results += createMachine(this);
}
});
} else {
$.each(allMachines, function() {
if (this.city == selected) {
results += createMachine(this);
}
});
$('#map_canvas').gmap('search', { 'address': selected}, function(results, status) {
if ( status === 'OK' ) {
$('#map_canvas').gmap('get', 'map').panTo(results[0].geometry.location);
$('#map_canvas').gmap('option', 'zoom', 11);
}
});
}
machines_list.html(results);
});
$("#st_paczkomaty_map_post_code_error img[title]").tooltip({
effect: 'slide',
opacity: 1,
position: 'bottom right',
offset: [15,4],
tipClass: 'alert_tooltip'
});
function setMapToPostCode() {
var postCode = $('#st_paczkomaty_map_post_code_input').val();
$('#st_paczkomaty_map_content').hide();
$('#st_paczkomaty_map_content_loading').show();
$('#st_paczkomaty_map_cities_list').val("NONE");
$.getJSON('/paczkomaty/getMachineByPostCode/' + postCode, function(machine) {
if (machine.name) {
$('#map_canvas').gmap('get', 'map').panTo(new google.maps.LatLng(machine.latitude, machine.longitude));
$('#map_canvas').gmap('option', 'zoom', 13);
$("#st_paczkomaty_map_post_code_error").css('display', 'none');
$.getJSON('/paczkomaty/getMachinesByPostCode/' + machine.postcode + '/10', function(data) {
var results = '';
$.each(data, function() {
var index = machinesNames[this.name];
results += createMachine(allMachines[index]);
});
machines_list.html(results);
$('#st_paczkomaty_map_content').show();
$('#st_paczkomaty_map_content_loading').hide();
});
} else {
$("#st_paczkomaty_map_post_code_error").css('display', 'inline');
$('#st_paczkomaty_map_content').show();
$('#st_paczkomaty_map_content_loading').hide();
}
});
}
$('#st_paczkomaty_map_post_code_button').click(function() {
setMapToPostCode();
});
$('#st_paczkomaty_map_post_code_input').keypress(function(e) {
if (e.which == 13)
setMapToPostCode();
});
machines_list.on("click", ".st_paczkomaty_map_machines_list_element", function(event){
$('#map_canvas').gmap('get', 'map').panTo(new google.maps.LatLng($(this).data('maps-latitude'), $(this).data('maps-longitude')));
$('#map_canvas').gmap('option', 'zoom', 13);
var index = machinesNames[$(this).data('maps-machine-name')];
allMarkers[index].triggerEvent('click');
});
});
});
</script>
{/literal}

View File

@@ -0,0 +1 @@
<iframe src="{pickup_point_url internal_url='@stPaczkomatyPlugin?action=easyPackShow'}" style="width: 100%; height: 500px; top: 0; left: 0; border: none" allowfullscreen></iframe>

View File

@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{__ text="Wybierz paczkomat"}</title>
<link rel="stylesheet" type="text/css" href="https://geowidget.easypack24.net/css/easypack.css?v3">
<script async src="https://geowidget.easypack24.net/js/sdk-for-javascript.js?v3"></script>
<script src="/js/jquery-1.8.3.min.js"></script>
</head>
<body style="position: absolute; height: 100%; width: 100%; padding: 0; margin: 0;">
<div id="easypack-map" style="position: absolute; width: 100%; height: 100%; padding-top: 56px"></div>
<script type="text/javascript">
const apiEndpoint = "{$api_endpoint}";
const pointName = "{$pickup_point_name}";
{literal}
window.easyPackAsyncInit = function () {
easyPack.init({
defaultLocale: 'pl',
apiEndpoint: apiEndpoint,
points: {
types: ['parcel_locker']
},
map: {
useGeolocation: true,
initialZoom: 13,
}
});
const map = easyPack.mapWidget('easypack-map', function(point) {
let address = point.address_details.street;
if (point.address_details.building_number) {
address += ' ' + point.address_details.building_number;
}
if (point.address_details.flat_number) {
address += '/' + point.address_details.flat_number;
}
window.parent.jQuery.deliveryModal.showPreloader();
$.get(apiEndpoint + '/points/' + point.name, function(response) {
window.parent.jQuery.delivery.updatePickupPoint(response.name, response.name, address, response.address_details.post_code, response.address_details.city, 'PL', response.payment_available, response.location_247);
});
}, function(map) {
if (pointName) {
map.searchLockerPoint(pointName);
}
}
);
}
{/literal}
</script>
</body>
</html>

View File

@@ -0,0 +1,236 @@
<div class="modal fade" id="inpost-easypack" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document" style="width: 1150px; height: 98%; max-width: 98%; margin: 0.5% auto 0 auto; padding: 0">
<div class="modal-content" style="width: 100%; height: 100%; padding: 0">
<div class="modal-header text-left" style="position: relative; z-index: 1">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Wybierz paczkomat</h4>
</div>
<div class="modal-body" style="position: absolute; width: 100%; padding: 0; top: 0; height: 100%; margin: 0"></div>
</div>
</div>
</div>
<div class="modal fade modal-vertical-centered" id="inpost-message-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header text-left">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">{__ text="InPost - Paczkomaty"}</h4>
</div>
<div class="modal-body text-center"></div>
<div class="modal-footer">
<div class="text-center">
<button type="button" class="btn btn-default" data-dismiss="modal">{__ text="Zamknij"}</button>
</div>
</div>
</div>
</div>
</div>
{literal}
<script type="text/javascript">
jQuery(function ($) {
{
/literal}
var url = "{urlfor internal='@stPaczkomatyPlugin?action=easyPackShow'}";
var is_authenticated = { $sf_user-> isAuthenticated() | string_format:"%d"
};
var shopping_cart_delivery = $('#shopping-cart-delivery');
var current = shopping_cart_delivery.find('.delivery-radio:checked');
var selected = current.parent().find('.inpost-easypack-trigger').length > 0;
var payments = { $payments };
var apiEndpoint = "{$endpoint}";
{ literal }
var i18n = {
{
/literal}
choose_delivery_point: '{__ text="Wybierz punkt odbioru."}',
change_delivey_point: '{__ text="Wybrany punkt nie obsługuje płatności przy odbiorze.<br>Zmień płatność lub wybierz inny punkt odbioru."}',
delivery_point_does_not_exist: '{__ text="Wybrany punkt został wyłączony lub nie istnieje."}'
{ literal }
}
function showMessage(message) {
var modal = $('#inpost-message-modal');
modal.find('.modal-body').html(message);
modal.modal('show');
}
function setParameter(name, value) {
var storage = window.localStorage;
storage.setItem(name, typeof value === 'object' ? JSON.stringify(value) : value);
}
function getParameter(name, defaultValue = null) {
var storage = window.localStorage;
var value = storage.getItem(name);
try {
return JSON.parse(value);
} catch (e) { }
return value ? value : defaultValue;
}
function pointUpdate() {
var point = getParameter('inpost_pickup_point');
if (point) {
$(document).trigger('paczkomaty.updatePoint', point, false);
}
}
function update() {
var different_delivery = $('#different_delivery');
if (selected) {
shopping_cart_delivery.data('delivery-type', 'inpost-paczkomaty');
shopping_cart_delivery.attr('data-delivery-type', 'inpost-paczkomaty');
}
var update = shopping_cart_delivery.data('delivery-type') == 'inpost-paczkomaty';
if (selected) {
current.parent().find('.inpost-easypack-address').show();
$('#paczkomaty_machine_number').prop('disabled', false);
$(window).trigger('resize');
if (update) {
if (different_delivery.prop('checked')) {
different_delivery.get(0).click();
}
different_delivery.prop('disabled', true);
if (is_authenticated) {
$('#order_form_delivery').hide();
$('#order_form_billing').parent().addClass('col-sm-push-6');
}
}
} else {
shopping_cart_delivery.find('.inpost-easypack-address').hide();
$('#paczkomaty_machine_number').prop('disabled', true);
$(window).trigger('resize');
if (update) {
different_delivery.prop('disabled', false);
if (is_authenticated) {
$('#order_form_delivery').show();
$('#order_form_billing').parent().removeClass('col-sm-push-6');
}
}
}
}
function validateDeliveryPoint() {
if (selected) {
const point = getParameter('inpost_pickup_point');
let payment_id = $('#shopping-cart-payment .radio input[type=radio]:checked').val();
if (!point) {
showMessage(i18n.choose_delivery_point);
return false;
}
if (point.status != 'Operating') {
showMessage(i18n.delivery_point_does_not_exist);
return false;
}
if (!point.payment_available && (payments.indexOf(payment_id) > -1 || payments.indexOf(Number(payment_id)) > -1)) {
showMessage(i18n.change_delivey_point);
return false;
}
}
return true;
}
function addressFormat(point) {
var address = [];
var ad = point.address_details;
address.push('<b>' + point.name + '</b>');
address.push(ad.street + ' ' + ad.building_number + (ad.flat_number ? '/' + ad.flat_number : ''));
address.push(ad.post_code + ' ' + ad.city);
return address.join('<br>');
}
$('#user_delivery_form').submit(validateDeliveryPoint);
shopping_cart_delivery.on('change', '.delivery-radio', function () {
current = $(this);
selected = $(this).parent().find('.inpost-easypack-trigger').length > 0;
pointUpdate();
update();
});
$(document).on('paczkomaty.ajaxUpdate', function () {
current = shopping_cart_delivery.find('.delivery-radio:checked');
selected = current.parent().find('.inpost-easypack-trigger').length > 0;
pointUpdate();
update();
});
$(document).on('paczkomaty.updatePoint', function (event, point, withClick = true) {
var address = addressFormat(point);
$(document).trigger('delivery.update.started');
$.get(apiEndpoint + '/points/' + point.name, function (response) {
point.payment_available = response.payment_available;
if (selected || !withClick) {
$(document).trigger('delivery.update.finished');
} else {
current.click();
}
if (response.status != '404') {
point = response;
} else {
point.status = response.status;
}
current.parent().find('.inpost-easypack-address').html(addressFormat(point));
current.parent().find('.inpost-easypack').data('inpost-point', point.name).data('inpost-cod', point.payment_available);
$('#paczkomaty_machine_number').val(JSON.stringify({ name: point.name, address: point.address_details, "cod": point.payment_available }));
setParameter('inpost_pickup_point', point);
$(window).trigger('resize');
});
});
shopping_cart_delivery.on('click', '.inpost-easypack-trigger', function () {
current = $(this).closest('.radio').find('.delivery-radio');
$('#inpost-easypack').modal('show');
});
$('#inpost-easypack').on('show.bs.modal', function (event) {
var point = current.parent().find('.inpost-easypack').data('inpost-point');
if (point) {
var src = url.indexOf('?') > -1 ? url + '&point=' + point : url + '?point=' + point;
} else {
var src = url;
}
$(this).find('.modal-body').find('iframe').remove();
$(this).find('.modal-body').html('<iframe src="' + src + '" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; border: none" allowfullscreen></iframe>');
});
update();
if (selected) {
pointUpdate();
}
});
</script>
{/literal}

View File

@@ -0,0 +1 @@
<input type="hidden" id="paczkomaty_machine_number" name="user_data_billing[paczkomaty_machine_number]" value="{$number}"/>

View File

@@ -0,0 +1,4 @@
<div data-delivery-id="{$id}" class="inpost-easypack">
<a href="#" class="btn btn-default inpost-easypack-trigger">{__ text="Wybierz Paczkomat"}</a>
<div class="inpost-easypack-address" style="display: none;"></div>
</div>