DHL Modul v0.5 Shipping Label ok

This commit is contained in:
Kevin Adametz 2025-08-22 18:18:26 +02:00
parent 480fdc65ed
commit 8fdaa0ba1d
122 changed files with 17938 additions and 2239 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,89 @@
<?php
namespace App\Services;
use App\Models\ShoppingOrder;
use App\Http\Controllers\SettingController;
/**
* DHL Data Helper
*
* Central class for preparing DHL API data structures
* Prevents code duplication between DhlShipmentService and CreateShipmentJob
*/
class DhlDataHelper
{
/**
* Prepare order data for DHL API v2
*
* Structure matches official DHL API v2 createOrders endpoint:
* https://developer.dhl.com/api-reference/parcel-de-shipping-post-parcel-germany-v2
*
* @param ShoppingOrder $order
* @param float $weight
* @param array $options
* @param array|null $dhlConfig Optional pre-loaded config (for queue jobs)
* @return array
*/
public static function prepareOrderData(ShoppingOrder $order, float $weight, array $options = [], ?array $dhlConfig = null): array
{
\Log::info('prepareOrderData', $options);
//die daten für das versandlabel werden immer aus dem Formular genommen, damit anpassungen möglich sind
if (!isset($options['shipping_address'])) {
throw new \Exception('shipping_address is required');
}
$shippingAddress = $options['shipping_address'];
// Get DHL configuration for shipper data
if ($dhlConfig === null) {
$settingController = new SettingController();
$dhlConfig = $settingController->getDhlConfig();
}
return [
'order_id' => $order->id,
'weight_kg' => $weight,
'product_code' => $options['product_code'] ?? 'V01PAK',
'label_format' => $options['label_format'] ?? $dhlConfig['label_format'] ?? 'PDF',
'print_format' => $options['print_format'] ?? $dhlConfig['print_format'] ?? null,
'retoure_print_format' => $options['retoure_print_format'] ?? $dhlConfig['retoure_print_format'] ?? null,
// Shipper data (sender) - from admin settings
'shipper' => [
'name' => $dhlConfig['sender']['company'] ?? 'mivita care gmbh',
'name2' => $dhlConfig['sender']['name'] ?? '',
'street' => $dhlConfig['sender']['street'] ?? 'Leinfeld',
'houseNumber' => $dhlConfig['sender']['house_number'] ?? '2',
'postalCode' => $dhlConfig['sender']['postalCode'] ?? '87755',
'city' => $dhlConfig['sender']['city'] ?? 'Kirchhaslach',
'country' => $dhlConfig['sender']['country'] ?? 'DE',
'email' => $dhlConfig['sender']['email'] ?? 'versand@mivita.care',
'phone' => $dhlConfig['sender']['phone'] ?? '+49 123 456789',
],
// Consignee data (recipient) - from order
'consignee' => [
'name' => $shippingAddress['firstname'] ?? '' . ' ' . $shippingAddress['lastname'] ?? '',
'name2' => $shippingAddress['company'] ?? '',
'street' => $shippingAddress['address'] ?? '',
'houseNumber' => $shippingAddress['houseNumber'] ?? '',
'postalCode' => $shippingAddress['zipcode'] ?? '',
'city' => $shippingAddress['city'] ?? '',
'country' => $shippingAddress['country']?->code ?? 'DE',
'email' => $shippingAddress['email'] ?? '',
'phone' => $shippingAddress['phone'] ?? '',
],
// Package dimensions from options or defaults
'dimensions' => [
'length' => $options['length'] ?? 30,
'width' => $options['width'] ?? 25,
'height' => $options['height'] ?? 10,
],
// Additional services
'services' => $options['services'] ?? [],
// Custom reference for tracking
'reference' => 'Order-' . $order->id,
];
}
}

View file

@ -0,0 +1,439 @@
<?php
namespace App\Services;
use App\Models\ShoppingOrder;
use App\Models\Country;
use Illuminate\Support\Facades\Log;
use Exception;
/**
* DHL Modal Service
*
* Service class that handles all business logic for the DHL shipment creation modal.
* Validates order data, processes addresses, and prepares data for the view.
*/
class DhlModalService
{
/**
* @var array DHL configuration
*/
private $config;
/**
* Constructor
*/
public function __construct()
{
$this->config = config('dhl');
}
/**
* Prepare modal data for DHL shipment creation
*
* @param mixed $id Order ID or 'new'
* @param array $data Additional data from the request
* @return array Prepared data for the view
* @throws Exception
*/
public function prepareModalData($id, array $data): array
{
$result = [
'order' => null,
'orderWeight' => 1.0,
'shippingAddress' => null,
'availableCountries' => $this->getAvailableCountries(),
'productCodes' => $this->getAvailableProductCodes(),
'errors' => [],
'warnings' => []
];
// If no order ID or 'new', return empty data for order selection
if (!$id || $id === 'new') {
return $result;
}
try {
// Load and validate order
$order = $this->loadOrder($id);
if (!$order) {
$result['errors'][] = "Bestellung #{$id} wurde nicht gefunden.";
return $result;
}
$result['order'] = $order;
// Calculate order weight
$result['orderWeight'] = $this->calculateOrderWeight($order);
// Process and validate shipping address
$result['shippingAddress'] = $this->processShippingAddress($order);
// Validate address completeness
$addressValidation = $this->validateAddress($result['shippingAddress']);
if (!$addressValidation['valid']) {
$result['errors'] = array_merge($result['errors'], $addressValidation['errors']);
}
if (!empty($addressValidation['warnings'])) {
$result['warnings'] = array_merge($result['warnings'], $addressValidation['warnings']);
}
Log::info('[DHL Modal] Prepared modal data successfully', [
'order_id' => $order->id,
'weight' => $result['orderWeight'],
'address_valid' => empty($result['errors'])
]);
} catch (Exception $e) {
Log::error('[DHL Modal] Error preparing modal data', [
'order_id' => $id,
'error' => $e->getMessage()
]);
$result['errors'][] = 'Fehler beim Laden der Bestelldaten: ' . $e->getMessage();
}
return $result;
}
/**
* Load order with required relationships
*
* @param mixed $id
* @return ShoppingOrder|null
*/
private function loadOrder($id): ?ShoppingOrder
{
return ShoppingOrder::with([
'shopping_order_items',
'shopping_user',
])->find($id);
}
/**
* Calculate order weight in kg
*
* @param ShoppingOrder $order
* @return float
*/
private function calculateOrderWeight(ShoppingOrder $order): float
{
return $order->weight / 100;
/*
// Default fallback weight
$defaultWeight = 1.0;
if (!$order->shopping_order_items || $order->shopping_order_items->isEmpty()) {
return $defaultWeight;
}
// If order has a weight field (in grams), convert to kg
if ($order->weight && $order->weight > 0) {
return round($order->weight / 100, 1); // Convert grams to kg
}
// Calculate from items if available
$totalWeight = 0;
foreach ($order->shopping_order_items as $item) {
if ($item->weight && $item->weight > 0) {
$totalWeight += ($item->weight * $item->quantity);
}
}
if ($totalWeight > 0) {
return round($totalWeight / 100, 1); // Convert grams to kg
}
// Estimate based on item count if no weight data
$itemCount = $order->shopping_order_items->sum('quantity');
$estimatedWeight = max($itemCount * 0.5, $defaultWeight); // Estimate 0.5kg per item
return round($estimatedWeight, 1);
*/
}
/**
* Process and parse shipping address from order
*
* @param ShoppingOrder $order
* @return array
*/
private function processShippingAddress(ShoppingOrder $order): array
{
$shoppingUser = $order->shopping_user;
if (!$shoppingUser) {
return $this->getEmptyAddress();
}
// Determine if shipping address is different from billing
$useShipping = !($shoppingUser->same_as_billing ?? true);
// Extract address data
$addressData = [
'firstname' => $useShipping ? ($shoppingUser->shipping_firstname ?? '') : ($shoppingUser->billing_firstname ?? ''),
'lastname' => $useShipping ? ($shoppingUser->shipping_lastname ?? '') : ($shoppingUser->billing_lastname ?? ''),
'company' => $useShipping ? ($shoppingUser->shipping_company ?? '') : ($shoppingUser->billing_company ?? ''),
'address' => $useShipping ? ($shoppingUser->shipping_address ?? '') : ($shoppingUser->billing_address ?? ''),
'address_2' => $useShipping ? ($shoppingUser->shipping_address_2 ?? '') : ($shoppingUser->billing_address_2 ?? ''),
'zipcode' => $useShipping ? ($shoppingUser->shipping_zipcode ?? '') : ($shoppingUser->billing_zipcode ?? ''),
'city' => $useShipping ? ($shoppingUser->shipping_city ?? '') : ($shoppingUser->billing_city ?? ''),
'country' => $useShipping ? ($shoppingUser->shipping_country ?? null) : ($shoppingUser->billing_country ?? null),
'phone' => $useShipping ? ($shoppingUser->shipping_phone ?? '') : ($shoppingUser->billing_phone ?? ''),
'email' => $shoppingUser->billing_email ?? '',
'houseNumber' => '',
];
// Parse and separate street name and number
$this->parseStreetAddress($addressData);
return $addressData;
}
/**
* Parse street address and separate street name from house number
*
* @param array &$addressData
*/
private function parseStreetAddress(array &$addressData): void
{
$address = trim($addressData['address']);
// If address_2 is empty and address contains both street and number
if (!empty($address)) {
// Try to separate street name and house number
$patterns = [
// Pattern 1: "Musterstraße 123" or "Musterstraße 123a"
'/^(.+?)\s+(\d+[a-zA-Z]?)$/u',
// Pattern 2: "Musterstraße 123-125" or "Musterstraße 123/125"
'/^(.+?)\s+(\d+[-\/]\d+[a-zA-Z]?)$/u',
// Pattern 3: "123 Musterstraße" (number first)
'/^(\d+[a-zA-Z]?)\s+(.+)$/u'
];
foreach ($patterns as $index => $pattern) {
if (preg_match($pattern, $address, $matches)) {
if ($index === 2) {
// Number first pattern
$addressData['address'] = trim($matches[2]);
$addressData['houseNumber'] = trim($matches[1]);
} else {
// Street first patterns
$addressData['address'] = trim($matches[1]);
$addressData['houseNumber'] = trim($matches[2]);
}
break;
}
}
}
// Clean up the address data
$addressData['address'] = trim($addressData['address']);
$addressData['houseNumber'] = trim($addressData['houseNumber']);
}
/**
* Validate address completeness and format
*
* @param array $address
* @return array Validation result with 'valid', 'errors', and 'warnings' keys
*/
private function validateAddress(array $address): array
{
$errors = [];
$warnings = [];
// Required fields
$requiredFields = [
'firstname' => 'Vorname',
'lastname' => 'Nachname',
'address' => 'Straße',
'zipcode' => 'Postleitzahl',
'city' => 'Stadt'
];
foreach ($requiredFields as $field => $label) {
if (empty(trim($address[$field]))) {
$errors[] = "{$label} ist erforderlich.";
}
}
// Name validation
if (empty(trim($address['firstname'])) && empty(trim($address['lastname'])) && empty(trim($address['company']))) {
$errors[] = 'Entweder Name oder Firmenname muss angegeben werden.';
}
// Street number validation
if (!empty($address['address']) && empty($address['houseNumber'])) {
$warnings[] = 'Hausnummer konnte nicht automatisch erkannt werden. Bitte prüfen Sie die Adressangaben.';
}
// Postal code format validation for Germany
if (!empty($address['zipcode']) && $address['country'] && $address['country']->code === 'DE') {
if (!preg_match('/^\d{5}$/', $address['zipcode'])) {
$warnings[] = 'Deutsche Postleitzahl sollte 5 Ziffern haben.';
}
}
// Country validation
if (!$address['country']) {
$errors[] = 'Land konnte nicht ermittelt werden.';
}
return [
'valid' => empty($errors),
'errors' => $errors,
'warnings' => $warnings
];
}
/**
* Get empty address template
*
* @return array
*/
private function getEmptyAddress(): array
{
return [
'firstname' => '',
'lastname' => '',
'company' => '',
'address' => '',
'address_2' => '',
'zipcode' => '',
'city' => '',
'country' => null,
'phone' => '',
'email' => '',
];
}
/**
* Get available countries for shipping
*
* @return \Illuminate\Database\Eloquent\Collection
*/
private function getAvailableCountries()
{
return Country::where('active', 1)->get();
}
/**
* Get available DHL product codes from settings
*
* @return array
*/
private function getAvailableProductCodes(): array
{
// Get DHL configuration with merged settings
$settingController = new \App\Http\Controllers\SettingController();
$dhlConfig = $settingController->getDhlConfig();
$productCodes = [];
// Add products based on configured account numbers
$accountNumbers = $dhlConfig['account_numbers'] ?? [];
if (!empty($accountNumbers['V01PAK'])) {
$productCodes['V01PAK'] = 'DHL Paket National';
}
if (!empty($accountNumbers['V53PAK'])) {
$productCodes['V53PAK'] = 'DHL Paket International';
}
if (!empty($accountNumbers['V62WP'])) {
$productCodes['V62WP'] = 'DHL Warenpost National';
}
if (!empty($accountNumbers['V07PAK'])) {
$productCodes['V07PAK'] = 'DHL Retoure Online';
}
// Fallback to default if no account numbers configured
if (empty($productCodes)) {
$productCodes = [
'V01PAK' => 'DHL Paket National',
'V53PAK' => 'DHL Paket International',
'V62WP' => 'DHL Warenpost National'
];
}
return $productCodes;
}
/**
* Validate shipment parameters before API call
*
* @param array $shipmentData
* @return array Validation result
*/
public function validateShipmentData(array $shipmentData): array
{
$errors = [];
$warnings = [];
// Weight validation
$weight = floatval($shipmentData['weight'] ?? 0);
if ($weight < 0.1) {
$errors[] = 'Gewicht muss mindestens 0.1 kg betragen.';
} elseif ($weight > 31.5) {
$errors[] = 'Gewicht darf maximal 31.5 kg betragen.';
}
// Product code validation
$productCode = $shipmentData['product_code'] ?? '';
$availableProducts = array_keys($this->getAvailableProductCodes());
if (!in_array($productCode, $availableProducts)) {
$errors[] = 'Ungültiger Produktcode ausgewählt.';
}
// Address validation
$requiredAddressFields = [
'shipping_firstname' => 'Vorname',
'shipping_lastname' => 'Nachname',
'shipping_address' => 'Straße',
'shipping_houseNumber' => 'Hausnummer',
'shipping_zipcode' => 'Postleitzahl',
'shipping_city' => 'Stadt',
'shipping_country_id' => 'Land'
];
foreach ($requiredAddressFields as $field => $label) {
if (empty(trim($shipmentData[$field] ?? ''))) {
$errors[] = "{$label} ist erforderlich.";
}
}
return [
'valid' => empty($errors),
'errors' => $errors,
'warnings' => $warnings
];
}
/**
* Prepare address data for DHL API
*
* @param array $formData
* @return array
*/
public function prepareAddressForApi(array $formData): array
{
$country = null;
if (!empty($formData['shipping_country_id'])) {
$country = Country::find($formData['shipping_country_id']);
}
return [
'firstname' => trim($formData['shipping_firstname'] ?? ''),
'lastname' => trim($formData['shipping_lastname'] ?? ''),
'company' => trim($formData['shipping_company'] ?? ''),
'address' => trim($formData['shipping_address'] ?? ''),
'address_2' => trim($formData['shipping_address_2'] ?? ''),
'houseNumber' => trim($formData['shipping_houseNumber'] ?? ''),
'zipcode' => trim($formData['shipping_zipcode'] ?? ''),
'city' => trim($formData['shipping_city'] ?? ''),
'country_id' => $country?->id,
'phone' => trim($formData['shipping_phone'] ?? '')
];
}
}

View file

@ -0,0 +1,147 @@
<?php
namespace App\Services;
use App\Models\ShoppingOrder;
use App\Http\Controllers\SettingController;
use App\Jobs\CreateShipmentJob;
use App\Services\DhlDataHelper;
use Illuminate\Support\Facades\Log;
use Exception;
/**
* DHL Shipment Service
*
* Handles both synchronous and asynchronous shipment creation
* based on configuration settings
*/
class DhlShipmentService
{
/**
* Create a DHL shipment (sync or async based on config)
*
* @param ShoppingOrder $order
* @param float $weight
* @param array $options
* @return array
*/
public function createShipment(ShoppingOrder $order, float $weight = 1.0, array $options = []): array
{
// Get DHL configuration
$settingController = new SettingController();
$dhlConfig = $settingController->getDhlConfig();
\Log::info('dhlConfig', $dhlConfig);
// Check if queue should be used
$useQueue = $dhlConfig['use_queue'] ?? false;
if ($useQueue) {
return $this->createShipmentAsync($order, $weight, $options, $dhlConfig);
} else {
return $this->createShipmentSync($order, $weight, $options, $dhlConfig);
}
}
/**
* Create shipment asynchronously using queue
*
* @param ShoppingOrder $order
* @param float $weight
* @param array $options
* @param array $dhlConfig
* @return array
*/
private function createShipmentAsync(ShoppingOrder $order, float $weight, array $options, array $dhlConfig): array
{
try {
// Dispatch job with pre-loaded config
CreateShipmentJob::dispatch($order, $weight, $options, $dhlConfig);
Log::info('[DHL Service] Shipment creation dispatched to queue', [
'order_id' => $order->id,
'weight' => $weight
]);
return [
'success' => true,
'message' => 'Sendung wird erstellt. Sie erhalten eine Benachrichtigung, sobald das Versandlabel verfügbar ist.',
'queued' => true,
'order_id' => $order->id
];
} catch (Exception $e) {
Log::error('[DHL Service] Failed to dispatch shipment creation', [
'error' => $e->getMessage(),
'order_id' => $order->id,
]);
return [
'success' => false,
'message' => 'Fehler beim Einreihen der Sendungserstellung: ' . $e->getMessage(),
'queued' => false
];
}
}
/**
* Create shipment synchronously
*
* @param ShoppingOrder $order
* @param float $weight
* @param array $options
* @param array $dhlConfig
* @return array
*/
private function createShipmentSync(ShoppingOrder $order, float $weight, array $options, array $dhlConfig): array
{
try {
Log::info('[DHL Service] Creating shipment synchronously', [
'order_id' => $order->id,
'weight' => $weight
]);
// Create DHL client directly
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlConfig['base_url'],
$dhlConfig['api_key'],
$dhlConfig['username'],
$dhlConfig['password']
);
$shippingService = new \Acme\Dhl\Services\ShippingService($dhlClient);
// Prepare order data using helper
$orderData = DhlDataHelper::prepareOrderData($order, $weight, $options, $dhlConfig);
Log::info('orderData', $orderData);
// Create the shipment directly
$result = $shippingService->createLabel($orderData);
Log::info('[DHL Service] Shipment created successfully (sync)', [
'order_id' => $order->id,
'shipment_number' => $result['shipmentNumber'] ?? 'N/A',
'label_path' => $result['labelPath'] ?? 'N/A',
]);
return [
'success' => true,
'message' => 'Versandlabel erfolgreich erstellt!',
'queued' => false,
'order_id' => $order->id,
'shipment_number' => $result['shipmentNumber'] ?? null,
'tracking_number' => $result['trackingNumber'] ?? null,
'label_path' => $result['labelPath'] ?? null,
'label_url' => $result['labelUrl'] ?? null,
];
} catch (Exception $e) {
Log::error('[DHL Service] Shipment creation failed (sync)', [
'order_id' => $order->id,
'error' => $e->getMessage()
]);
return [
'success' => false,
'message' => 'Fehler beim Erstellen des Versandlabels: ' . $e->getMessage(),
'queued' => false,
'order_id' => $order->id
];
}
}
}

View file

@ -126,7 +126,9 @@ class DomainService
$subdomain = null;
if (count($parts) > 2) {
$subdomain = $parts[0];
\Log::debug('DomainService: Using extracted subdomain', ['subdomain' => $subdomain, 'host' => $host]);
if (config('app.debug')) {
\Log::debug('DomainService: Using extracted subdomain', ['subdomain' => $subdomain, 'host' => $host]);
}
}
// Determine domain type based on subdomain and host

View file

@ -270,6 +270,9 @@ class Payment
public static function paymentStatusSendMail(ShoppingOrder $shopping_order, $shopping_payment, $data){
$bcc = [];
$billing_email = $shopping_order->shopping_user->billing_email;
// Überprüfung der Billing-E-Mail-Adresse
if(!$billing_email){
if($data['mode'] === 'test'){
$billing_email = config('app.checkout_test_mail');
@ -277,6 +280,11 @@ class Payment
$billing_email = config('app.checkout_mail');
}
}
if(!filter_var($billing_email, FILTER_VALIDATE_EMAIL)){
\Log::channel('payment')->error("Invalid billing email at shopping_order ".$shopping_order->id, ['billing_email' => $billing_email]);
$billing_email = config('app.checkout_mail');
}
if($data['mode'] === 'test'){
$bcc[] = config('app.checkout_test_mail');
}else{

View file

@ -1,4 +1,5 @@
<?php
namespace App\Services;
use App\Models\Country;
@ -13,7 +14,7 @@ class Util
{
private static $postRoute = 'base.';
public static function getToken()
{
return hash_hmac('sha256', Str::random(40), config('app.key'));
@ -23,87 +24,95 @@ class Util
{
$uuid = (string) Str::uuid();
$e_uuid = explode("-", $uuid);
if(isset($e_uuid[0]) && $e_uuid[1]){
return $e_uuid[0]."-".$e_uuid[1];
if (isset($e_uuid[0]) && $e_uuid[1]) {
return $e_uuid[0] . "-" . $e_uuid[1];
}
return $uuid;
}
public static function formatDate(){
if(\App::getLocale() === "en"){
public static function formatDate()
{
if (\App::getLocale() === "en") {
return 'yyyy-mm-dd';
}
return 'dd.mm.yyyy';
}
public static function formatDateDB(){
if(\App::getLocale() === "en"){
public static function formatDateDB()
{
if (\App::getLocale() === "en") {
return 'Y-m-d';
}
return 'd.m.Y';
}
public static function formatDateTimeDB(){
if(\App::getLocale() === "en"){
public static function formatDateTimeDB()
{
if (\App::getLocale() === "en") {
return 'Y-m-d - H:i';
}
return 'd.m.Y - H:i';
}
public static function _format_number($value){
public static function _format_number($value)
{
return preg_replace("/[^0-9,-]/", "", $value);
}
public static function _thousands_separator(){
return \App::getLocale() === "en" ? ',' : '.';
public static function _thousands_separator()
{
return \App::getLocale() === "en" ? ',' : '.';
}
public static function _decimal_separator(){
return \App::getLocale() === "en" ? '.' : ',';
public static function _decimal_separator()
{
return \App::getLocale() === "en" ? '.' : ',';
}
public static function maxStrLength($str, $length = 40){
public static function maxStrLength($str, $length = 40)
{
if(strlen($str) > $length){
if (strlen($str) > $length) {
$str = substr($str, 0, $length);
//$str = substr($str, 0, strrpos($str, " "));
$str = $str." ...";
$str = $str . " ...";
}
return $str;
}
public static function reFormatNumber($value){
public static function reFormatNumber($value)
{
return (float) str_replace(',', '.', self::_format_number($value));
}
public static function formatNumber($value, $dec=2){
public static function formatNumber($value, $dec = 2)
{
$value = floatval(str_replace(',', '', $value));
return number_format($value, $dec, self::_decimal_separator(), self::_thousands_separator());
}
public static function cleanIntegerFromString($value) {
public static function cleanIntegerFromString($value)
{
// Entferne alle nicht-numerischen Zeichen außer Minus
$cleanStr = preg_replace("/[^0-9-]/", "", $value);
// Konvertiere zu Integer und entferne führende Nullen
$number = (int)$cleanStr;
return $number;
}
public static function cleanNumberFormat($num = 0, $dec = 2, $fullzero = false){
if($fullzero && $num == 0){
public static function cleanNumberFormat($num = 0, $dec = 2, $fullzero = false)
{
if ($fullzero && $num == 0) {
return number_format($num, $dec, self::_decimal_separator(), self::_thousands_separator());
}
return rtrim(rtrim(number_format($num, $dec, self::_decimal_separator(), self::_thousands_separator()),'0'), self::_decimal_separator());
return rtrim(rtrim(number_format($num, $dec, self::_decimal_separator(), self::_thousands_separator()), '0'), self::_decimal_separator());
}
public static function utf8ize( $mixed ) {
public static function utf8ize($mixed)
{
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = self::utf8ize($value);
@ -115,14 +124,17 @@ class Util
}
public static function getPostRoute(){
public static function getPostRoute()
{
return self::$postRoute;
}
public static function setPostRoute($postRoute){
public static function setPostRoute($postRoute)
{
self::$postRoute = $postRoute;
}
public static function getUserShop(){
public static function getUserShop()
{
$shop = session('user_shop');
if (empty($shop) || !is_object($shop)) {
return null;
@ -130,17 +142,19 @@ class Util
return $shop;
}
public static function getDefaultUserShop(){
public static function getDefaultUserShop()
{
$user = \App\User::find(6);
if($user && $user->shop){
if ($user && $user->shop) {
return $user->shop;
}
return false;
}
public static function getAuthUser(){
if(\Session::has('auth_user')){
if($auth_user = \Session::get('auth_user')){
public static function getAuthUser()
{
if (\Session::has('auth_user')) {
if ($auth_user = \Session::get('auth_user')) {
return $auth_user;
}
}
@ -148,91 +162,102 @@ class Util
}
public static function getUserShopIdentifier(){
if(\Session::has('user_shop_identifier')){
if($user_shop_identifier = \Session::get('user_shop_identifier')){
public static function getUserShopIdentifier()
{
if (\Session::has('user_shop_identifier')) {
if ($user_shop_identifier = \Session::get('user_shop_identifier')) {
return $user_shop_identifier;
}
}
return false;
}
public static function getInstanceStatus(){
public static function getInstanceStatus()
{
$identifier = self::getUserShopIdentifier();
if($identifier && \Session::has('user_shop_payment') && \Session::get('user_shop_payment') === 6){
if ($identifier && \Session::has('user_shop_payment') && \Session::get('user_shop_payment') === 6) {
return OrderPaymentService::getInstanceStatus($identifier);
}
return false;
}
public static function setInstanceStatus($status, $lower = true){
public static function setInstanceStatus($status, $lower = true)
{
$identifier = self::getUserShopIdentifier();
if($identifier && \Session::has('user_shop_payment') && \Session::get('user_shop_payment') === 6){
if ($identifier && \Session::has('user_shop_payment') && \Session::get('user_shop_payment') === 6) {
OrderPaymentService::updateInstanceStatus($identifier, $status, $lower);
}
}
public static function setInstanceStatusByPayment($shopping_payment, $status, $lower = true){
if($shopping_payment->identifier){
public static function setInstanceStatusByPayment($shopping_payment, $status, $lower = true)
{
if ($shopping_payment->identifier) {
OrderPaymentService::updateInstanceStatus($shopping_payment->identifier, $status, $lower);
}
}
public static function getShoppingInstance(){
if(\Session::has('shopping_instance')){
public static function getShoppingInstance()
{
if (\Session::has('shopping_instance')) {
return \Session::get('shopping_instance');
}
return false;
}
public static function getUserHistory(){
public static function getUserHistory()
{
$auth_user = self::getAuthUser();
$user_shop_identifier = self::getUserShopIdentifier();
if($user_shop_identifier && $auth_user){
if ($user_shop_identifier && $auth_user) {
return UserHistory::whereUserId($auth_user->id)->whereIdentifier($user_shop_identifier)->get()->last();
}
return false;
}
public static function setUserHistoryValue($values = []){
if($user_history = self::getUserHistory()){
foreach ($values as $key=>$val){
public static function setUserHistoryValue($values = [])
{
if ($user_history = self::getUserHistory()) {
foreach ($values as $key => $val) {
$user_history->{$key} = $val;
}
$user_history->save();
}
}
}
public static function getUserHistoryValue($key){
if($user_history = self::getUserHistory()) {
public static function getUserHistoryValue($key)
{
if ($user_history = self::getUserHistory()) {
return $user_history->{$key};
}
return null;
}
public static function getUserShoppingMode(){
if($auth_user = self::getAuthUser()){
if($auth_user->isTestMode()){
public static function getUserShoppingMode()
{
if ($auth_user = self::getAuthUser()) {
if ($auth_user->isTestMode()) {
return 'test';
}
}
return config('app.mode');
}
public static function addRoute($p = []){
public static function addRoute($p = [])
{
$b = [];
if(\Session::has('user_shop')){
if($user_shop = \Session::get('user_shop')){
if (\Session::has('user_shop')) {
if ($user_shop = \Session::get('user_shop')) {
$b = ['subdomain' => $user_shop->slug];
}
}
return array_merge($p, $b);
}
public static function checkUserLandIsNot($user){
public static function checkUserLandIsNot($user)
{
if(isset($user->account->country_id)){
if (isset($user->account->country_id)) {
//ch schweiz is out
if($user->account->country_id === 6){
if ($user->account->country_id === 6) {
return false;
}
return true;
@ -241,9 +266,10 @@ class Util
}
public static function getMyMivitaShopUrl($add_url = ""){
if(\Session::has('user_shop_domain')){
$url = \Session::get('user_shop_domain').$add_url;
public static function getMyMivitaShopUrl($add_url = "")
{
if (\Session::has('user_shop_domain')) {
$url = \Session::get('user_shop_domain') . $add_url;
if (!str_starts_with($url, 'http')) {
$url = 'https://' . ltrim($url, '/');
}
@ -251,83 +277,90 @@ class Util
}
//alois sein shop
$user = \App\User::find(6);
if($user && $user->shop){
return config('app.protocol').$user->shop->slug.".".config('app.domain').config('app.tld_care').$add_url;
if ($user && $user->shop) {
return config('app.protocol') . $user->shop->slug . "." . config('app.domain') . config('app.tld_care') . $add_url;
}
}
public static function getMyMivitaPortalUrl($protocol = true){
public static function getMyMivitaPortalUrl($protocol = true)
{
$pro = $protocol ? config('app.protocol') : "";
return $pro.config('app.pre_url_portal').config('app.domain').config('app.tld_care');
return $pro . config('app.pre_url_portal') . config('app.domain') . config('app.tld_care');
}
public static function getMyMivitaUrl($protocol = true){
public static function getMyMivitaUrl($protocol = true)
{
$pro = $protocol ? config('app.protocol') : "";
return $pro.config('app.pre_url_crm').config('app.domain').config('app.tld_care');
return $pro . config('app.pre_url_crm') . config('app.domain') . config('app.tld_care');
}
public static function getUserPaymentFor($instance = 'shopping'){
if(Yard::instance($instance)->getYardExtra('user_shop_payment')){
public static function getUserPaymentFor($instance = 'shopping')
{
if (Yard::instance($instance)->getYardExtra('user_shop_payment')) {
return Yard::instance($instance)->getYardExtra('user_shop_payment');
}
if(\Session::has('user_shop_payment')){
if (\Session::has('user_shop_payment')) {
return \Session::get('user_shop_payment');
}
return null;
}
public static function getUserShopBackUrl($reference = ""){
public static function getUserShopBackUrl($reference = "")
{
if(\Session::has('user_shop')){
if(\Session::has('user_shop_domain')){
if (\Session::has('user_shop')) {
if (\Session::has('user_shop_domain')) {
return \Session::get('user_shop_domain');
}
if($user_shop = \Session::get('user_shop')){
return config('app.protocol').$user_shop->slug.".".config('app.domain').config('app.tld_care')."/back/to/shop/".$reference;
if ($user_shop = \Session::get('user_shop')) {
return config('app.protocol') . $user_shop->slug . "." . config('app.domain') . config('app.tld_care') . "/back/to/shop/" . $reference;
}
}
return config('app.protocol').config('app.domain').config('app.tld_care');
return config('app.protocol') . config('app.domain') . config('app.tld_care');
}
public static function getUserCardBackUrl($uri, $instance = 'shopping'){
public static function getUserCardBackUrl($uri, $instance = 'shopping')
{
if(\Session::has('user_shop')){
if(\Session::has('user_shop_domain')){
if(\Session::has('back_link')){
if (\Session::has('user_shop')) {
if (\Session::has('user_shop_domain')) {
if (\Session::has('back_link')) {
return \Session::get('back_link');
}
if(self::getUserPaymentFor($instance) === 3){
return \Session::get('user_shop_domain')."/user/membership";
if (self::getUserPaymentFor($instance) === 3) {
return \Session::get('user_shop_domain') . "/user/membership";
}
if(self::getUserPaymentFor($instance) === 2){
return \Session::get('user_shop_domain')."/user/orders";
if (self::getUserPaymentFor($instance) === 2) {
return \Session::get('user_shop_domain') . "/user/orders";
}
return \Session::get('user_shop_domain');
}
if($user_shop = \Session::get('user_shop')){
return config('app.protocol').$user_shop->slug.".".config('app.domain').config('app.tld_care').$uri;
if ($user_shop = \Session::get('user_shop')) {
return config('app.protocol') . $user_shop->slug . "." . config('app.domain') . config('app.tld_care') . $uri;
}
}
return config('app.protocol').config('app.domain').config('app.tld_care');
return config('app.protocol') . config('app.domain') . config('app.tld_care');
}
public static function isMivitaShop(){
if(Request::getHost() === 'checkout.'.config('app.domain').config('app.tld_care')){
if($user_shop = \Session::get('user_shop')){
if($user_shop->slug === 'aloevera' || $user_shop->slug === 'naturcosmetic'){
public static function isMivitaShop()
{
if (Request::getHost() === 'checkout.' . config('app.domain') . config('app.tld_care')) {
if ($user_shop = \Session::get('user_shop')) {
if ($user_shop->slug === 'aloevera' || $user_shop->slug === 'naturcosmetic') {
return true;
}
}
}
}
if(Request::getHost() === 'naturcosmetic.'.config('app.domain').config('app.tld_care')){
if (Request::getHost() === 'naturcosmetic.' . config('app.domain') . config('app.tld_care')) {
return true;
}
return \Config::get('app.url') === config('app.domain').config('app.tld_shop');
}
return \Config::get('app.url') === config('app.domain') . config('app.tld_shop');
}
public static function isTestSystem($dev = false){
if(\Config::get('app.tld_care') === '.test' || \Config::get('app.tld_shop') === '.lshop'){
if($dev && config('app.debug') !== true){
public static function isTestSystem($dev = false)
{
if (\Config::get('app.tld_care') === '.test' || \Config::get('app.tld_shop') === '.lshop') {
if ($dev && config('app.debug') !== true) {
return false;
}
return true;
@ -347,25 +380,61 @@ class Util
return $size;
}
}
public static function sanitize($string, $force_lowercase = true, $anal = false, $substr = false)
{
$strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
"—", "–", ",", "<", ".", ">", "/", "?");
$strip = array(
"~",
"`",
"!",
"@",
"#",
"$",
"%",
"^",
"&",
"*",
"(",
")",
"_",
"=",
"+",
"[",
"{",
"]",
"}",
"\\",
"|",
";",
":",
"\"",
"'",
"&#8216;",
"&#8217;",
"&#8220;",
"&#8221;",
"&#8211;",
"&#8212;",
"—",
"–",
",",
"<",
".",
">",
"/",
"?"
);
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "_", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
if($substr){
$clean = (strlen($clean) > 20) ? substr($clean,-20) : $clean;
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean;
if ($substr) {
$clean = (strlen($clean) > 20) ? substr($clean, -20) : $clean;
}
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
}
}