Skip to content

Commit 28a1833

Browse files
commit
1 parent aa15b9b commit 28a1833

File tree

4 files changed

+207
-3
lines changed

4 files changed

+207
-3
lines changed

app/base/controllers/Admin/Commerce/OrderShipments.php

Lines changed: 114 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ public function getFormDefinition(FAPI\Form $form, array &$form_state): FAPI\For
149149
switch ($type) {
150150
case 'view' :
151151

152+
$form->addMarkup($this->renderShipmentInfo($orderShipment));
152153

153154
break;
154155
case 'edit':
@@ -251,7 +252,29 @@ public function formSubmitted(FAPI\Form $form, &$form_state): mixed
251252
// no break
252253
case 'edit':
253254

254-
255+
$orderShipment->setShippingMethod($values['shipping_method']);
256+
$orderShipment->setShipmentCode($values['shipment_code']);
257+
$orderShipment->setStatus($values['status']);
258+
$orderShipment->setWebsiteId($values['website_id']);
259+
260+
$changedData = $orderShipment->getChangedData();
261+
262+
if (is_numeric($values['location']['latitude']) && is_numeric($values['location']['longitude'])) {
263+
$changedData += [
264+
'latitude' => $values['location']['latitude'],
265+
'longitude' => $values['location']['longitude'],
266+
];
267+
268+
// update position, saving history if needed (this also persists the object)
269+
$orderShipment->updatePosition($values['location']['latitude'], $values['location']['longitude']);
270+
}
271+
272+
$this->setAdminActionLogData($changedData);
273+
274+
$orderShipment->persist();
275+
276+
$this->addSuccessFlashMessage($this->getUtils()->translate("Order Shipment Saved."));
277+
255278
break;
256279
case 'delete':
257280
$orderShipment->delete();
@@ -276,8 +299,9 @@ protected function getTableHeader(): ?array
276299
'ID' => 'id',
277300
'Website' => ['order' => 'website_id', 'foreign' => 'website_id', 'table' => $this->getModelTableName(), 'view' => 'site_name'],
278301
'Order' => ['order' => 'order_id', 'foreign' => 'order_id', 'table' => $this->getModelTableName(), 'view' => 'order_number'],
279-
'Shipping Method' => ['order' => 'shipping_method'],
280-
'Shipment Code' => ['order' => 'shipment_code'],
302+
'Shipping Method' => ['order' => 'shipping_method', 'search' => 'shipping_method'],
303+
'Shipment Code' => ['order' => 'shipment_code', 'search' => 'shipment_code'],
304+
'Status' => ['order' => 'status'],
281305
'actions' => null,
282306
];
283307
}
@@ -301,6 +325,7 @@ function ($orderShipment) {
301325
'Order' => $orderShipment->getOrder()->getOrderNumber(),
302326
'Shipping Method' => $orderShipment->getShippingMethod(),
303327
'Shipment Code' => $orderShipment->getShipmentCode(),
328+
'Status' => $orderShipment->getStatus(),
304329
'actions' => [
305330
static::VIEW_BTN => $this->getViewButton($orderShipment->id),
306331
static::EDIT_BTN => $this->getEditButton($orderShipment->id),
@@ -337,4 +362,90 @@ public static function exposeDataToDashboard() : mixed
337362
{
338363
return null;
339364
}
365+
366+
protected function renderShipmentInfo(OrderShipmentModel $orderShipment) : string
367+
{
368+
$locationScript = '';
369+
$latitude = $orderShipment->getLatitude();
370+
$longitude = $orderShipment->getLongitude();
371+
if ($this->getEnvironment()->getVariable('GOOGLE_API_KEY')) {
372+
$locationScript = "<script type=\"text/javascript\">
373+
var latlng = {
374+
lat: ".$latitude.",
375+
lng: ".$longitude."
376+
};
377+
var map = new google.maps.Map(document.getElementById('shipment-history-map'), {
378+
zoom: 4,
379+
center: latlng
380+
});
381+
382+
var marker = new google.maps.Marker({
383+
position: latlng,
384+
map: map,
385+
draggable: false
386+
});
387+
</script>";
388+
} else if ($this->getEnvironment()->getVariable('MAPBOX_API_KEY')) {
389+
$locationScript = "<script type=\"text/javascript\">
390+
var latlng = {
391+
lat: ".$latitude.",
392+
lng: ".$longitude."
393+
};
394+
var map = L.map('shipment-history-map').setView([latlng.lat,latlng.lng],4);
395+
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
396+
attribution:
397+
'Map data &copy; <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors,'+
398+
'<a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>,'+
399+
' Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>',
400+
maxZoom: 18,
401+
id: 'mapbox/streets-v12',
402+
accessToken: '{$this->getEnvironment()->getVariable('MAPBOX_API_KEY')}'
403+
}).addTo(map);
404+
405+
var marker = L.marker([latlng.lat, latlng.lng],{
406+
draggable: false
407+
}).addTo(map);
408+
</script>";
409+
}
410+
411+
return
412+
'<h2>'.$this->getUtils()->translate('Shipment %s for order %s', [$orderShipment->getShipmentCode(),$orderShipment->getOrder()?->getOrderNumber()]).'</h2><hr/>'.
413+
'<div id="shipment-history-map" style="height:400px;margin-bottom:20px;"></div>'.
414+
$locationScript .
415+
($orderShipment->getLatitude() && $orderShipment->getLongitude() ?
416+
'<script type="text/javascript">
417+
document.addEventListener("DOMContentLoaded", function() {
418+
var mapOptions = {
419+
center: { lat: '.$orderShipment->getLatitude().', lng: '.$orderShipment->getLongitude().' },
420+
zoom: 12
421+
};
422+
var map = new google.maps.Map(document.querySelector(".shipment-history-map"), mapOptions);
423+
var marker = new google.maps.Marker({
424+
position: { lat: '.$orderShipment->getLatitude().', lng: '.$orderShipment->getLongitude().' },
425+
map: map,
426+
title: "Current Location"
427+
});
428+
});
429+
</script>'
430+
: '<p>'.$this->getUtils()->translate('No current location available').'</p>'
431+
).
432+
433+
($orderShipment->getPositionHistory() === [] ?
434+
'<p>'.$this->getUtils()->translate('No position history available').'</p>'
435+
:
436+
'<h3>'.$this->getUtils()->translate('Position History').'</h3>'.
437+
'<ul class="list-group"><li class="list-group-item">'.implode('</li><li class="list-group-item">', array_map(
438+
function ($historyItem) {
439+
$data = [
440+
'latitude' => $historyItem->getLatitude(),
441+
'longitude' => $historyItem->getLongitude(),
442+
'when' => $historyItem->getCreatedAt()
443+
];
444+
445+
return $this->getHtmlRenderer()->renderArrayOnTable($data);
446+
},
447+
$orderShipment->getPositionHistory()
448+
))."</li></ul>"
449+
);
450+
}
340451
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace App\Base\Migrations;
4+
5+
use App\Base\Abstracts\Migrations\DBMigration;
6+
use Psr\Container\ContainerInterface;
7+
use Degami\SqlSchema\Index;
8+
use Degami\SqlSchema\Table;
9+
use Degami\SqlSchema\ForeignKey;
10+
11+
class CreateOrderShipmentHistoryTableMigration extends DBMigration
12+
{
13+
protected string $tableName = 'order_shipment_history';
14+
15+
public function getName(): string
16+
{
17+
return '9.3_'.parent::getName();
18+
}
19+
20+
public function addDBTableDefinition(Table $table): Table
21+
{
22+
$table->addColumn('id', 'INT', null, ['UNSIGNED'], false)
23+
->addColumn('shipment_id', 'INT', null, ['UNSIGNED'], false)
24+
->addColumn('latitude', 'FLOAT', null, [], true, null)
25+
->addColumn('longitude', 'FLOAT', null, [], true, null)
26+
->addColumn('created_at', 'TIMESTAMP', null, [], false, 'CURRENT_TIMESTAMP()')
27+
->addColumn('updated_at', 'TIMESTAMP', null, [], false, 'CURRENT_TIMESTAMP()')
28+
->addIndex(null, 'id', Index::TYPE_PRIMARY)
29+
->addForeignKey('fk_shipmenthistory_shipment_id', ['shipment_id'], 'order_shipment', ['id'], ForeignKey::ACTION_CASCADE, ForeignKey::ACTION_CASCADE)
30+
->setAutoIncrementColumn('id');
31+
32+
return $table;
33+
}
34+
}

app/base/models/OrderShipment.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace App\Base\Models;
1515

1616
use App\App;
17+
use App\Base\Abstracts\Models\BaseCollection;
1718
use App\Base\Abstracts\Models\BaseModel;
1819
use App\Base\Traits\WithWebsiteTrait;
1920
use App\Base\Traits\WithOwnerTrait;
@@ -217,4 +218,40 @@ public function postPersist(array $persistOptions = []): BaseModel
217218

218219
return parent::postPersist($persistOptions);
219220
}
221+
222+
public function updatePosition(float $latitude, float $longitude): self
223+
{
224+
if ($this->getLatitude() === $latitude && $this->getLongitude() === $longitude) {
225+
return $this;
226+
}
227+
228+
if (!is_null($this->getLatitude()) || !is_null($this->getLongitude())) {
229+
// log previous location
230+
/** @var OrderShipmentHistory $history */
231+
$history = App::getInstance()->containerMake(OrderShipmentHistory::class);
232+
$history
233+
->setShipmentId($this->getId())
234+
->setLatitude($this->getLatitude())
235+
->setLongitude($this->getLongitude())
236+
->persist();
237+
}
238+
239+
$this
240+
->setLatitude($latitude)
241+
->setLongitude($longitude)
242+
->persist();
243+
244+
return $this;
245+
}
246+
247+
public function getPositionHistory(): array
248+
{
249+
/** @var OrderShipmentHistory[] $history */
250+
$history = OrderShipmentHistory::getCollection()
251+
->where(['shipment_id' => $this->getId()])
252+
->addOrder(['created_at' => 'DESC'])
253+
->getItems();
254+
255+
return $history;
256+
}
220257
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace App\Base\Models;
4+
5+
use App\Base\Abstracts\Models\BaseModel;
6+
7+
8+
/**
9+
* @method int getShipmentId()
10+
* @method float getLatitude()
11+
* @method float getLongitude()
12+
* @method \DateTime getCreatedAt()
13+
* @method \DateTime getUpdatedAt()
14+
* @method self setShipmentId(int $shipment_id)
15+
* @method self setLatitude(float $latitude)
16+
* @method self setLongitude(float $longitude)
17+
* @method self setCreatedAt(\DateTime $created_at)
18+
* @method self setUpdatedAt(\DateTime $updated_at)
19+
*/
20+
class OrderShipmentHistory extends BaseModel
21+
{
22+
}

0 commit comments

Comments
 (0)