first commit

This commit is contained in:
2026-04-28 15:13:50 +02:00
commit a95acc355b
63745 changed files with 9487948 additions and 0 deletions

View File

@@ -0,0 +1,592 @@
<?php
/**
* @deprecated since 1.5.0 use \Polkurier\ApiClient
* Class PolkurierAPI
*/
class PolkurierAPI extends \Polkurier\ApiClient
{
/**
* @param $method
* @param array $params
* @return array|bool|mixed
*/
protected function call($method, $params = array())
{
try {
return parent::call($method, $params);
} catch (\Polkurier\Exception\ApiException $ex) {
Polkurier_Admin::api_error_notice($ex->getMessage());
$this->lastError = $ex->getMessage();
return false;
}
}
}
class PolkurierModel implements ArrayAccess, JsonSerializable
{
public $params = [];
/**
* @return array
*/
public function toArray()
{
$data = array();
foreach ($this->params as $field => $value) {
if (is_array($value) || is_object($value)) {
$data[$field] = json_encode($value);
} else {
$data[$field] = $value;
}
}
return $data;
}
/**
* @param $params
* @return $this
*/
public function fromArray($params)
{
foreach ($params as $key => $val) {
$this->__set($key, $val);
}
return $this;
}
/**
* @return int
*/
public function getId()
{
return (int)$this->id;
}
/**
* @param $name
* @param $value
*/
public function __set($name, $value)
{
if (array_key_exists($name, $this->params)) {
$this->params[$name] = $value;
} else {
$this->params['extra'][$name] = $value;
}
}
/**
* @param $name
* @return mixed|null
*/
public function __get($name)
{
if (array_key_exists($name, $this->params)) {
return $this->params[$name];
} else if (array_key_exists($name, $this->params['extra'])) {
return $this->params['extra'][$name];
}
return null;
}
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return array_key_exists($offset, $this->params) || array_key_exists($offset, $this->params['extra']);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return $this->__get($offset);
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
return $this->__set($offset, $value);
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
}
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->toArray();
}
}
class PolkurierAddress implements JsonSerializable
{
public $id;
public $address = [
"company" => null,
"person" => null,
"street" => null,
"housenumber" => null,
"flatnumber" => null,
"postcode" => null,
"city" => null,
"country" => null,
"email" => null,
"phone" => null,
"account_id" => null,
"machine_name" => null,
"point_name" => null,
];
public function __toString()
{
$msg = "";
$msg .= $this->address["company"] . "<br/>";
$msg .= $this->address["person"] . "<br/>";
$msg .= $this->address["street"] . " " . $this->address["housenumber"] . " " . $this->address["flatnumber"] . "<br/>";
$msg .= $this->address["postcode"] . " " . $this->address["city"] . " " . $this->address['country'] . "<br/>";
$msg .= $this->address["phone"] . " " . $this->address["email"];
if (!empty($this->address['point_name'])) {
$msg .= 'Punkt: ' . $this->address["point_name"];
}
$msg .= "";
return $msg;
}
public function asTableRow(array $excludedRows = [])
{
$row = '';
if (!in_array('company', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["company"]);
}
if (!in_array('person', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["person"]);
}
if (!in_array('address', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["street"] . " " . $this->address["housenumber"] . " " . $this->address["flatnumber"]);
}
if (!in_array('location', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["postcode"] . " " . $this->address["city"] . " " . $this->address["country"]);
}
if (!in_array('phone', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["phone"]);
}
if (!in_array('email', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["email"]);
}
if (!in_array('account_id', $excludedRows)) {
$row .= sprintf("<td>%s</td>", $this->address["account_id"]);
}
return $row;
}
public function toArray()
{
$data = $this->address;
$data['id'] = $this->id;
return $data;
}
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->toArray();
}
public function fromArray($array)
{
$this->id = (int)$array['id'];
foreach ($array as $key => $val) {
if (array_key_exists($key, $this->address)) {
$this->address[$key] = $val;
}
}
}
public static function getAddressById($id)
{
$opt = get_option('polkurier_addresses');
$opt[$id]->id = $id;
return $opt[$id];
}
public static function getCoverAddressById($id)
{
$opt = get_option('polkurier_cover_addresses');
if ($opt[$id] !== null) {
$opt[$id]->id = $id;
return $opt[$id];
}
return null;
}
public function renderForm()
{
if ($this->id || $this->id == 0) {
echo '<input type="hidden" name="polkurier_id" value="' . $this->id . '"/>';
}
?>
<table class="form-table">
<tbody>
<tr>
<th scope="row">
<label for="polkurier_company_name">Nazwa firmy</label></th>
<td><input required type="text" name="polkurier_company_name" id="polkurier_company_name"
value="<?php echo $this->address['company'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_name_surname_cb">Imię&nbsp;i nazwisko</label></th>
<td><input required type="text" name="polkurier_name_surname" id="polkurier_name_surname"
value="<?php echo $this->address['person'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_street_cb">Ulica</label></th>
<td><input required type="text" name="polkurier_street" id="polkurier_street"
value="<?php echo $this->address['street'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_number_1_cb">Numer budynku</label></th>
<td><input required type="text" name="polkurier_number_1" id="polkurier_number_1"
value="<?php echo $this->address['housenumber'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_number_2_cb">Numer lokalu</label></th>
<td><input type="text" name="polkurier_number_2" id="polkurier_number_2"
value="<?php echo $this->address['flatnumber'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_postal_code_cb">Kod pocztowy</label></th>
<td><input required type="text" pattern="[0-9]{2}-[0-9]{3}" title="Kod pocztowy musi być w formie xx-xxx"
name="polkurier_postal_code" id="polkurier_postal_code"
value="<?php echo $this->address['postcode'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_city_cb">Miasto</label></th>
<td><input required type="text" name="polkurier_city" id="polkurier_city"
value="<?php echo $this->address['city'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_phone_cb">Numer telefonu</label></th>
<td><input required type="text" pattern="[0-9]{9}" title="Podaj dziewięciocyfrowy numer telefonu"
name="polkurier_phone" id="polkurier_phone" value="<?php echo $this->address['phone'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_email_cb">Adres e-mail</label></th>
<td><input required type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
title="Podaj poprawny adres e-mail" name="polkurier_email" id="polkurier_email"
value="<?php echo $this->address['email'] ?>"></td>
</tr>
<tr>
<th scope="row"><label for="polkurier_polkurier_account_id_cb">ID konta Polkurier</label></th>
<td><input type="text" name="polkurier_polkurier_account_id" id="polkurier_polkurier_account_id"
value="<?php echo $this->address['account_id'] ?>"> <br/><em>Opcja dostępna dla klientów
nadających przesyłki za pośrednictwem przewoźnika Geis oraz posiadających aktywną opcje stałych
odbiorów. ID konta należy pozyskać kontaktując się z biurem obsługi klienta serwisu
polkurier.pl.</em></td>
</tr>
</tbody></table><?php
}
}
class PolkurierBankAccount
{
public $account = null;
public $alias = null;
public function __toString()
{
return (string)$this->account;
}
public function asTableRow()
{
return sprintf("<td>%s</td><td>%s</td>",
$this->alias,
$this->account
);
}
}
class PolkurierOrder extends PolkurierModel
{
public $params = [
'id' => null,
'wp_order_id' => null,
"order_number" => '',
"label" => null,
"price_gross" => 0,
"price_net" => 0,
"carrier" => '',
"address" => null,
"address_to" => null,
"pobranie" => 0,
'status_code' => '',
"extra" => [],
'date_created' => null,
];
/**
* @param $response
* @param $carrier
* @param $address
* @param $address_to
* @param $pobranie
* @param $extra
* @return PolkurierOrder
*/
public static function createFromApiResponse($response, $carrier, $address, $address_to, $pobranie, $extra)
{
$order = new PolkurierOrder();
$order->order_number = (string)$response['order_number'];
$order->label = (array)$response['label'];
$order->price_gross = (float)$response['price_gross'];
$order->price_net = (float)$response['price_net'];
$order->carrier = (string)$carrier;
$order->address = $address;
$order->address_to = $address_to;
$order->pobranie = (float)$pobranie;
$order->extra = (array)$extra;
$order->date_created = new DateTime();
return $order;
}
/**
* @return $this
*/
public function save()
{
global $wpdb;
if (!empty($this->getId())) {
$wpdb->update($wpdb->prefix . 'polkurier_orders', $this->toArray(), [
'id' => $this->getId()
]);
} else {
$this->wp_order_id = $wpdb->insert($wpdb->prefix . 'polkurier_orders', $this->toArray());
}
return $this;
}
/**
* @param $params
* @return $this
*/
public function fromArray($params)
{
$this->id = (int)$params['id'];
$this->wp_order_id = (int)$params['wp_order_id'];
$this->order_number = (string)$params['order_number'];
$this->label = json_decode($params['label'], true);
$this->price_gross = (float)$params['price_gross'];
$this->price_net = (float)$params['price_net'];
$this->carrier = $params['carrier'];
$this->address = new PolkurierAddress();
$this->address->fromArray(json_decode($params['address'], true));
$this->address_to = new PolkurierAddress();
$this->address_to->fromArray(json_decode($params['address_to'], true));
$this->pobranie = (float)$params['pobranie'];
$this->status_code = $params['status_code'];
$this->extra = json_decode($params['extra'], true);
$this->date_created = \Polkurier\Util\Dates::dateTimeOrNull($params['date_created']);
return $this;
}
public function toArray()
{
$data = parent::toArray();
$data['date_created'] = $this->date_created
? $this->date_created->format(\Polkurier\Util\Dates::MYSQL_DATETIME)
: date(\Polkurier\Util\Dates::MYSQL_DATETIME);
return $data;
}
/**
* @param $id
* @return PolkurierOrder|null
*/
public static function getOrderByWCOrderId($id)
{
return PolkurierOrder::getOrderBy('wp_order_id', (int)$id);
}
/**
* @param $id
* @return PolkurierOrder|null
*/
public static function getOrderById($id)
{
return PolkurierOrder::getOrderBy('id', (int)$id);
}
/**
* @param $orderNumber
* @return PolkurierOrder|null
*/
public static function getOrderByNumber($orderNumber)
{
return PolkurierOrder::getOrderBy('order_number', $orderNumber);
}
/**
* @param string $field
* @param string $value
* @return PolkurierOrder|null
*/
public static function getOrderBy($field, $value)
{
global $wpdb;
$data = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}polkurier_orders WHERE `$field` = %s", $value), ARRAY_A);
if (!empty($data)) {
$order = new PolkurierOrder();
$order->fromArray($data);
return $order;
}
return null;
}
/**
* @param $id
* @return bool
*/
public static function hasOrderDefined($id)
{
return self::getOrderByWCOrderId($id) !== null;
}
/**
* @param array $where
* @return string
*/
private static function createWhere(array $where)
{
$searchQuery = '';
if (isset($where['searchQuery'])) {
$searchQuery = trim($where['searchQuery']);
unset($where['searchQuery']);
}
$query = \Polkurier\Util\Database::createWhere($where);
if (!empty($searchQuery)) {
if (!empty($query)) {
$query = "($query) AND ";
}
$query .= \Polkurier\Util\Database::createSearchWhere($searchQuery, array(
'order_number',
'label',
'address',
'address_to',
));
}
return $query;
}
/**
* @param array $where
* @param string|array $order
* @param null $limit
* @param null $offset
* @return PolkurierOrder[]
*/
public static function getAll($where = array(), $order = null, $limit = null, $offset = null)
{
global $wpdb;
$data = [];
$query = "SELECT * FROM {$wpdb->prefix}polkurier_orders";
$whereString = self::createWhere($where);
if (!empty($whereString)) {
$query .= ' WHERE ' . $whereString;
}
if (!empty($order)) {
$col = is_array($order) ? $order[0] : $order;
$dir = strtoupper(is_array($order) ? $order[1] : 'ASC');
$dir = $dir === 'DESC' ? 'DESC' : 'ASC';
$query .= " ORDER BY `$col` $dir ";
}
$limit = (int)$limit;
$offset = (int)$offset;
if (!empty($limit)) {
$query .= ' LIMIT ' . $limit;
if (!empty($offset)) {
$query .= ' OFFSET ' . $offset;
}
}
foreach ($wpdb->get_results($query, ARRAY_A) as $row) {
$polkurierOrder = new PolkurierOrder();
$polkurierOrder->fromArray($row);
$data[] = $polkurierOrder;
}
return $data;
}
/**
* @param array $where
* @return int
*/
public static function countAll($where = array())
{
global $wpdb;
$query = "SELECT COUNT(*) as c FROM {$wpdb->prefix}polkurier_orders";
$whereString = self::createWhere($where);
if (!empty($whereString)) {
$query .= ' WHERE ' . $whereString;
}
$data = $wpdb->get_results($query, ARRAY_A);
return (int)$data[0]['c'];
}
/**
* @param $id
*/
public static function deleteByOrderNumber($orderNumber)
{
global $wpdb;
$wpdb->delete($wpdb->prefix . 'polkurier_orders', ['order_number' => $orderNumber]);
}
public function getDateCreated()
{
if (!($this->date_created instanceof DateTime)) {
$this->date_created = new DateTime('1970-01-01');
}
return $this->date_created;
}
}

View File

@@ -0,0 +1,92 @@
<?php
require_once plugin_dir_path(__FILE__) . 'PolkurierAPI.php';
/**
* Class Polkurier_OrderStatusUpdater
*/
class PolkurierOrderStatusUpdater
{
/**
* Co ile sekund sprawdzać status
* @var int
*/
private static $UPDATE_STATUS_INTERVAL = 1440; // 4H
/**
* Przez ile dni po utworzeniu zamówienia sprawdzać status
* @var int
*/
private static $UPDATE_STATUS_DAYS = 21;
/**
* @var \Polkurier\ApiClient
*/
private $api;
public function __construct()
{
$this->api = new \Polkurier\ApiClient(get_option('polkurier_account_id'), get_option('polkurier_apikey'));
}
/**
* @param PolkurierOrder $polkurierOrder
* @return bool
* @throws Exception
*/
public function shouldUpdateOrderStatus($polkurierOrder)
{
$lastStatusUpdateTime = (int)$polkurierOrder->lastStatusUpdateTime;
$dateTo = (clone $polkurierOrder->getDateCreated());
$dateTo->add(new DateInterval('P' . self::$UPDATE_STATUS_DAYS . 'D'));
return
!empty($polkurierOrder['order_number']) &&
$lastStatusUpdateTime + self::$UPDATE_STATUS_INTERVAL < time() &&
$dateTo >= new DateTime() &&
in_array((string)$polkurierOrder->status_code, array('', 'O', 'OC', 'P', 'WP', 'PZ', 'Z'))
;
}
/**
* @param PolkurierOrder $polkurierOrder
* @throws \Polkurier\Exception\ApiException
*/
public function updateOrderStatus($polkurierOrder)
{
if (!empty($polkurierOrder['order_number'])) {
try {
$polkurierStatus = $this->api->getStatus($polkurierOrder['order_number']);
if (!empty($polkurierStatus)) {
$polkurierOrder->status = $polkurierStatus['status'];
$polkurierOrder->status_code = $polkurierStatus['status_code'];
$polkurierOrder->status_date = isset($polkurierStatus['status_date']) ? $polkurierStatus['status_date'] : null;
$polkurierOrder->delivered_date = $polkurierOrder->params['status_code'] === 'D' ? $polkurierStatus['delivered_date'] : '';
$polkurierOrder->lastStatusUpdateSuccess = true;
} else {
$polkurierOrder->lastStatusUpdateSuccess = false;
}
$polkurierOrder->lastStatusUpdateTime = time();
$polkurierOrder->save();
} catch (Exception $e) {
}
}
}
/**
* Aktualizuje wszystkie statusy
*/
public function updateAllOrdersStatuses()
{
$orders = PolkurierOrder::getAll(["status_code IN ('', 'O', 'OC', 'P', 'WP', 'PZ', 'Z')" => null]);
foreach ($orders as $order) {
$this->updateOrderStatus($order);
}
}
}

View File

@@ -0,0 +1,109 @@
<?php
class PolkurierPackage
{
public $id;
public $height;
public $width;
public $depth;
public $weight;
public $count = 1;
public $nonstandard = false;
public $type = "paczka"; // list|paleta|paczka
public function __toString()
{
return $this->type . " (wymiary:" . $this->height . "x" . $this->width . "x" . $this->depth . "cm, waga: {$this->weight}kg, ilość: {$this->count})" . ($this->nonstandard ? " niestandardowa" : null);
}
public function asTableRow()
{
return sprintf("<td>%s</td><td>%s</td><td>%s</td><td>%d</td><td>%s</td>",
$this->type,
$this->height . "x" . $this->width . "x" . $this->depth . "cm",
$this->weight . "kg",
$this->count,
$this->nonstandard ? "tak" : "nie"
);
}
public function getType()
{
switch ($this->type) {
case "paczka":return "box";
case "koperta":return "envelope";
case "paleta":return "palette";
}
}
public static function getPackageById($id)
{
$opt = get_option('polkurier_packages');
if (isset($opt[$id])) {
$package = $opt[$id];
$package->id = $id;
return $package;
} else {
return null;
}
}
public function renderForm()
{
if ($this->id || $this->id == 0) {
echo '<input type="hidden" name="polkurier_id" value="' . $this->id . '"/>';
}
?>
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="polkurier_height">Wysokość (cm)</label></th>
<td><input required type="number" name="polkurier_height" id="polkurier_height" value="<?php echo $this->height ?>"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_width">Szerokość (cm)</label></th>
<td><input required type="number" name="polkurier_width" id="polkurier_width" value="<?php echo $this->width ?>"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_depth">Głębokość (cm)</label></th>
<td><input required type="number" name="polkurier_depth" id="polkurier_depth" value="<?php echo $this->depth ?>"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_weight">Waga (kg)</label></th>
<td><input required type="number" name="polkurier_weight" id="polkurier_weight" value="<?php echo $this->weight ?>"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_count">Ilość</label></th>
<td><input required type="number" name="polkurier_count" id="polkurier_count" value="<?php echo $this->count ?>"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_nonstandard">Niestandardowa</label></th>
<td><input type="checkbox" name="polkurier_nonstandard" id="polkurier_nonstandard" <?php if ($this->nonstandard) {
echo "checked";
}
?> value="1"> </td>
</tr>
<tr>
<th scope="row"><label for="polkurier_type">Typ przesyłki</label></th>
<td>
<input type="radio" name="polkurier_type" id="polkurier_type_1" value="koperta" <?php if ($this->type == "koperta") {
echo "checked";
}
?> >
<label for="polkurier_type_1">koperta</label><br/>
<input type="radio" name="polkurier_type" id="polkurier_type_2" value="paczka" <?php if ($this->type == "paczka") {
echo "checked";
}
?> >
<label for="polkurier_type_2">paczka</label><br/>
<input type="radio" name="polkurier_type" id="polkurier_type_3" value="paleta" <?php if ($this->type == "paleta") {
echo "checked";
}
?> >
<label for="polkurier_type_3">paleta</label>
</td>
</tr>
</tbody></table><?php
}
}

View File

@@ -0,0 +1,217 @@
<?php
use Polkurier\Util\Arr;
require_once plugin_dir_path(__FILE__) . 'PolkurierOrderStatusUpdater.php';
class Polkurier_WP_List_Table extends WP_List_Table
{
private static $DEFAULT_PAGE_SIZE = 50;
private static $MAX_DEFAULT_PAGE_SIZE = 250;
/**
* @var \Polkurier\ApiClient|null
*/
private $api;
/**
* @var array|null
*/
private $couriersByCode;
public function get_columns()
{
$columns = array(
'mark' => 'Zaznacz',
'order_number' => 'Numer zamówienia',
'address' => 'Adres nadawcy',
'address_to' => 'Adres odbiorcy',
'date_send' => 'Data nadania',
'label' => 'Listy przewoz.',
'status_date' => 'Zmiana statusu',
'status' => 'Status',
'delivered_date' => 'Data doręczenia',
'price' => 'Cena netto/brutto',
'pobranie' => 'Pobranie',
'action' => 'Działania',
);
return $columns;
}
public function get_sortable_columns()
{
$sortable_columns = array(
'order_number' => array('id', false),
'status_date' => array('status_date', false),
'status' => array('status', false),
'delivered_date' => array('delivered_date', false),
'price_net' => array('price', false),
);
return $sortable_columns;
}
public function prepare_items($unpaid_only = false)
{
$columns = $this->get_columns();
$hidden = array('_id');
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
$orderBy = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'id';
$orderDir = (!empty($_GET['order'])) ? $_GET['order'] : 'DESC';
$currentPage = $this->get_pagenum();
$pageSize = (int)(!empty($_GET['items_per_page'])) ? $_GET['items_per_page'] : 0;
if ($pageSize <= 0) {
$pageSize = self::$DEFAULT_PAGE_SIZE;
}
if ($pageSize >= self::$MAX_DEFAULT_PAGE_SIZE) {
$pageSize = self::$MAX_DEFAULT_PAGE_SIZE;
}
$where = [
'searchQuery' => trim((!empty($_GET['s'])) ? $_GET['s'] : ''),
];
$orders = PolkurierOrder::getAll($where, [$orderBy, $orderDir], $pageSize, ($currentPage - 1) * $pageSize);
$rowsCount = PolkurierOrder::countAll($where);
$this->set_pagination_args(array(
'total_items' => $rowsCount,
'per_page' => $pageSize,
));
$statusUpdater = new PolkurierOrderStatusUpdater();
foreach ($orders as $polkurierOrder) {
if ($statusUpdater->shouldUpdateOrderStatus($polkurierOrder)) {
try {
$statusUpdater->updateOrderStatus($polkurierOrder);
} catch (\Polkurier\Exception\ApiException $e) {
}
}
if ($polkurierOrder->status_code !== 'D') {
$polkurierOrder->delivered_date = null;
$polkurierOrder->save();
}
}
$this->items = $orders;
}
public function column_default($item, $column_name)
{
switch ($column_name) {
case 'date_send':
return !empty($item['extra']['pickup']['pickupdate'])
? $item['extra']['pickup']['pickupdate']
: '';
case 'price':
return $item['price_net'] . ' / ' . $item['price_gross'];
case 'order_number':
return
'<a href="post.php?post=' . $item['wp_order_id'] . '&action=edit">' . $item[$column_name] . '</a>'
. '<div style="font-size: 80%;">' . $this->getCourierName($item['carrier']) . '</div>';
case 'label':
return $this->formatWaybills($item[$column_name]);
case 'status_date':
return ($item[$column_name] == '1970-01-01 01:00') ? '-' : $item[$column_name];
case 'mark':
return '<input type="checkbox" name="label[]" value="' . $item['order_number'] . '"/>';
case 'address':
case 'address_to':
return $this->formatAddress($item[$column_name]->address);
default:
return $item[$column_name];
}
}
private function getCourierName($courier)
{
if ($this->api === null) {
return $courier;
}
if ($this->couriersByCode === null) {
$this->couriersByCode = [];
try {
foreach ($this->api->getAvailableCarriers() as $row) {
$this->couriersByCode[$row['servicecode']] = $row['name'];
}
} catch (\Polkurier\Exception\ApiException $e) {
}
}
if (isset($this->couriersByCode[$courier])) {
return $this->couriersByCode[$courier];
}
return $courier;
}
private function formatWaybills($waybills)
{
$rows = [];
foreach ((array)$waybills as $waybill) {
$rows[] .= '<li><span>' . $waybill . '</span></li>';
}
return '<ul>' . implode('', $rows) . '</ul>';
}
private function formatAddress($address)
{
if (empty($address)) {
return '';
}
$parts = [];
$partsExpand = [];
$country = Arr::get($address, 'country');
if (empty($country)) {
$country = 'PL';
}
$parts[] = $address["company"];
$parts[] = $address["person"];
$parts[] = $address["street"] . " " . $address["housenumber"] . " " . (!empty($address["flatnumber"]) ? (' / ' . $address["flatnumber"]) : '');
$parts[] = $address["postcode"] . " " . $address["city"] . ' (' . $country . ')';
$partsExpand[] = $address["phone"];
$partsExpand[] = $address["email"];
if (!empty($address['point_name'])) {
$partsExpand[] = 'Punkt: ' . $address["point_name"];
}
return
implode('<br>', array_filter($parts))
. (!empty($partsExpand) ? (
'<div class="pk-expand">'
. '<div class="pk-expand-content" style="display: none;">'
. implode('<br>', array_filter($partsExpand))
. '</div>'
. '<a href="#" class="pk-expand-button">[Rozwiń]</a>'
. '</div>'
) : '')
;
}
public function column_action($item)
{
$actions = array(
'cancel' => sprintf('<a href="?page=%s&action=%s&package=%s&order_id=%s" onclick="return confirm(\'Czy na pewno chcesz anulować zamówienie?\')">Anuluj</a>', $_REQUEST['page'], 'cancel', $item['order_number'], $item['wp_order_id']),
'download' => sprintf('<a href="?page=%s&action=%s&label=%s&order_id=%s" target="_blank">Pobierz etykietę</a>', $_REQUEST['page'], 'label', $item['order_number'], $item['wp_order_id']),
'details' => sprintf('<a href="?page=%s&action=%s&label=%s&order_id=%s" target="_blank">Szczegóły</a>', $_REQUEST['page'], 'details', $item['order_number'], $item['wp_order_id']),
);
return sprintf('%1$s', $this->row_actions($actions));
}
/**
* @param \Polkurier\ApiClient $api
* @return $this
*/
public function set_polkurier_api_client($api)
{
if ($api instanceof \Polkurier\ApiClient) {
$this->api = $api;
}
return $this;
}
}

View File

@@ -0,0 +1,204 @@
<?php
/**
* Fired during plugin activation
*
* @link https://example.com
* @since 1.0.0
*
* @package Polkurier
* @subpackage Polkurier/includes
*/
require_once(ABSPATH . '/wp-admin/includes/upgrade.php');
require_once(__DIR__ . '/PolkurierAPI.php');
/**
* Fired during plugin activation.
*
* This class defines all code necessary to run during the plugin's activation.
*
* @since 1.0.0
* @package Polkurier
* @subpackage Polkurier/includes
* @author Polkurier <test@example.com>
*/
class Polkurier_Activator
{
const DATABASE_VERSION = 5;
public static function getDbVersion()
{
return (int)get_option('pk_database_version');
}
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function activate()
{
self::updateDatabaseVersionVersion();
add_option( 'pk_plugin_version', POLKURIER_PLUGIN_VERSION);
}
private static function updateDatabaseVersionVersion()
{
self::ensureOrdersTable();
if (self::getDbVersion() <= 0) {
self::convertDatabaseVersionFrom0To1();
update_option( 'pk_database_version', 1);
}
if (self::getDbVersion() === 1) {
self::convertDatabaseVersionFrom1To2();
update_option( 'pk_database_version', 2);
}
if (self::getDbVersion() === 2) {
self::convertDatabaseVersionFrom2To3();
update_option( 'pk_database_version', 3);
}
if (self::getDbVersion() === 3) {
self::convertDatabaseVersionFrom3To4();
update_option( 'pk_database_version', 4);
}
if (self::getDbVersion() === 4) {
self::convertDatabaseVersionFrom4To5();
update_option( 'pk_database_version', 5);
}
}
private static function ensureOrdersTable()
{
global $wpdb;
$tableName = $wpdb->prefix . 'polkurier_orders';
$charsetCollate = $wpdb->get_charset_collate();
dbDelta("
CREATE TABLE $tableName (
id int(11) NOT NULL AUTO_INCREMENT,
wp_order_id int(11) DEFAULT NULL,
order_number varchar(55) NULL,
label text NULL,
price_gross decimal(20,2) DEFAULT '0.00' NOT NULL,
price_net decimal(20,2) DEFAULT '0.00' NOT NULL,
carrier varchar(255) DEFAULT '' NOT NULL,
address text NULL,
address_to text NULL,
pobranie decimal(20,2) DEFAULT '0.00' NOT NULL,
status_code varchar(10) DEFAULT '' NOT NULL,
delivered_date datetime NULL DEFAULT NULL,
extra text NULL,
date_created DATETIME NULL,
KEY wp_order_id (wp_order_id),
KEY order_number (order_number),
PRIMARY KEY (`id`)
) $charsetCollate;
");
}
private static function convertDatabaseVersionFrom0To1()
{
global $wpdb;
$orders = get_option('polkurier_orders');
if (!empty($orders)) {
foreach ((array)$orders as $order) {
$order->address->fromArray(array_merge($order->address->address, [
'id' => $order->address->id,
]));
$order->address_to->fromArray(array_merge($order->address_to->address, [
'id' => $order->address->id,
]));
$wpdb->insert($wpdb->prefix . 'polkurier_orders', [
'wp_order_id' => $order->params['wp_order_id'],
'order_number' => $order->params['order_number'],
'label' => json_encode($order->params['label']),
'price_gross' => (string)$order->params['price_gross'],
'price_net' => (string)$order->params['price_net'],
'carrier' => $order->params['carrier'],
'address' => json_encode($order->params['address'], JSON_FORCE_OBJECT),
'address_to' => json_encode($order->params['address_to'], JSON_FORCE_OBJECT),
'pobranie' => $order->params['pobranie'],
'extra' => json_encode($order->params['extra'], JSON_FORCE_OBJECT),
'date_created' => date('Y-m-d H:i:s')
]);
}
}
}
private static function convertDatabaseVersionFrom1To2()
{
$settings = get_option('woocommerce_pk_paczka_w_ruchu_settings');
if (!empty($settings) && isset($settings['method_title']) && $settings['method_title'] === 'Paczka w RUCHu') {
$settings['method_title'] = 'ORLEN Paczka';
update_option('woocommerce_pk_paczka_w_ruchu_settings', $settings);
}
}
private static function convertDatabaseVersionFrom2To3()
{
global $wpdb;
$tableName = $wpdb->prefix . 'polkurier_orders';
$wpdb->query("UPDATE $tableName SET date_created = NOW() WHERE date_created IS NULL");
}
private static function convertDatabaseVersionFrom3To4()
{
global $wpdb;
$shippings = [
new \Polkurier\ShippingMethods\InpostParcelMachineShippingMethodMethod(0),
new \Polkurier\ShippingMethods\PaczkaWRuchuShippingMethodMethod(0),
];
$zones = (array)WC_Shipping_Zones::get_zones();
$zones[] = ['id' => 0];
foreach ($shippings as $shipping) {
if ($shipping->is_enabled() && (float)$shipping->get_option('fee') > 0.0) {
foreach ($zones as $zone) {
$position = (int)$wpdb->get_var("SELECT MAX(method_order) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE zone_id = {$zone['id']};");
$wpdb->insert($wpdb->prefix . 'woocommerce_shipping_zone_methods', [
'zone_id' => $zone['id'],
'method_id' => $shipping->getId(),
'method_order' => $position + 1,
'is_enabled' => 1,
]);
$shippingMethod = new \Polkurier\ShippingMethods\InpostParcelMachineShippingMethodMethod($wpdb->insert_id);
update_option($shippingMethod->get_instance_option_key(), [
"enabled" => "yes",
"title" => $shipping->get_option('method_title'),
"cost" => $shipping->get_option('fee'),
"cost_cod" => $shipping->get_option('fee_cod'),
"free_shipping_from" => $shipping->get_option('free_shipping_from'),
]);
}
update_option('pk-update-notice-1.10.0', 1);
}
}
}
private static function convertDatabaseVersionFrom4To5()
{
update_option('polkurier_default_point_id_POCZTEX_PUNKT', get_option('polkurier_default_point_id_KURIER48'));
update_option('polkurier_default_point_label_POCZTEX_PUNKT', get_option('polkurier_default_point_label_KURIER48'));
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* Fired during plugin deactivation
*
* @link https://example.com
* @since 1.0.0
*
* @package Polkurier
* @subpackage Polkurier/includes
*/
/**
* Fired during plugin deactivation.
*
* This class defines all code necessary to run during the plugin's deactivation.
*
* @since 1.0.0
* @package Polkurier
* @subpackage Polkurier/includes
* @author Polkurier <test@example.com>
*/
class Polkurier_Deactivator
{
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function deactivate()
{
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Define the internationalization functionality
*
* Loads and defines the internationalization files for this plugin
* so that it is ready for translation.
*
* @link https://example.com
* @since 1.0.0
*
* @package Polkurier
* @subpackage Polkurier/includes
*/
/**
* Define the internationalization functionality.
*
* Loads and defines the internationalization files for this plugin
* so that it is ready for translation.
*
* @since 1.0.0
* @package Polkurier
* @subpackage Polkurier/includes
* @author Polkurier <test@example.com>
*/
class Polkurier_i18n {
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
public function load_plugin_textdomain() {
load_plugin_textdomain(
'polkurier',
false,
dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/'
);
}
}

View File

@@ -0,0 +1,129 @@
<?php
/**
* Register all actions and filters for the plugin
*
* @link https://example.com
* @since 1.0.0
*
* @package Polkurier
* @subpackage Polkurier/includes
*/
/**
* Register all actions and filters for the plugin.
*
* Maintain a list of all hooks that are registered throughout
* the plugin, and register them with the WordPress API. Call the
* run function to execute the list of actions and filters.
*
* @package Polkurier
* @subpackage Polkurier/includes
* @author Polkurier <test@example.com>
*/
class Polkurier_Loader {
/**
* The array of actions registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $actions The actions registered with WordPress to fire when the plugin loads.
*/
protected $actions;
/**
* The array of filters registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $filters The filters registered with WordPress to fire when the plugin loads.
*/
protected $filters;
/**
* Initialize the collections used to maintain the actions and filters.
*
* @since 1.0.0
*/
public function __construct() {
$this->actions = array();
$this->filters = array();
}
/**
* Add a new action to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress action that is being registered.
* @param object $component A reference to the instance of the object on which the action is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. The priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1.
*/
public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* Add a new filter to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. The priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1
*/
public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* A utility function that is used to register the actions and hooks into a single
* collection.
*
* @since 1.0.0
* @access private
* @param array $hooks The collection of hooks that is being registered (that is, actions or filters).
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority The priority at which the function should be fired.
* @param int $accepted_args The number of arguments that should be passed to the $callback.
* @return array The collection of actions and filters registered with WordPress.
*/
private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) {
$hooks[] = array(
'hook' => $hook,
'component' => $component,
'callback' => $callback,
'priority' => $priority,
'accepted_args' => $accepted_args
);
return $hooks;
}
/**
* Register the filters and actions with WordPress.
*
* @since 1.0.0
*/
public function run() {
foreach ( $this->filters as $hook ) {
add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
foreach ( $this->actions as $hook ) {
add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
}
}

View File

@@ -0,0 +1,792 @@
<?php
/**
* The file that defines the core plugin class
*
* A class definition that includes attributes and functions used across both the
* public-facing side of the site and the admin area.
*
* @link https://example.com
* @since 1.0.0
*
* @package Polkurier
* @subpackage Polkurier/includes
*/
use Polkurier\Blocks\WooCommerceCheckoutIntegration;
use Polkurier\Controller\CheckoutController;
use Polkurier\Controller\CourierPointController;
use Polkurier\Controller\OrderController;
use Polkurier\Exception\HttpException;
use Polkurier\Http\JsonResponse;
use Polkurier\Http\Request;
use Polkurier\Http\Response;
use Polkurier\Integrations\AbstractIntegration;
use Polkurier\Integrations\FlexibleShipping;
use Polkurier\ShippingMethods\AbstractShippingMethod;
use Polkurier\ShippingMethods\DhlPopShippingMethodMethod;
use Polkurier\ShippingMethods\DpdShippingMethodMethod;
use Polkurier\ShippingMethods\FedExDtrShippingMethodMethod;
use Polkurier\ShippingMethods\InpostParcelMachineShippingMethodMethod;
use Polkurier\ShippingMethods\PaczkaWRuchuShippingMethodMethod;
use Polkurier\ShippingMethods\PocztexPointShippingMethod;
use Polkurier\ShippingMethods\UpsAccessPointShippingMethodMethod;
use Polkurier\Types\CheckoutPointButtonPosition;
use Polkurier\Util\Arr;
use Polkurier\Util\OrderTools;
/**
* The core plugin class.
*
* This is used to define internationalization, admin-specific hooks, and
* public-facing site hooks.
*
* Also maintains the unique identifier of this plugin as well as the current
* version of the plugin.
*
* @since 1.0.0
* @package Polkurier
* @subpackage Polkurier/includes
* @author Polkurier <test@example.com>
*/
class Polkurier
{
/**
* The loader that's responsible for maintaining and registering all hooks that power
* the plugin.
*
* @since 1.0.0
* @access protected
* @var Polkurier_Loader $loader Maintains and registers all hooks for the plugin.
*/
protected $loader;
/**
* The unique identifier of this plugin.
*
* @since 1.0.0
* @access protected
* @var string $plugin_name The string used to uniquely identify this plugin.
*/
protected $plugin_name;
/**
* The current version of the plugin.
*
* @since 1.0.0
* @access protected
* @var string $version The current version of the plugin.
*/
protected $version;
/**
* @var Polkurier
*/
private static $runtimeInstance;
/**
* @var string
*/
private $pluginDir;
/**
* @var string
*/
private $pluginUrl;
/**
* @var string
*/
private $text_domain = 'woocommerce-polkurier';
/**
* @var string[]
*/
private $shippingMethods = [
'pk_inpost_paczkomat' => InpostParcelMachineShippingMethodMethod::class,
'pk_paczka_w_ruchu' => PaczkaWRuchuShippingMethodMethod::class,
'pk_dpd_point' => DpdShippingMethodMethod::class,
'pk_fedex_dtr' => FedExDtrShippingMethodMethod::class,
'pk_dhl_point' => DhlPopShippingMethodMethod::class,
'pk_ups_access_point' => UpsAccessPointShippingMethodMethod::class,
'pk_pocztex_point' => PocztexPointShippingMethod::class,
];
/**
* @var AbstractIntegration[]
*/
private $integrations = [];
/**
* Define the core functionality of the plugin.
*
* Set the plugin name and the plugin version that can be used throughout the plugin.
* Load the dependencies, define the locale, and set the hooks for the admin area and
* the public-facing side of the site.
*
* @since 1.0.0
*/
public function __construct()
{
$this->version = POLKURIER_PLUGIN_VERSION;
$this->plugin_name = 'polkurier';
$this->pluginDir = plugin_dir_path(__DIR__);
$this->pluginUrl = plugin_dir_url(__DIR__);
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
add_action('plugins_loaded', [$this, 'onPluginsLoaded'], 100);
add_action('wp_ajax_pk_courier_points', function () {
$this->handlerAjaxRequest(function (Request $request) {
return (new CourierPointController())->searchAction($request);
});
});
add_action('wp_ajax_pk_update_default_courier_point', function () {
$this->handlerAjaxRequest(function (Request $request) {
return (new CourierPointController())->setCourierPoint($request);
});
});
add_action('wp_ajax_pk_evaluate_order', function () {
$this->handlerAjaxRequest(function (Request $request) {
return (new OrderController())->evaluateAction($request);
});
});
// Rejestruje integrację z WC Blocks
add_action('woocommerce_blocks_checkout_block_registration', function ($integration_registry) {
$integration_registry->register(new WooCommerceCheckoutIntegration());
});
// Rejestruje zapis zmian na froncie
add_action('woocommerce_blocks_loaded', function () {
woocommerce_store_api_register_update_callback([
'namespace' => $this->get_plugin_name(),
'callback' => function ($data) {
(new CheckoutController())->handleStoreUpdateCallback(
(string)Arr::get($data, 'action'),
new Request((array)Arr::get($data, 'data'))
);
}
]);
});
}
/**
* @param callable $action
*/
public function handlerAjaxRequest(callable $action)
{
$nonce = Arr::get($_POST, 'nonce', Arr::get($_GET, 'nonce'));
if (!wp_verify_nonce($nonce, 'polkurier-nonce')) {
$response = new JsonResponse(['error' => 'Forbidden'], 403);
$response->send();
exit;
}
try {
$reponse = $action(new Request());
if (!$reponse instanceof Response) {
throw new HttpException('Controller must return instance of Response class', 500);
}
} catch (HttpException $e) {
$reponse = new JsonResponse(['error' => $e->getMessage()], $e->getCode());
} catch (\Exception $e) {
$reponse = new JsonResponse(['error' => $e->getMessage()], 500);
}
$reponse->send();
exit;
}
/**
* @return Polkurier
*/
public static function instance()
{
if (static::$runtimeInstance === null) {
static::$runtimeInstance = new Polkurier();
}
return static::$runtimeInstance;
}
/**
* @return string
*/
public function getPluginDir()
{
return $this->pluginDir;
}
/**
* @param $path
* @return string
*/
public function getPluginPath($path)
{
return $this->getPluginDir() . '/' . $path;
}
/**
* @return string
*/
public function getPluginUrl()
{
return $this->pluginUrl;
}
/**
* @return string
*/
public function getTextDomain()
{
return $this->text_domain;
}
/**
* Zawraca URL do katalogu bazowego
* @param $file
* @return string
*/
public function getPluginDirUrl($file)
{
$basePath = untrailingslashit(plugin_dir_url(__FILE__));
$lastPart = strrpos($basePath, '/');
if ($lastPart !== false) {
$basePath = substr($basePath, 0, $lastPart);
}
return trailingslashit($basePath) . $file;
}
/**
* Load the required dependencies for this plugin.
*
* Include the following files that make up the plugin:
*
* - Polkurier_Loader. Orchestrates the hooks of the plugin.
* - Polkurier_i18n. Defines internationalization functionality.
* - Polkurier_Admin. Defines all hooks for the admin area.
* - Polkurier_Public. Defines all hooks for the public side of the site.
*
* Create an instance of the loader which will be used to register the hooks
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function load_dependencies()
{
/**
* The class responsible for orchestrating the actions and filters of the
* core plugin.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-polkurier-loader.php';
/**
* The class responsible for defining internationalization functionality
* of the plugin.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-polkurier-i18n.php';
/**
* The class responsible for defining all actions that occur in the admin area.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-polkurier-admin.php';
/**
* The class responsible for defining all actions that occur in the public-facing
* side of the site.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'public/class-polkurier-public.php';
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/PolkurierOrderStatusUpdater.php';
$this->loader = new Polkurier_Loader();
}
/**
* Define the locale for this plugin for internationalization.
*
* Uses the Polkurier_i18n class in order to set the domain and to register the hook
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function set_locale()
{
$plugin_i18n = new Polkurier_i18n();
$this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');
}
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_admin_hooks()
{
$plugin_admin = new Polkurier_Admin($this->get_plugin_name(), $this->get_version());
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
// Hooks into admin_menu hook to add custom page
$this->loader->add_action('admin_menu', $plugin_admin, 'add_admin_page');
$this->loader->add_action('admin_init', $plugin_admin, 'register_setting');
}
/**
* Register all of the hooks related to the public-facing functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_public_hooks()
{
$plugin_public = new Polkurier_Public( $this->get_plugin_name(), $this->get_version() );
// $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
// $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
// Hook in
add_filter('woocommerce_checkout_fields', 'polkurier_override_checkout_fields');
// Our hooked in function - $fields is passed via the filter!
function polkurier_override_checkout_fields($fields)
{
$fields['shipping']['shipping_phone'] = array(
'label' => __('Telefon', 'woocommerce'),
'placeholder' => _x('Telefon', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['shipping']['shipping_email'] = array(
'label' => __('E-mail', 'woocommerce'),
'placeholder' => _x('E-mail', 'placeholder', 'woocommerce'),
'required' => false,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
/**
* Display field value on the order edit page
*/
add_action('woocommerce_admin_order_data_after_shipping_address', 'polkurier_checkout_field_display_admin_order_meta', 10, 1);
/**
* @param WC_Order $order
*/
function polkurier_checkout_field_display_admin_order_meta($order)
{
echo '<p><strong>' . __('Numer telefonu') . ':</strong> ' . get_post_meta($order->get_id(), '_shipping_phone', true) . '</p>';
echo '<p><strong>' . __('Adres e-mail') . ':</strong> ' . get_post_meta($order->get_id(), '_shipping_email', true) . '</p>';
echo '<p><strong>' . __('Punkt odbioru') . ':</strong> ' . get_post_meta($order->get_id(), '_polkurier_point_id', true) . '</p>';
$shippingMethod = OrderTools::getShippingMethod($order);
if (!empty(get_post_meta($order->get_id(), '_polkurier_point_id', true))) {
echo '<p>'
. '<strong>' . ($shippingMethod !== null && OrderTools::isOwnShippingMethod($shippingMethod) ? $shippingMethod->getSelectedPointLabel() : 'Wybrany punkt odbioru') . ':</strong><br>'
. '<strong>' . get_post_meta($order->get_id(), '_polkurier_point_id', true) . '</strong><br>'
. nl2br(get_post_meta($order->get_id(), '_polkurier_point_label', true))
. '</p>';
}
}
}
/**
* @return array
*/
public function getShippingMethods()
{
$shippingMethods = [];
foreach ($this->getAllShippingMethods() as $shippingMethod) {
if ($shippingMethod instanceof AbstractShippingMethod) {
$shippingMethods[] = $shippingMethod;
}
}
return $shippingMethods;
}
/**
* @param $id
* @param null $instanceId
* @return WC_Shipping_Method|null
*/
public function getShippingMethodById($id, $instanceId = null)
{
foreach ($this->getAllShippingMethods() as $shippingMethod) {
if ($shippingMethod->id === $id && ($instanceId === null || $instanceId === $shippingMethod->instance_id)) {
return $shippingMethod;
}
}
return null;
}
/**
* @return WC_Shipping_Method[]
*/
public function getAllShippingMethods()
{
$zones = (array)WC_Shipping_Zones::get_zones();
$shippingMethods = [];
foreach ($zones as $zone) {
/** @var WC_Shipping_Method $method */
foreach ((array)$zone['shipping_methods'] as $method) {
$shippingMethods[] = $method;
}
}
return $shippingMethods;
}
public function getMapShippingMethods()
{
$methods = [];
foreach ($this->getAllShippingMethods() as $shippingMethod) {
if ($shippingMethod instanceof AbstractShippingMethod && $shippingMethod->isParcelPickupPoint()) {
$methods[] = $shippingMethod;
}
foreach ($this->integrations as $integration) {
if ($integration instanceof FlexibleShipping && $integration->shouldShowMapButton($shippingMethod)) {
$methods[] = $shippingMethod;
}
}
}
return $methods;
}
public function getMapShippingMethodsIds()
{
$methodsIds = [];
foreach ($this->getMapShippingMethods() as $shippingMethod) {
$methodsIds[] = $shippingMethod->id . ':' . $shippingMethod->instance_id;
}
return $methodsIds;
}
/**
* @return WC_Shipping_Method|null
*/
public function getCurrentShippingMethod()
{
$session = WC()->session;
if ($session === null) {
return null;
}
$chosenShippingMethods = $session->chosen_shipping_methods;
if (!is_array($chosenShippingMethods) || count($chosenShippingMethods) === 0) {
return null;
}
$currentShippingMethodId = $chosenShippingMethods[0];
foreach ($this->getAllShippingMethods() as $method) {
$methodId = $method->id . ':' . $method->instance_id;
if ($methodId === $currentShippingMethodId) {
return $method;
}
}
return null;
}
/**
* @return AbstractIntegration[]
*/
public function getIntegrations()
{
return $this->integrations;
}
public function onPluginsLoaded()
{
if (!class_exists('WooCommerce') || version_compare(WC()->version, '3.0', '<')) {
add_action('admin_notices', function () {
echo '<div class="error"><p><strong>Polkurier</strong> wymaga do działania wtyczki WooCommerce w wersji minimum 3.0</p></div>';
});
return;
}
$activePlugins = apply_filters('active_plugins', get_option('active_plugins'));
// Integracja z FlexibleShipping
if (in_array('flexible-shipping/flexible-shipping.php', $activePlugins, true)) {
$this->integrations[] = new FlexibleShipping();
}
add_filter('woocommerce_shipping_methods', [$this, 'onWoocommerceShippingMethods']);
add_filter('woocommerce_get_order_item_totals', [$this, 'onWoocommerceGetOrderItemTotals'], 2, 100);
add_action('wp_enqueue_scripts', function () {
if (is_checkout()) {
$this->enqueueFrontAssets();
}
});
// Formatowanie adresu wysyłki po złożeniu zamówienia
add_filter('woocommerce_order_get_formatted_shipping_address', function ($addressData) {
global $wp;
$orderId = (int)Arr::get($wp->query_vars, 'order-received');
if ($orderId > 0) {
$order = new WC_Order($orderId);
$orderShippingMethod = Arr::get(array_values($order->get_shipping_methods()), '0');
$shippingMethod = \Polkurier::instance()->getShippingMethodById($orderShippingMethod->get_method_id(), (int)$orderShippingMethod->get_instance_id());
if ($shippingMethod !== null) {
$shouldShowPickupPointAddress = false;
if ($shippingMethod instanceof AbstractShippingMethod && $shippingMethod->isParcelPickupPoint()) {
$shouldShowPickupPointAddress = true;
}
foreach ($this->integrations as $integration) {
if ($integration instanceof FlexibleShipping && $integration->shouldShowMapButton($shippingMethod)) {
$shouldShowPickupPointAddress = true;
}
}
if ($shouldShowPickupPointAddress) {
return wc_get_template_html(
'checkout/order_get_formatted_shipping_address.php',
[
'provider' => get_post_meta($orderId, '_polkurier_provider', true),
'pointId' => get_post_meta($orderId, '_polkurier_point_id', true),
'pointLabel' => get_post_meta($orderId, '_polkurier_point_label', true),
'pointType' => get_post_meta($orderId, '_polkurier_point_type', true),
],
'',
$this->getPluginPath('templates/')
);
}
}
}
return $addressData;
});
$renderMapButton = function ($method, $position) {
if (is_checkout() && get_option('polkurier_layout_checkout_point_button_position') === $position) {
$currentMethod = \Polkurier::instance()->getCurrentShippingMethod();
if ($method instanceof \WC_Shipping_Rate && $currentMethod !== null) {
$isValid = $method->id === $currentMethod->id . ':' . $currentMethod->get_instance_id();
} else {
$isValid = true;
}
if ($currentMethod !== null && $isValid) {
if ($currentMethod instanceof AbstractShippingMethod && $currentMethod->isParcelPickupPoint()) {
$currentMethod->render();
}
foreach ($this->integrations as $integration) {
if ($integration instanceof FlexibleShipping && $integration->shouldShowMapButton($currentMethod)) {
$integration->renderShippingMethod($currentMethod);
}
}
}
}
};
// Wyświetla przycisk "Wybierz paczkomat" pod blokiem wyboru metod wysyłki
add_action('woocommerce_review_order_after_shipping', function () use ($renderMapButton) {
$renderMapButton(null, CheckoutPointButtonPosition::AFTER_SHIPPING_BLOCK);
});
// Wyświetla przycisk "Wybierz paczkomat" w wybranym miejscu
foreach (CheckoutPointButtonPosition::VALID_POSITIONS as $positionName) {
$filterName = $positionName;
if (!empty(CheckoutPointButtonPosition::MAP_POSITIONS[$positionName])) {
$filterName = CheckoutPointButtonPosition::MAP_POSITIONS[$positionName];
}
$priority = CheckoutPointButtonPosition::DEFAULT_PRIORITY;
if (!empty(CheckoutPointButtonPosition::PRIORITIES[$positionName])) {
$priority = CheckoutPointButtonPosition::PRIORITIES[$positionName];
}
add_action($filterName, function ($method) use ($renderMapButton, $positionName) {
$renderMapButton($method, $positionName);
}, $priority);
}
add_action('woocommerce_checkout_update_order_review', function () {
$currentMethod = \Polkurier::instance()->getCurrentShippingMethod();
if ($currentMethod instanceof AbstractShippingMethod) {
$currentMethod->onCheckoutUpdateOrderReview();
}
});
// Walidacja zamówienia legacy
add_action('woocommerce_checkout_process', function () {
$currentMethod = \Polkurier::instance()->getCurrentShippingMethod();
if ($currentMethod instanceof AbstractShippingMethod && $currentMethod->isParcelPickupPoint()) {
$currentMethod->onCheckoutProcess();
}
foreach ($this->integrations as $integration) {
if ($integration instanceof FlexibleShipping) {
$integration->onCheckoutProcess();
}
}
});
// Walidacja zamówienia Blocks
add_action('woocommerce_store_api_checkout_order_processed', function (WC_Order $order) {
$currentMethod = \Polkurier::instance()->getCurrentShippingMethod();
if ($currentMethod instanceof AbstractShippingMethod && $currentMethod->isParcelPickupPoint()) {
$currentMethod->onCheckoutProcess($order);
}
foreach ($this->integrations as $integration) {
if ($integration instanceof FlexibleShipping) {
$integration->onCheckoutProcess($order);
}
}
}, 10, 3);
// Zapis zamówienia
add_action('woocommerce_new_order', function ($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
$sessionStore = WC()->session->get($this->get_plugin_name() . '_delivery_point');
$hasSessionStore = !empty($sessionStore);
$pointId = Arr::get($_POST, 'polkurier_point_id');
if ($hasSessionStore && empty($pointId)) {
$pointId = Arr::get($sessionStore, 'id');
}
if (empty($pointId) && !empty($post_id)) {
$pointId = Arr::get(get_post_meta($post_id, '_polkurier_point_id'), 0);
}
$providerName = Arr::get($_POST, 'polkurier_provider');
if ($hasSessionStore && empty($providerName)) {
$providerName = Arr::get($sessionStore, 'provider');
}
if (empty($providerName) && !empty($post_id)) {
$providerName = Arr::get(get_post_meta($post_id, '_polkurier_provider'), 0);
}
$pointLabel = Arr::get($_POST, 'polkurier_point_label');
if ($hasSessionStore && empty($pointLabel)) {
$pointLabel = Arr::get($sessionStore, 'label');
}
if (empty($pointLabel) && !empty($post_id)) {
$pointLabel = Arr::get(get_post_meta($post_id, '_polkurier_point_label'), 0);
}
$pointType = Arr::get($_POST, 'polkurier_point_type');
if ($hasSessionStore && empty($pointType)) {
$pointType = Arr::get($sessionStore, 'type');
}
if (empty($pointType) && !empty($post_id)) {
$pointType = Arr::get(get_post_meta($post_id, '_polkurier_point_type'), 0);
}
update_post_meta($post_id, '_polkurier_provider', esc_attr($providerName));
update_post_meta($post_id, '_polkurier_point_id', esc_attr($pointId));
update_post_meta($post_id, '_polkurier_point_label', esc_attr($pointLabel));
update_post_meta($post_id, '_polkurier_point_type', esc_attr($pointType));
WC()->session->set(\Polkurier::instance()->get_plugin_name() . '_delivery_point', null);
});
}
public function onWoocommerceGetOrderItemTotals($items, $wcOrder)
{
$pointId = get_post_meta($wcOrder->get_id(), '_polkurier_point_id', true);
if (isset($items['shipping']) && !empty($pointId)) {
$items['shipping']['value'] .= wc_get_template_html(
'checkout/get_order_item_totals_point.php',
[
'pointId' => $pointId,
'pointLabel' => get_post_meta($wcOrder->get_id(), '_polkurier_point_label', true),
],
'',
$this->getPluginPath('templates/')
);
}
return $items;
}
public function enqueueFrontAssets()
{
$name = $this->get_plugin_name();
wp_enqueue_script(uniqid($name, true), $this->getPluginUrl() . 'public/js/polkurier-checkout-page.js', ['jquery'], $this->version, true);
wp_enqueue_script(uniqid($name, true), 'https://maps.polkurier.pl/assets/dist/points-map.bundle.js', ['jquery'], $this->version, true);
wp_enqueue_style(uniqid($name, true), 'https://maps.polkurier.pl/assets/dist/points-map.css', [], $this->version);
}
/**
* @param array $methods
* @return array
*/
public function onWoocommerceShippingMethods($methods)
{
foreach ($this->shippingMethods as $methodId => $methodClass) {
$methods[$methodId] = $methodClass;
}
return $methods;
}
/**
* Run the loader to execute all of the hooks with WordPress.
*
* @since 1.0.0
*/
public function run()
{
$this->loader->run();
}
/**
* The name of the plugin used to uniquely identify it within the context of
* WordPress and to define internationalization functionality.
*
* @return string The name of the plugin.
* @since 1.0.0
*/
public function get_plugin_name()
{
return $this->plugin_name;
}
/**
* The reference to the class that orchestrates the hooks with the plugin.
*
* @return Polkurier_Loader Orchestrates the hooks of the plugin.
* @since 1.0.0
*/
public function get_loader()
{
return $this->loader;
}
/**
* Retrieve the version number of the plugin.
*
* @return string The version number of the plugin.
* @since 1.0.0
*/
public function get_version()
{
return $this->version;
}
}

View File

@@ -0,0 +1 @@
<?php // Silence is golden

View File

@@ -0,0 +1,30 @@
<?php
ob_clean();
$paczka = null;
switch ($_GET['package']) {
case "paczka":$paczka = "box";
break;
case "koperta":$paczka = "envelope";
break;
case "paleta":$paczka = "palette";
break;
}
$data = $api->pickupCourier($_GET['date'], $_GET['courier'], $_GET['postalcode'], $paczka);
if (!$api->lastError) {
if (empty($data['time'])) {
echo "Wybrany przewoźnik nie wymaga podania godziny odbioru.";
} else {
?>
<select name="polkurier_pickup_date" id="polkurier_pickup_date_select">
<?php foreach ($data['time'] as $times): ?>
<option value="<?php echo $times['timefrom'] . '-' . $times['timeto'] ?>" <?php if (isset($_GET['check']) && $_GET['check'] == $times['timefrom'] . '-' . $times['timeto']) {
echo "selected";
}
?>><?php echo $times['timefrom'] . '-' . $times['timeto'] ?></option>
<?php endforeach;?>
</select>
<?php
}
}
exit();

View File

@@ -0,0 +1,21 @@
<?php
ob_clean();
$content = $api->getLabel($_GET['label']);
if ($api->lastError) {
null;
} else {
if (is_array($_GET['label'])) {
$name = "polkurier_" . time() . ".pdf";
} else {
$name = "polkurier_" . $_GET['label'] . ".pdf";
}
header('Content-Type: application/pdf');
header('Content-Length: ' . strlen($content));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
echo $content;
}
exit();