Updates to 03-2025

This commit is contained in:
Kevin Adametz 2025-04-01 10:39:21 +02:00
parent 6167273a48
commit 9b54eb0512
348 changed files with 34535 additions and 5774 deletions

View file

@ -1,36 +1,40 @@
<?php
namespace App\Services;
use App\Models\Attribute;
use App\Models\Category;
use App\Models\Country;
use App\Models\Ingredient;
use App\Models\Product;
use App\Models\ShippingCountry;
use App\Models\ShoppingUser;
use App\Models\UserLevel;
use App\User;
use App\Models\Country;
use App\Models\Product;
use App\Models\Category;
use App\Models\LeadType;
use App\Models\Attribute;
use App\Models\UserLevel;
use App\Models\Ingredient;
use App\Models\ShoppingUser;
use App\Models\AttributeType;
use App\Models\ShippingCountry;
use Illuminate\Support\Facades\Auth;
class HTMLHelper
{
private static $months = [
1 => 'Januar',
2 => 'Februar',
3 => 'März',
4 => 'April',
5 => 'Mai',
6 => 'Juni',
7 => 'Juli',
8 => 'August',
9 => 'September',
10 => 'Oktober',
11 => 'November',
12 => 'Dezember',
public static $months = [
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December'
];
private static $roles = [
0 => 'Kunde',
1 => 'Redakteur',
@ -45,6 +49,23 @@ class HTMLHelper
return self::$months[intval($i)];
}
public static function getTransMonths($full = false){
$ret = [];
foreach(self::$months as $key=>$val){
$ret[$key] = trans('cal.months.'.$val);
}
if($full){ //ganzes Jahr
$ret[13] = trans('cal.months.full_year');
}
return $ret;
}
public static function getYearRange($start = 2021)
{
$end = date("Y");
return array_reverse(range($start, $end));
}
public static function getRoleLabel($role_id = 0){
return '<span class="badge badge-pill '.self::getLabel($role_id).'">'.self::$roles[$role_id].'</span>';
}
@ -150,22 +171,68 @@ class HTMLHelper
return $ret;
}
public static function getAttributesWithoutParents($id = false, $sameId = false, $all = true){
$values = Attribute::where('parent_id', null)->get();
public static function getAttributeTypes($id = false){
$values = AttributeType::where('parent_id', null)->where('active', 1)->orderBy('pos', 'asc')->get();
$ret = "";
if($id === false){
$val = $values->first();
$id = $val->id;
}
foreach ($values as $value){
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getProductsWhiteLabelOptions($ids = [], $unsets = [], $type_id = false){
$values = Product::where('whitelabel', 1)->where('active', 1)->get();
$ret = "";
foreach ($values as $value){
if(is_array($unsets) && in_array($value->id, $unsets)){
continue;
}
$attr = (is_array($ids) && in_array($value->id, $ids)) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getAttributesOptions($ids = array(), $all = true, $type_id = false){
if($type_id){
$values = Attribute::where('active', 1)->where('attribute_type_id', $type_id)->get();
}else{
$values = Attribute::where('active', 1)->get();
}
$ret = "";
if($all){
$ret .= '<option value="">'.__('no').'</option>\n';
}
foreach ($values as $value){
if($sameId == $value->id){
continue;
}
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$attr = in_array($value->id, $ids) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getProductAttributesOptions($product_attributes, $ids = [], $all = true, $type_id = false){
$ret = "";
if($all){
$ret .= '<option value="">'.__('no').'</option>\n';
}
foreach ($product_attributes as $product_attribute){
if($product_attribute->attribute){
$attr = (is_array($ids) && in_array($product_attribute->attribute_id, $ids)) ? 'selected="selected"' : '';
$ret .= '<option value="'.$product_attribute->attribute_id.'" '.$attr.'>'.$product_attribute->attribute->name.'</option>\n';
}
}
return $ret;
}
public static function getCategoriesWithoutParents($id = false, $sameId = false, $all = true){
$values = Category::where('parent_id', null)->get();
$ret = "";
@ -211,6 +278,14 @@ class HTMLHelper
return $ret;
}
public static function getCategoriesByShowOn($show_on = []){
$values = Category::where('active', true)->whereJsonContains('show_on', $show_on)->orderBy('pos', 'ASC')->get();
$ret = [];
foreach ($values as $value){
$ret[$value->id] = ['name' => $value->name, 'count' => $value->getProductsCountOn($show_on)];
}
return $ret;
}
public static function getCategoriesOptionsByShowOn($ids = array(), $all = false, $show_on = []){
$values = Category::where('active', true)->whereJsonContains('show_on', $show_on)->orderBy('pos', 'ASC')->get();
$ret = "";
@ -219,7 +294,8 @@ class HTMLHelper
}
foreach ($values as $value){
$attr = in_array($value->id, $ids) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
$count = $value->getProductsCountOn($show_on);
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.' ('.$count.')</option>\n';
}
return $ret;
}
@ -236,14 +312,14 @@ class HTMLHelper
return $ret;
}
public static function getAttributesOptions($ids = array(), $all = true){
$values = Attribute::where('active', 1)->get();
public static function getLeadTypeOptions($id = false, $all = true){
$values = LeadType::where('active', 1)->get();
$ret = "";
if($all){
$ret .= '<option value="">'.__('no').'</option>\n';
}
foreach ($values as $value){
$attr = in_array($value->id, $ids) ? 'selected="selected"' : '';
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;

View file

@ -31,10 +31,18 @@ class Invoice
return "/invoice/".\Carbon::parse($invoice_date)->format('Y/m/');
}
public static function getDeliveryStorageDir($invoice_date){
return "/delivery/".\Carbon::parse($invoice_date)->format('Y/m/');
}
public static function makeInvoiceFilename($invoice_number){
return "Rechnung-".$invoice_number.".pdf";
}
public static function makeDeliveryFilename($invoice_number){
return "Lieferschein-".$invoice_number.".pdf";
}
//invoice
public static function isInvoice(ShoppingOrder $shopping_order){
return isset($shopping_order->invoice['filename']) ? true : false;
}
@ -54,10 +62,27 @@ class Invoice
public static function getNumber($shopping_order){
return isset($shopping_order->invoice['invoice_number']) ? $shopping_order->invoice['invoice_number'] : false;
}
public static function getDownloadURL(ShoppingOrder $shopping_order, $do = false){
// return route('storage_file', [$shopping_order->id, 'cms_download_file', $do]);
//delivery
public static function isDelivery(ShoppingOrder $shopping_order){
return isset($shopping_order->delivery['filename']) ? true : false;
}
public static function getDeliveryFilename($shopping_order){
return isset($shopping_order->delivery['filename']) ? $shopping_order->delivery['filename'] : self::makeDeliveryFilename(self::getDeliveryNumber($shopping_order));
}
public static function getDeliveryDir($shopping_order){
return isset($shopping_order->delivery['dir']) ? $shopping_order->delivery['dir'] : self::getDeliveryStorageDir(self::getDeliveryDate($shopping_order));
}
public static function getDeliveryDate($shopping_order){
return isset($shopping_order->delivery['date']) ? $shopping_order->delivery['date'] : self::getDate($shopping_order);
}
public static function getDeliveryNumber($shopping_order){
return isset($shopping_order->delivery['number']) ? $shopping_order->delivery['number'] : self::getNumber($shopping_order);
}
public static function getDownloadPath(ShoppingOrder $shopping_order, $full = false){
$dir = self::getDir($shopping_order);
$filename = self::getFilename($shopping_order);
@ -67,6 +92,15 @@ class Invoice
return \Storage::disk('public')->path($dir.$filename);
}
public static function getDownloadPathDelivery(ShoppingOrder $shopping_order, $full = false){
$dir = self::getDeliveryDir($shopping_order);
$filename = self::getDeliveryFilename($shopping_order);
if(!$full){
return $dir.$filename;
}
return \Storage::disk('public')->path($dir.$filename);
}
public static function sendInvoiceMail($shopping_order){
$bcc = [];
$billing_email = $shopping_order->shopping_user->billing_email;

34
app/Services/MyLog.php Normal file
View file

@ -0,0 +1,34 @@
<?php
namespace App\Services;
use App\Mail\MailLog;
use Illuminate\Support\Facades\Mail;
class MyLog
{
public static function writeLog($channel = 'payment', $context = 'error', $message = '', $data = []){
switch ($context) {
case 'notice':
\Log::channel($channel)->notice($message.' : '.json_encode($data));
break;
case 'warning':
\Log::channel($channel)->warning($message.' : '.json_encode($data));
break;
case 'info':
\Log::channel($channel)->info($message.' : '.json_encode($data));
break;
default:
\Log::channel($channel)->error($message.' : '.json_encode($data));
break;
}
Mail::to(config('app.exception_mail'))->send(new MailLog($channel, $context, $message, $data));
}
}

245
app/Services/PDFMerger.php Normal file
View file

@ -0,0 +1,245 @@
<?php
namespace App\Services;
use setasign\Fpdi\Fpdi as FPDI;
use setasign\Fpdi\PdfParser\StreamReader;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Response;
class PDFMerger {
/**
* Access the filesystem on an oop base
*
* @var Filesystem
*/
protected $oFilesystem = Filesystem::class;
/**
* Hold all the files which will be merged
*
* @var Collection
*/
protected $aFiles = Collection::class;
/**
* Holds every tmp file so they can be removed during the deconstruction
*
* @var Collection
*/
protected $tmpFiles = Collection::class;
/**
* The actual PDF Service
*
* @var FPDI
*/
protected $oFPDI = FPDI::class;
/**
* The final file name
*
* @var string
*/
protected $fileName = 'undefined.pdf';
/**
* Construct and initialize a new instance
* @param Filesystem $oFilesystem
*/
public function __construct(Filesystem $oFilesystem = null){
$this->oFilesystem = $oFilesystem;
$this->oFPDI = new FPDI();
$this->tmpFiles = collect([]);
$this->init();
}
/**
* The class deconstructor method
*/
public function __destruct() {
$oFilesystem = $this->oFilesystem;
$this->tmpFiles->each(function($filePath) use($oFilesystem){
$oFilesystem->delete($filePath);
});
}
/**
* Initialize a new internal instance of FPDI in order to prevent any problems with shared resources
* Please visit https://www.setasign.com/products/fpdi/manual/#p-159 for more information on this issue
*
* @return self
*/
public function init(){
$this->oFPDI = new FPDI();
$this->aFiles = collect([]);
return $this;
}
/**
* Stream the merged PDF content
*
* @return string
*/
public function stream(){
return $this->oFPDI->Output($this->fileName, 'I');
}
/**
* Download the merged PDF content
*
* @return string
*/
public function download(){
$output = $this->output();
return new Response($output, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $this->fileName . '"',
'Content-Length' => strlen($output),
]);
}
/**
* Save the merged PDF content to the filesystem
*
* @return string
*/
public function save($filePath = null){
return $this->oFilesystem->put($filePath?$filePath:$this->fileName, $this->output());
}
/**
* Get the merged PDF content
*
* @return string
*/
public function output(){
return $this->oFPDI->Output($this->fileName, 'S');
}
/**
* Set the final filename
* @param string $fileName
*
* @return string
*/
public function setFileName($fileName){
$this->fileName = $fileName;
return $this;
}
/**
* Set the final filename
* @param string $string
* @param mixed $pages
* @param mixed $orientation
*
* @return string
*/
public function addString($string, $pages = 'all', $orientation = null){
$filePath = storage_path('tmp/'.Str::random(16).'.pdf');
$this->oFilesystem->put($filePath, $string);
$this->tmpFiles->push($filePath);
return $this->addPDF($filePath, $pages, $orientation);
}
/**
* Add a PDF for inclusion in the merge with a valid file path. Pages should be formatted: 1,3,6, 12-16.
* @param string $filePath
* @param string $pages
* @param string $orientation
*
* @return self
*
* @throws \Exception if the given pages aren't correct
*/
public function addPDF($filePath, $pages = 'all', $orientation = null) {
if (file_exists($filePath)) {
if (!is_array($pages) && strtolower($pages) != 'all') {
throw new \Exception($filePath."'s pages could not be validated");
}
$this->aFiles->push([
'name' => $filePath,
'pages' => $pages,
'orientation' => $orientation
]);
} else {
throw new \Exception("Could not locate PDF on '$filePath'");
}
return $this;
}
/**
* Merges your provided PDFs and outputs to specified location.
* @param string $orientation
*
* @return void
*
* @throws \Exception if there are now PDFs to merge
*/
public function merge($orientation = null) {
$this->doMerge($orientation, false);
}
/**
* Merges your provided PDFs and adds blank pages between documents as needed to allow duplex printing
* @param string $orientation
*
* @return void
*
* @throws \Exception if there are now PDFs to merge
*/
public function duplexMerge($orientation = 'P') {
$this->doMerge($orientation, true);
}
protected function doMerge($orientation, $duplexSafe) {
if ($this->aFiles->count() == 0) {
throw new \Exception("No PDFs to merge.");
}
$oFPDI = $this->oFPDI;
$this->aFiles->each(function($file) use($oFPDI, $orientation, $duplexSafe){
$file['orientation'] = is_null($file['orientation'])?$orientation:$file['orientation'];
$count = $oFPDI->setSourceFile(StreamReader::createByString(file_get_contents($file['name'])));
if ($file['pages'] == 'all') {
for ($i = 1; $i <= $count; $i++) {
$template = $oFPDI->importPage($i);
$size = $oFPDI->getTemplateSize($template);
$autoOrientation = isset($file['orientation']) ? $file['orientation'] : $size['orientation'];
$oFPDI->AddPage($autoOrientation, [$size['width'], $size['height']]);
$oFPDI->useTemplate($template);
}
} else {
foreach ($file['pages'] as $page) {
if (!$template = $oFPDI->importPage($page)) {
throw new \Exception("Could not load page '$page' in PDF '" . $file['name'] . "'. Check that the page exists.");
}
$size = $oFPDI->getTemplateSize($template);
$autoOrientation = isset($file['orientation']) ? $file['orientation'] : $size['orientation'];
$oFPDI->AddPage($autoOrientation, [$size['width'], $size['height']]);
$oFPDI->useTemplate($template);
}
}
if ($duplexSafe && $oFPDI->page % 2) {
$oFPDI->AddPage($file['orientation'], [$size['width'], $size['height']]);
}
});
}
}

View file

@ -89,6 +89,11 @@ class Payment
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_order->txaction).'">'.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
public static function getPaymentForTypeBadge(ShoppingOrder $shopping_order){
return '<span class="badge badge-pill badge-'.$shopping_order->getPaymentForColor().'">'.$shopping_order->getPaymentForType().'</span>';
}
public static function getShoppingPaymentBadge(ShoppingPayment $shopping_payment){
if($shopping_payment->mode === 'test'){
return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_payment->mode).' - '.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
@ -207,14 +212,13 @@ class Payment
}
}
//if the order has action
if($shopping_order->shopping_user->is_from === 'user_order' && $shopping_order->shopping_order_margin){
//is margin -> set paid
$shopping_order->shopping_order_margin->paid = true;
$shopping_order->shopping_order_margin->save();
}
}
//if the order has action
if(($shopping_order->shopping_user->is_from === 'user_order' || $shopping_order->shopping_user->is_from === 'shopping') && $shopping_order->shopping_order_margin){
//is margin -> set paid
$shopping_order->shopping_order_margin->order_paid = true;
$shopping_order->shopping_order_margin->save();
}
return $send_link;
}
@ -326,6 +330,14 @@ class Payment
}
}
public static function handelUserShopOrder(ShoppingOrder $shopping_order){
//no user shop
if($shopping_order->payment_for !== 8 || !$shopping_order->user_shop){
return;
}
// need something to do?
}
//add or remove form credit,
//when done, put it back SalesController
public static function handelUserPayCreditsPromotion(PromotionUserOrder $promotion_user_order, $do){

View file

@ -0,0 +1,269 @@
<?php
namespace App\Services\Stats;
use Carbon\Carbon;
use App\Services\Util;
use App\Models\ShoppingOrder;
class Sales
{
private $month;
private $year;
private $products;
private $objects;
public function __construct()
{
$this->month = 0;
$this->year = 0;
$this->products = [];
$this->objects = [];
}
public function setFilterVars($month = null, $year = null, $products = null){
$this->month = $month ? $month : intval(date('m'));
$this->year = $year ? $year : intval(date('Y'));
$this->products = $products;
}
public function setFilterProducts(){
$ShoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year);
$products = [];
foreach($ShoppingOrders as $ShoppingOrder){
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product && !$shopping_order_item->product->exclude_stats_sales && !isset($products[$shopping_order_item->product->id])){
$products[$shopping_order_item->product->id] = $shopping_order_item->product->name.' # '.
($shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission.' / '.$shopping_order_item->product->partner_commission : 'Staffelrabatt');
}
}
}
return $products;
}
private function getShoppingOrdersBy($month, $year){
if($month == '13'){ //all the year
$date_start = Carbon::parse('01.01.'.$year)->format('Y-m-d H:i:s');
$date_end = Carbon::parse('31.12.'.$year)->endOfMonth()->format('Y-m-d H:i:s');
}else{
$date_start = Carbon::parse('01.'.$month.'.'.$year)->format('Y-m-d H:i:s');
$date_end = Carbon::parse('01.'.$month.'.'.$year)->endOfMonth()->format('Y-m-d H:i:s');
}
return ShoppingOrder::where('paid', 1)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
}
public function getCollection(){
$this->getObjects();
$collection = collect();
foreach($this->objects as $key => $obj){
$collection->push([
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'qty' => $obj['qty'],
'total' => $obj['total'],
'pre_qty' => $obj['pre_qty'],
'pre_total' => $obj['pre_total'],
'single_commission' => $obj['single_commission'],
'value_commission' => $obj['value_commission'],
'partner_commission' => $obj['partner_commission'],
]);
}
return $collection;
}
public function getObjects(){
$this->readObjects();
$this->readObjectsPreview();
return $this->objects;
}
private function readObjects()
{
$shoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year);
$this->objects = [];
$subtotal_full = 0; // gesamtumsatz
$subtotal = 0; // gesamtumsatz ohne rabatte
$discount = 0; // gesamtrabatte
$subtotal_hide = 0; // ausgeschlossene Produkte
foreach($shoppingOrders as $ShoppingOrder){
$subtotal_full += $ShoppingOrder->subtotal_full;
$subtotal += $ShoppingOrder->subtotal;
$discount += $ShoppingOrder->discount;
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if(!in_array($shopping_order_item->product->id, $this->products) && !$shopping_order_item->product->exclude_stats_sales){ //ausschließen der Produkte über filter und exclude_stats_sales
if(isset($this->objects[$shopping_order_item->product->id])){
$qty = intval($this->objects[$shopping_order_item->product->id]['qty'] + $shopping_order_item->qty);
$total = round($this->objects[$shopping_order_item->product->id]['total'] + ($shopping_order_item->price_net * $shopping_order_item->qty), 3);
$this->objects[$shopping_order_item->product->id]['qty'] = $qty;
$this->objects[$shopping_order_item->product->id]['total'] = $total;
}else{
$this->objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'qty' => $shopping_order_item->qty,
'total' => round($shopping_order_item->price_net * $shopping_order_item->qty, 3),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => $shopping_order_item->product->single_commission ? 'Ja' : 'Nein',
'value_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission : '',
'partner_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->partner_commission : '',
];
}
}else{
$subtotal_hide += $shopping_order_item->price_net * $shopping_order_item->qty;
}
}
}
}
$this->objects[9990] = [
'name' => 'Angezeigter Umsatz netto €',
'number' => '',
'qty' => '',
'total' => round($subtotal_full - $subtotal_hide, 2),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9991] = [
'name' => 'Ausgeblendeter Umsatz netto €',
'number' => '',
'qty' => '',
'total' => $subtotal_hide,
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9992] = [
'name' => 'Gesamter Umsatz netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => $subtotal_full,
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9998] = [
'name' => 'Gesamte Rabatte netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => ($discount),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9999] = [
'name' => 'Gesamt netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => ($subtotal),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
//format total
foreach($this->objects as $key => $obj){
$this->objects[$key]['total'] = formatNumber($obj['total']);
}
}
private function readObjectsPreview(){
$shoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year-1);
$subtotal_full = 0; // gesamtumsatz
$subtotal = 0; // gesamtumsatz ohne rabatte
$discount = 0; // gesamtrabatte
$subtotal_hide = 0; // ausgeschlossene Produkte
foreach($shoppingOrders as $ShoppingOrder){
$subtotal_full += $ShoppingOrder->subtotal_full;
$subtotal += $ShoppingOrder->subtotal;
$discount += $ShoppingOrder->discount;
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if(!in_array($shopping_order_item->product->id, $this->products) && !$shopping_order_item->product->exclude_stats_sales){ //ausschließen der Produkte über filter und exclude_stats_sales
if(isset($this->objects[$shopping_order_item->product->id])){ //einsetzen der Zahlen, wenn vorhanden
$qty = intval($this->objects[$shopping_order_item->product->id]['pre_qty'] + $shopping_order_item->qty);
$total = round($this->objects[$shopping_order_item->product->id]['pre_total'] + ($shopping_order_item->price_net * $shopping_order_item->qty), 3);
$this->objects[$shopping_order_item->product->id]['pre_qty'] = $qty;
$this->objects[$shopping_order_item->product->id]['pre_total'] = $total;
}else{ // nicht vorhanden, anlegen
$this->objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'qty' => 0,
'total' => 0,
'pre_qty' => $shopping_order_item->qty,
'pre_total' => round($shopping_order_item->price_net * $shopping_order_item->qty, 3),
'single_commission' => $shopping_order_item->product->single_commission ? 'Ja' : 'Nein',
'value_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission : '',
'partner_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->partner_commission : '',
];
}
}else{
//ausgeschlossene Produkte
$subtotal_hide += $shopping_order_item->price_net * $shopping_order_item->qty;
}
}
}
}
$this->objects[9990]['pre_total'] = round($subtotal_full - $subtotal_hide, 2);
$this->objects[9991]['pre_total'] = $subtotal_hide;
$this->objects[9992]['pre_total'] = $subtotal_full;
$this->objects[9998]['pre_total'] = ($discount);
$this->objects[9999]['pre_total'] = ($subtotal);
//format total
foreach($this->objects as $key => $obj){
$this->objects[$key]['pre_total'] = formatNumber($obj['pre_total']);
}
}
}

View file

@ -0,0 +1,303 @@
<?php
namespace App\Services\Payment;
use App\Models\ShoppingOrderMargin;
use App\Models\UserCreditMargin;
use App\Services\Payment\UserCredits;
use App\Services\UserHelper;
use App\Services\UserMarign;
use Carbon\Carbon;
class UserBot
{
public $users;
public $users_pending;
public function __construct()
{
$this->users = [];
$this->users_pending = [];
}
public function readUserHasCredits(){
//user by m_sponsor_id die Partner Provisionen haben
$usersWithPartnerCommission = $this->getUsersWithPartnerCommission(false);
//user die manuelle Gutschriften haben
$usersWithCreditMargin = $this->getUsersWithCreditMargin();
//user die Shop Provisionen haben
$usersWithShopCommission = $this->getUsersWithShopCommission(false);
// Alle Benutzer zum Array hinzufügen
$allUsers = $usersWithPartnerCommission->concat($usersWithCreditMargin)->concat($usersWithShopCommission);
foreach ($allUsers as $user) {
//prüfe ob der User Account noch aktiv ist
if(UserHelper::isActiveAccountByID($user->user_id)){
$this->addUser($user);
}
}
}
public function readUserHasPendingCredit(){
//sponsor Users von Provisionen die bezahlt wurden die noch im pending sind
$usersWithPartnerCommissionPending = $this->getUsersWithPartnerCommission(true);
$usersWithShopCommissionPending = $this->getUsersWithShopCommission(true);
// Alle Benutzer zum Array hinzufügen
$allUsers = $usersWithPartnerCommissionPending->concat($usersWithShopCommissionPending);
foreach ($allUsers as $user) {
//prüfe ob der User Account noch aktiv ist
if(UserHelper::isActiveAccountByID($user->user_id)){
$this->addUserPending($user);
}
}
}
public function getUsers(){
return $this->users;
}
public function getUsersPending(){
return $this->users_pending;
}
private function addUser($user){
// Prüfen, ob Benutzer bereits existiert
if (!isset($this->users[$user->user_id])) {
$this->users[$user->user_id] = $this->createUserCredit($user);
$this->addCreditItems($user->user_id, false);
}
}
private function addUserPending($user){
// Prüfen, ob Benutzer bereits existiert
if (!isset($this->users_pending[$user->user_id])) {
$this->users_pending[$user->user_id] = $this->createUserCredit($user);
$this->addCreditItems($user->user_id, true);
}
}
private function addCreditItems($user_id, $isPending){
// Partner Provisionen hinzufügen
$this->addPartnerCommissionItems($user_id, $isPending);
// Shop Provisionen hinzufügen
$this->addShopCommissionItems($user_id, $isPending);
// Wenn es nicht ausstehende Credits sind, füge manuelle Gutschriften hinzu
if (!$isPending) {
$this->addCreditMarginItems($user_id);
}
}
private function addPartnerCommissionItems($user_id, $isPending){
$shoppingOrderMargins = UserMarign::getPartnerCommissionItems($user_id, $isPending);
if ($isPending) {
$targetArray = 'users_pending';
} else {
$targetArray = 'users';
}
foreach ($shoppingOrderMargins as $shoppingOrderMargin) {
$entry = $this->createCreditEntry($shoppingOrderMargin);
if ($shoppingOrderMargin->net_partner_commission) {
$entry->price_formatted = $shoppingOrderMargin->getFormattedNetPartnerCommission();
$entry->price = $shoppingOrderMargin->net_partner_commission;
}
$this->{$targetArray}[$user_id]->addItem($entry);
if (!empty($entry->price)) {
$this->{$targetArray}[$user_id]->total += $entry->price;
}
}
}
private function addShopCommissionItems($user_id, $isPending){
$shoppingOrderMargins = UserMarign::getShopCommissionItems($user_id, $isPending);
if ($isPending) {
$targetArray = 'users_pending';
} else {
$targetArray = 'users';
}
foreach ($shoppingOrderMargins as $shoppingOrderMargin) {
$entry = $this->createCreditEntry($shoppingOrderMargin);
$entry->delete = $this->addDeleteButton($shoppingOrderMargin->id, 'shopping_order_margin');
if ($shoppingOrderMargin->net_discount) {
$entry->price_formatted = $shoppingOrderMargin->getFormattedNetDiscount();
$entry->price = $shoppingOrderMargin->net_discount;
}
$this->{$targetArray}[$user_id]->addItem($entry);
if (!empty($entry->price)) {
$this->{$targetArray}[$user_id]->total += $entry->price;
}
}
}
private function addCreditMarginItems($user_id){
$creditMargins = UserMarign::getUserCreditMarginByUserID($user_id);
foreach ($creditMargins as $creditMargin) {
$entry = new \stdClass();
$entry->badge = '<i class="fa fa-plus-circle text-secondary"></i> ';
$entry->link = '';//route('admin_credits_detail', [$creditMargin->id]);
$entry->name = nl2br($creditMargin->message);
$entry->reference = '';
$entry->total = '';
$entry->date = $creditMargin->created_at->format("d.m.Y");
$entry->price_formatted = formatNumber($creditMargin->credit);
$entry->price = $creditMargin->credit;
$entry->delete = $this->addDeleteButton($creditMargin->id, 'user_credit_margin', $creditMargin->deleteTime());
$this->users[$user_id]->addItem($entry);
if (!empty($entry->price)) {
$this->users[$user_id]->total += $entry->price;
}
}
}
private function createCreditEntry($shoppingOrderMargin){
$entry = new \stdClass();
$entry->badge = \App\Services\Payment::getPaymentForTypeBadge($shoppingOrderMargin->shopping_order);
if ($shoppingOrderMargin->shopping_order->payment_for === 7 || $shoppingOrderMargin->shopping_order->payment_for === 8) {
$entry->link = route('admin_sales_customers_detail', [$shoppingOrderMargin->shopping_order->id]);
} else {
$entry->link = route('admin_sales_users_detail', [$shoppingOrderMargin->shopping_order->id]);
}
$entry->name = $shoppingOrderMargin->shopping_order->shopping_user->billing_firstname . " " .
$shoppingOrderMargin->shopping_order->shopping_user->billing_lastname;
$entry->reference = $shoppingOrderMargin->shopping_order->getLastShoppingPayment('reference');
$entry->total = $shoppingOrderMargin->shopping_order->getFormattedTotalWithoutCredit() . "";
$entry->date = $shoppingOrderMargin->shopping_order->created_at->format("d.m.Y");
return $entry;
}
private function addDeleteButton($id, $type, $deleteTime = false){
if($type === 'shopping_order_margin'){
return '<span class="no-line-break">
<a class="btn btn-danger btn-xs" href="'.route('admin_payments_credit_delete', [$id, $type]).'" onclick="return confirm(\'Wirklich löschen?\');">
<i class="ion ion-ios-trash"></i>
</a>
</span>';
}
if($type === 'user_credit_margin'){
if($deleteTime){
return '<span class="no-line-break">
<a class="btn btn-danger btn-xs" href="'.route('admin_payments_credit_delete', [$id, $type]).'" onclick="return confirm(\'Wirklich löschen?\');">
<i class="ion ion-ios-trash"></i>
</a> noch '. $deleteTime .' min.
</span>';
}
}
return '';
}
/**
* Gibt User mit Partner Provisionen zurück
*
* @param bool $isPending True für künftige Provisionen, False für fällige Provisionen
* @return \Illuminate\Database\Eloquent\Collection
*/
private function getUsersWithPartnerCommission(bool $isPending)
{
$query = ShoppingOrderMargin::join('users', 'm_sponsor_id', '=', 'users.id')
->groupBy('m_sponsor_id')
->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('users.id as user_id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')
->whereOrderPaid(true)
->whereOutPaid(false)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->whereNotNull('partner_commission_pending_to');
if ($isPending) {
$query->where('partner_commission_pending_to', '>=', Carbon::now());
} else {
$query->where('partner_commission_pending_to', '<', Carbon::now());
}
return $query->get();
}
/**
* Gibt User mit Shop Provisionen zurück
*
* @param bool $isPending True für künftige Provisionen, False für fällige Provisionen
* @return \Illuminate\Database\Eloquent\Collection
*/
private function getUsersWithShopCommission(bool $isPending)
{
$query = ShoppingOrderMargin::join('users', 'user_id', '=', 'users.id')
->groupBy('user_id')
->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('users.id as user_id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')
->whereOrderPaid(true)
->whereOutPaid(false)
->whereCancellation(false)
->whereMarginPaid(false)
->whereNotNull('margin_pending_to');
if ($isPending) {
$query->where('margin_pending_to', '>=', Carbon::now());
} else {
$query->where('margin_pending_to', '<', Carbon::now());
}
return $query->get();
}
/**
* Gibt User mit manuellen Gutschriften zurück
*
* @return \Illuminate\Database\Eloquent\Collection
*/
private function getUsersWithCreditMargin()
{
return UserCreditMargin::join('users', 'user_id', '=', 'users.id')
->join('user_accounts', 'account_id', '=', 'user_accounts.id')
->select('user_id', 'users.email', 'user_accounts.first_name', 'user_accounts.last_name')
->wherePaid(false)
->get();
}
/**
* Erstellt ein neues UserCredits-Objekt
*
* @param object $user Benutzerdaten
* @return UserCredits
*/
private function createUserCredit($user)
{
$userCredit = new UserCredits();
$userCredit->email = $user->email;
$userCredit->first_name = $user->first_name;
$userCredit->last_name = $user->last_name;
$userCredit->user_id = $user->user_id;
$userCredit->total = 0;
return $userCredit;
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Services\Payment;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderMargin;
use App\Models\UserCreditMargin;
use App\Services\Util;
use Carbon\Carbon;
class UserCredits
{
public $email;
public $first_name;
public $last_name;
public $user_id;
public $items;
public $total;
public function __construct()
{
$this->items = [];
}
public function addItem($entry){
$this->items[] = $entry;
}
}

View file

@ -0,0 +1,103 @@
<?php
namespace App\Services;
use App\Models\ProductImage as ProductImageModel;
use App\Models\Product;
use Request;
class ProductImage {
public static function imageUpload($relation, $model, $upload_type = 'product'){
$route = "/";
if($relation === 'product'){
$route = route('admin_product_edit', [$model->id]);
$storage_path = 'images/product/'.$model->id;
}
if($relation === 'user_wl_product'){
$show = Request::get('show');
$route = route('admin_lead_edit', [$model->user_id])."?show=".$show;
$storage_path = 'images/user_product/'.$model->id;
}
try {
$image = \App\Services\Slim::getImages('images')[0];
if ( isset($image['output']['data']) )
{
// Base64 of the image
$data = $image['output']['data'];
$file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');
if (!isset($file_ex[$image['output']['type']])) {
\Session()->flash('alert-danger', 'File is not jpg or png!');
return redirect($route);
}
$ext = $file_ex[$image['output']['type']];
// Original file name
$name = $image['output']['name'];
$name = \App\Services\Slim::sanitizeFileName($name);
$name = uniqid() . '_' . $name;
$data = \Storage::disk('public')->put(
$storage_path.'/'.$name,
$data
);
ProductImageModel::create([
'product_id' => $relation === 'product' ? $model->id : null,
'user_wl_product_id' => $relation === 'user_wl_product' ? $model->id : null,
'type' => $upload_type,
'filename' => $name,
'original_name' => $image['output']['name'],
'ext' => $ext,
'mine' => $image['output']['type'],
'size' => $image['input']['size']
]);
\Session()->flash('alert-success', "Datei hochgeladen");
return redirect($route);
}
\Session()->flash('alert-danger', "Datei leer");
return redirect($route);
}
catch (\Exception $e) {
\Session()->flash('alert-danger', "Fehler".$e);
return redirect($route);
}
}
public static function imageDelete($relation, $model, $product_image_id, $redirect = true){
$route = "/";
if($relation === 'product'){
$route = route('admin_product_edit', [$model->id]);
$storage_path = 'images/product/'.$model->id;
}
if($relation === 'user_wl_image'){
$show = Request::get('show');
$route = route('admin_lead_edit', [$model->user_id])."?show=".$show;
$storage_path = 'images/user_wl_product/'.$model->id;
}
$product_image = ProductImageModel::findOrFail($product_image_id);
if($product_image->product_id == $model->id || $product_image->user_wl_product_id == $model->id){
$file = $storage_path.'/'.$product_image->filename;
\Storage::disk('public')->delete($file);
$product_image->delete();
\Session()->flash('alert-success', "Datei gelöscht");
return $redirect ? redirect($route) : true;
}
\Session()->flash('alert-danger', "Datei nicht gefunden");
return $redirect ? redirect($route) : true;
}
}

View file

@ -1,14 +1,26 @@
<?php
namespace App\Services;
use App\Models\Country;
use App\Models\ShippingCountry;
use Yard;
use App\User;
use stdClass;
use App\Models\ShoppingUser;
use App\Services\Yard\Margin;
use App\Models\ShippingCountry;
use App\Services\Yard\Commission;
use Gloudemans\Shoppingcart\CartItem;
class Shop
{
public static $user_country;
public static $shipping_country;
public static $user_tax_free;
public static $shipping_free;
public static $user_reverse_charge = false;
public static function userOrders() {
$shopping_users = ShoppingUser::whereHas('shopping_order', function($q) {
$q->where('txaction', 'paid')->OrWhere('txaction', 'appointed')->OrWhere('txaction', 'extern')->OrWhere('txaction', 'invoice_open')->OrWhere('txaction', 'invoice_paid');
@ -43,7 +55,6 @@ class Shop
}
}
public static function getShippingCountryCountryId($shipping_country_id){
$shippingCountry = ShippingCountry::find($shipping_country_id);
if($shippingCountry && $shippingCountry->country){
@ -57,10 +68,258 @@ class Shop
if($shippingCountry){
return $shippingCountry->id;
}
if($ShippingCountry = ShippingCountry::all()->first()){
$ShippingCountry->id;
}
return 1;
return ShippingCountry::all()->first()->id;
}
public static function initUserShopLang($country){
Yard::instance('shopping')->destroy();
\Session::put('user_shop_lang', strtolower($country->code));
//init Yard
self::initUserShopYard($country);
}
public static function initUserShopYard($country){
//Lieferadresse im Drittland?
self::$user_tax_free = $country->supply_country ? true : false;
$ShippingCountry = ShippingCountry::whereCountryId($country->id)->first();
self::$shipping_free = $ShippingCountry->shipping->free;
self::$shipping_country = $ShippingCountry;
self::$user_country = $country;
Yard::instance('shopping')->setShippingCountryWithPrice($ShippingCountry->id);
Yard::instance('shopping')->setUserPriceInfos(Shop::getShopYardInfo());
}
public static function getShopYardInfo(){
return [
'user_tax_free' => self::$user_tax_free,
'shipping_free' => self::$shipping_free,
'user_reverse_charge' => self::$user_reverse_charge,
'user_country_id' => self::$user_country->id,
'shipping_country_id' => self::$shipping_country->id,
];
}
public static function checkShoppingUser($id, $user){
if($id === null){
abort(403, 'Error: Keine User ID');
}
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->member_id !== $user->id){
abort(403, 'Error: Falsche User ID');
}
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->is_like){
abort(403, 'Error: Kunde in Prüfung');
}
return $shopping_user;
}
public static function checkShoppingCountry($for, $id=null){
$country_id = null;
if($for === 'me' || $for === 'mp' || $for === 'cr'){
$user = User::find(\Auth::user()->id);
if($user->account->same_as_billing){
$country_id = $user->account->country_id;
}else{
$country_id = $user->account->shipping_country_id;
}
}
if(strpos($for, 'ot') !== false && $id){
$shopping_user = ShoppingUser::findOrFail($id);
if($shopping_user->same_as_billing){
$country_id = $shopping_user->billing_country->id;
}else{
$country_id = $shopping_user->shipping_country->id;
}
}
if($country_id){
if($shipping_country = ShippingCountry::whereCountryId($country_id)->first()){
if($shipping_country->shipping && $shipping_country->shipping->active){
return $shipping_country->id;
}
}
}
return false;
}
public static function getShippingPriceByShippingCountryId($shipping_country_id, $shipping_weight){
$shippingCountry = ShippingCountry::find($shipping_country_id);
if(!$shippingCountry){
abort(403, 'Fehler: Versandland nicht gefunden');
}
if(!isset($shippingCountry->shipping) && count($shippingCountry->shipping->shipping_prices) === 0){
abort(403, 'Fehler: Kein Preise für das Versandland angelegt');
}
$shipping_price = $shippingCountry->shipping->shipping_prices->first();
if(!$shipping_price){
abort(403, 'Fehler: Preis vom Versandland nicht gefunden');
}
/*if(!$shipping_weight){
abort(403, 'Fehler: Kein Versandgewicht');
}*/
if($shipping_weight == 0){
$shipping_price->price = 0;
$shipping_price->price_comp = 0;
return $shipping_price;
}
if($shipping_weight > 0){
/*
if($this->shipping_free && $this->total(2, '.', '') >= $this->shipping_free){
if($this->weightByFreeShipping() == 0){
$shipping_price->price = 0;
$shipping_price->price_comp = 0;
}else{
$shipping_price = $this->shippingPriceByWeight($shipping->shipping_prices, $this->weightByFreeShipping());
}
}else{
*/
return self::shippingPriceByWeight($shippingCountry->shipping->shipping_prices, $shipping_weight);
}
/*if($this->weight() == 0){
}else{
$shipping_price = $this->shippingPriceByWeight($shipping->shipping_prices, $this->weight());
//first by price
//$shipping_price = $this->shippingPriceByTotal($shipping->shipping_prices, $this->total(2, '.', ''));
//sec by weight
//if(!$shipping_price){
//}
}
//default
}*/
}
public static function shippingPriceByWeight($shipping_prices, $shipping_weight){
foreach ($shipping_prices as $price){
if($price->weight_from == 0 && $price->weight_to == 0){
return $price;
}
if($price->weight_from > 0 && $price->weight_to > 0){
if($shipping_weight >= $price->weight_from && $shipping_weight <= $price->weight_to){
return $price;
}
}
}
abort(403, 'Fehler: Preis nach Gewicht im Versandland nicht gefunden');
}
public static function calculateUserShopMargins($userShop = null, $promotionUser = null){ //'shop' or 'prom'
// return;
if($userShop){
$user = $userShop->user;
}
if($promotionUser){
$user = $promotionUser->user;
}
if(!isset($user)){
return;
}
Yard::setUser($user);
//get user monthy amount
$monthy_amount = UserMarign::getMontlyAmount($user);
$content = Yard::getCartContent();
/*single + partner Commissions */
//get price net commission, add amount, partner (total) from products is single_commission
$yard_commission = new Commission();
$yard_commission = $content->reduce(function ($yard_commission, CartItem $cartItem) {
$price_net = $cartItem->price / ((100 + $cartItem->taxRate) / 100);
//nicht vom Staffelrabatt -> extra Rabatt / Provision
if($cartItem->options->single_commission){
$value_commission = $price_net / 100 * $cartItem->options->value_commission;
$partner_commission = $price_net / 100 * $cartItem->options->partner_commission;
$price_net_commission = ($cartItem->qty * $price_net) - ($cartItem->qty * $value_commission);
$yard_commission->single_price_net += ($cartItem->qty * $price_net);
$yard_commission->single_value_commission += ($cartItem->qty * $value_commission);
if(Yard::sponsorHasCommisson()){
$yard_commission->single_partner_commission += ($cartItem->qty * $partner_commission);
}
$yard_commission->single_price_net_commission += $price_net_commission;
//
if($cartItem->options->amount_commission){
$yard_commission->single_amount_commission += $price_net_commission;
}
}else{
$yard_commission->price_net = $yard_commission->price_net + ($cartItem->qty * $price_net);
}
return $yard_commission;
}, $yard_commission);
//dump($monthy_amount);
//add to $monthy_amount für max level margins
$start_monthy_amount = $monthy_amount + $yard_commission->single_amount_commission;
$end_monthy_amount = $start_monthy_amount + $yard_commission->price_net;
//dump($start_monthy_amount);
//dump($end_monthy_amount);
$margin = new Margin();
$rest_amount = 0;
$range = 0;
$price_net = $yard_commission->price_net;
if($yard_commission->price_net > 0 && $user && $user->user_level && $user->user_level->user_level_margins){
foreach ($user->user_level->user_level_margins_re as $user_level_margin) {
//total split?
if ($end_monthy_amount >= $user_level_margin->price_from) {
if(!isset($balance)){
if($start_monthy_amount >= $user_level_margin->price_from){
$balance = $yard_commission->price_net;
$rest_amount = 0;
}else{
$balance = $end_monthy_amount - $user_level_margin->price_from;
$rest_amount = $end_monthy_amount - ($start_monthy_amount + $balance);
}
}else{
if(isset($last_limit)){
$range = $last_limit - $user_level_margin->price_from;
if($rest_amount >= $range){
$balance = $range;
}else{
$balance = $rest_amount;
}
$rest_amount = $rest_amount - $balance;
}
}
$last_limit = $user_level_margin->price_from;
if($balance != 0){
$commission = 0;
if($user->sponsorHasCommisson()){
$commission = $user_level_margin->commission;
}
$margin->add($user_level_margin->price_from, [
'price_net' => $price_net,
'range' => $range,
'rest_amount' => $rest_amount,
'balance' => $balance,
'trading_margin' => $user_level_margin->trading_margin,
'commission' => $commission,
]);
}
}
}
}
$margin->setCommission($yard_commission);
$margin->calculate();
//$this->yard_margin = $margin;
$ret = new stdClass();
$ret->yard_margin = $margin;
$ret->yard_commission = $yard_commission;
return $ret;
}
}

View file

@ -0,0 +1,269 @@
<?php
namespace App\Services\Stats;
use Carbon\Carbon;
use App\Services\Util;
use App\Models\ShoppingOrder;
class Sales
{
private $month;
private $year;
private $products;
private $objects;
public function __construct()
{
$this->month = 0;
$this->year = 0;
$this->products = [];
$this->objects = [];
}
public function setFilterVars($month = null, $year = null, $products = null){
$this->month = $month ? $month : intval(date('m'));
$this->year = $year ? $year : intval(date('Y'));
$this->products = $products;
}
public function setFilterProducts(){
$ShoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year);
$products = [];
foreach($ShoppingOrders as $ShoppingOrder){
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product && !$shopping_order_item->product->exclude_stats_sales && !isset($products[$shopping_order_item->product->id])){
$products[$shopping_order_item->product->id] = $shopping_order_item->product->name.' # '.
($shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission.' / '.$shopping_order_item->product->partner_commission : 'Staffelrabatt');
}
}
}
return $products;
}
private function getShoppingOrdersBy($month, $year){
if($month == '13'){ //all the year
$date_start = Carbon::parse('01.01.'.$year)->format('Y-m-d H:i:s');
$date_end = Carbon::parse('31.12.'.$year)->endOfMonth()->format('Y-m-d H:i:s');
}else{
$date_start = Carbon::parse('01.'.$month.'.'.$year)->format('Y-m-d H:i:s');
$date_end = Carbon::parse('01.'.$month.'.'.$year)->endOfMonth()->format('Y-m-d H:i:s');
}
return ShoppingOrder::where('paid', 1)->where('mode', 'live')->whereBetween('created_at', [$date_start, $date_end])->get();
}
public function getCollection(){
$this->getObjects();
$collection = collect();
foreach($this->objects as $key => $obj){
$collection->push([
'id' => $key,
'name' => $obj['name'],
'number' => $obj['number'],
'qty' => $obj['qty'],
'total' => $obj['total'],
'pre_qty' => $obj['pre_qty'],
'pre_total' => $obj['pre_total'],
'single_commission' => $obj['single_commission'],
'value_commission' => $obj['value_commission'],
'partner_commission' => $obj['partner_commission'],
]);
}
return $collection;
}
public function getObjects(){
$this->readObjects();
$this->readObjectsPreview();
return $this->objects;
}
private function readObjects()
{
$shoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year);
$this->objects = [];
$subtotal_full = 0; // gesamtumsatz
$subtotal = 0; // gesamtumsatz ohne rabatte
$discount = 0; // gesamtrabatte
$subtotal_hide = 0; // ausgeschlossene Produkte
foreach($shoppingOrders as $ShoppingOrder){
$subtotal_full += $ShoppingOrder->subtotal_full;
$subtotal += $ShoppingOrder->subtotal;
$discount += $ShoppingOrder->discount;
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if(!in_array($shopping_order_item->product->id, $this->products) && !$shopping_order_item->product->exclude_stats_sales){ //ausschließen der Produkte über filter und exclude_stats_sales
if(isset($this->objects[$shopping_order_item->product->id])){
$qty = intval($this->objects[$shopping_order_item->product->id]['qty'] + $shopping_order_item->qty);
$total = round($this->objects[$shopping_order_item->product->id]['total'] + ($shopping_order_item->price_net * $shopping_order_item->qty), 3);
$this->objects[$shopping_order_item->product->id]['qty'] = $qty;
$this->objects[$shopping_order_item->product->id]['total'] = $total;
}else{
$this->objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'qty' => $shopping_order_item->qty,
'total' => round($shopping_order_item->price_net * $shopping_order_item->qty, 3),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => $shopping_order_item->product->single_commission ? 'Ja' : 'Nein',
'value_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission : '',
'partner_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->partner_commission : '',
];
}
}else{
$subtotal_hide += $shopping_order_item->price_net * $shopping_order_item->qty;
}
}
}
}
$this->objects[9990] = [
'name' => 'Angezeigter Umsatz netto €',
'number' => '',
'qty' => '',
'total' => round($subtotal_full - $subtotal_hide, 2),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9991] = [
'name' => 'Ausgeblendeter Umsatz netto €',
'number' => '',
'qty' => '',
'total' => $subtotal_hide,
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9992] = [
'name' => 'Gesamter Umsatz netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => $subtotal_full,
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9998] = [
'name' => 'Gesamte Rabatte netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => ($discount),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
$this->objects[9999] = [
'name' => 'Gesamt netto € (alle Verkäufe)',
'number' => '',
'qty' => '',
'total' => ($subtotal),
'pre_qty' => 0,
'pre_total' => 0,
'single_commission' => '',
'value_commission' => '',
'partner_commission' => '',
];
//format total
foreach($this->objects as $key => $obj){
$this->objects[$key]['total'] = formatNumber($obj['total']);
}
}
private function readObjectsPreview(){
$shoppingOrders = $this->getShoppingOrdersBy($this->month, $this->year-1);
$subtotal_full = 0; // gesamtumsatz
$subtotal = 0; // gesamtumsatz ohne rabatte
$discount = 0; // gesamtrabatte
$subtotal_hide = 0; // ausgeschlossene Produkte
foreach($shoppingOrders as $ShoppingOrder){
$subtotal_full += $ShoppingOrder->subtotal_full;
$subtotal += $ShoppingOrder->subtotal;
$discount += $ShoppingOrder->discount;
foreach($ShoppingOrder->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if(!in_array($shopping_order_item->product->id, $this->products) && !$shopping_order_item->product->exclude_stats_sales){ //ausschließen der Produkte über filter und exclude_stats_sales
if(isset($this->objects[$shopping_order_item->product->id])){ //einsetzen der Zahlen, wenn vorhanden
$qty = intval($this->objects[$shopping_order_item->product->id]['pre_qty'] + $shopping_order_item->qty);
$total = round($this->objects[$shopping_order_item->product->id]['pre_total'] + ($shopping_order_item->price_net * $shopping_order_item->qty), 3);
$this->objects[$shopping_order_item->product->id]['pre_qty'] = $qty;
$this->objects[$shopping_order_item->product->id]['pre_total'] = $total;
}else{ // nicht vorhanden, anlegen
$this->objects[$shopping_order_item->product->id] = [
'name' => $shopping_order_item->product->name,
'number' => $shopping_order_item->product->number,
'qty' => 0,
'total' => 0,
'pre_qty' => $shopping_order_item->qty,
'pre_total' => round($shopping_order_item->price_net * $shopping_order_item->qty, 3),
'single_commission' => $shopping_order_item->product->single_commission ? 'Ja' : 'Nein',
'value_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->value_commission : '',
'partner_commission' => $shopping_order_item->product->single_commission ? $shopping_order_item->product->partner_commission : '',
];
}
}else{
//ausgeschlossene Produkte
$subtotal_hide += $shopping_order_item->price_net * $shopping_order_item->qty;
}
}
}
}
$this->objects[9990]['pre_total'] = round($subtotal_full - $subtotal_hide, 2);
$this->objects[9991]['pre_total'] = $subtotal_hide;
$this->objects[9992]['pre_total'] = $subtotal_full;
$this->objects[9998]['pre_total'] = ($discount);
$this->objects[9999]['pre_total'] = ($subtotal);
//format total
foreach($this->objects as $key => $obj){
$this->objects[$key]['pre_total'] = formatNumber($obj['pre_total']);
}
}
}

View file

@ -14,6 +14,7 @@ class Type
4 => 'Nur Mitgliedschaft Vertriebspartner',
//5 => 'Onboarding Vertriebspartner',
6 => 'Guthaben aufladen',
8 => 'Shop',
7 => 'zur internen Berechnung',
];
@ -25,7 +26,10 @@ class Type
4 => 'Registrierung Vertriebspartner',
5 => 'Mitgliedschaft Vertriebspartner',
6 => 'Guthaben aufladen',
8 => 'Shop',
10 => 'zur internen Berechnung',
11 => 'Kompensationprodukt beim Versand',
];
@ -50,4 +54,13 @@ class Type
];
public static $shoppingIsFor = [
'ME' => 'Ware ist für mich und wird an meine Adresse versandt',
'OT' => 'Ware ist für einen Kunden und wird an den Kunden versandt',
'MP' => 'Ware ist für mich und ich hole die Ware selbst ab',
'CR' => 'Mein Guthaben aufladen',
'pr' => 'promoation',
'us' => 'shops',
];
}

View file

@ -5,7 +5,8 @@ use Yard;
use App\Models\Product;
use App\Models\ShippingCountry;
class PromotionCart
class UserCart
{
public static $points = 0;
@ -13,18 +14,25 @@ class PromotionCart
public static $price_net = 0;
public static $ek_price = 0;
public static $income_price = 0;
public static $max_qty= 100;
public static $yard_margin;
public static $yard_commission;
public static function initYard(){
public static function initYard($for='shop', $userShop = null, $promotionUser = null){
$id = 1;
if($ShippingCountry = ShippingCountry::all()->first()){
$id = $ShippingCountry->id;
}
Yard::instance('shopping')->setShippingCountryWithPrice($id, 'shop');
// Yard::instance('shopping')->destroy();
Yard::instance('shopping')->setShippingCountryWithPrice($id, $for); //'shop' or 'prom'
}
public static function getCurrentShippingPrice($shipping_for = 2) //shipping_for === microsite
public static function getCurrentShippingPrice($shipping_for = 2) //shipping_for === 2 promotion , 3 shop
{
$shipping = Yard::instance('shopping')->shipping();
if($shipping > 0){
@ -56,19 +64,19 @@ class PromotionCart
}
public static function changeStateShipping($data)
public static function changeStateShipping($data, $for='shop')
{
$id = 1;
if($ShippingCountry = ShippingCountry::find($data['shipping_country_id'])){
$id = $ShippingCountry->id;
}
Yard::instance('shopping')->setShippingCountryWithPrice($id, 'shop');
Yard::instance('shopping')->setShippingCountryWithPrice($id, $for); //'shop' or 'prom'
}
public static function updateProduct($data, $add=false)
public static function updateProduct($data, $add=false, $minus=false)
{
if($product = Product::find($data['product_id'])){
$image = "";
@ -76,23 +84,46 @@ class PromotionCart
$image = $product->images->first()->slug;
}
//get the card item
//get the card item or add 1
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, $product->price, $product->tax,
[
'image' => $image,
'slug' => $product->slug,
'weight' => $product->weight,
'single_commission' => $product->single_commission,
'amount_commission' => $product->amount_commission,
'value_commission' => $product->value_commission,
'partner_commission' => $product->partner_commission,
]);
Yard::setTax($cartItem->rowId, $product->tax);
if(!$add){
Yard::setTax($cartItem->rowId, $product->tax);
//remove one from Card or remove it
if($minus){
if(intval($cartItem->qty) <= 2){
Yard::instance('shopping')->update($cartItem->rowId, intval($cartItem->qty)-2);
//Yard::instance('shopping')->remove($cartItem->rowId);
}else{
// > 1
Yard::instance('shopping')->update($cartItem->rowId, intval($cartItem->qty)-2);
}
}
//update Card set product by qty or remove it
if(!$add && !$minus){
if(isset($data['qty']) && $data['qty'] > 0){
Yard::instance('shopping')->update($cartItem->rowId, $data['qty']);
}else{
//if 0 get the item by qty:1 and remove it
Yard::instance('shopping')->remove($cartItem->rowId);
Yard::instance('shopping')->update($cartItem->rowId, $data['qty']);
//Yard::instance('shopping')->remove($cartItem->rowId);
}
}
//max 100
if($cartItem->qty > self::$max_qty){
Yard::instance('shopping')->update($cartItem->rowId, self::$max_qty);
}
Yard::instance('shopping')->reCalculate();
return $cartItem->qty;
}
@ -117,12 +148,16 @@ class PromotionCart
}
$cartItem = Yard::instance('shopping')->add($product->id, $product->getLang('name'), 1, 0, 0,
[
'image' => $image,
'slug' => $product->slug,
//'weight' => $product->weight,
'weight' => 1,
'free_product_id' => intval($data['free_product_id']),
'product_id' => $product->id
'image' => $image,
'slug' => $product->slug,
//'weight' => $product->weight,
'weight' => 1,
'free_product_id' => intval($data['free_product_id']),
'product_id' => $product->id,
'single_commission' => 0,
'amount_commission' => 0,
'value_commission' => 0,
'partner_commission' => 0,
]);
Yard::setTax($cartItem->rowId, 0);
Yard::instance('shopping')->reCalculate();
@ -131,5 +166,4 @@ class PromotionCart
}
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace App\Services;
use App\User;
use Carbon\Carbon;
class UserHelper
{
public static $user_country;
public static $shipping_country;
public static $shipping_free = false;
public static $user_tax_free = false;
public static $user_reverse_charge = false;
public static function isActive(User $user){
return ($user->active == 1 && $user->blocked == 0) ? true : false;
}
public static function isActiveAccount(User $user){
if(self::isActive($user) && $user->payment_account){
return Carbon::parse($user->payment_account)->gt(Carbon::now());
}
return false;
}
public static function isActiveAccountByID($user_id){
$user = User::find($user_id);
return self::isActiveAccount($user);
}
public static function isActiveByID($user_id){
$user = User::find($user_id);
return self::isActive($user);
}
}

View file

@ -18,7 +18,7 @@ class UserMarign
$sum_net_amount = ShoppingOrderMargin::whereUserId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->sum('net_price');
if($format){
@ -35,7 +35,7 @@ class UserMarign
$sum_net_amount = ShoppingOrderMargin::whereUserId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(false)
->whereOrderPaid(false)
->whereCancellation(false)
->sum('net_price');
if($format){
@ -52,7 +52,7 @@ class UserMarign
$sum_net_amount = ShoppingOrderMargin::whereUserId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->sum('net_amount');
if($format){
@ -73,7 +73,7 @@ class UserMarign
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->sum('net_partner_commission');
if($format){
@ -99,7 +99,7 @@ class UserMarign
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '<', Carbon::now())
@ -109,11 +109,37 @@ class UserMarign
}
return $sum_net_amount;
}
public static function getMontlyPartnerCommissionPending(User $user, $date = null, $format = false){
if(!$date){
$start = Carbon::parse('01.01.2021');
$end = Carbon::now();
$startDay = $start->startOfMonth()->toDateString();
$endDay = $end->endOfMonth()->toDateString();
}else{
$now = $date ? Carbon::parse($date) : Carbon::now();
$startDay = $now->startOfMonth()->toDateString();
$endDay = $now->endOfMonth()->toDateString();
}
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user->id)
->whereBetween('from', [$startDay, $endDay])
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '>=', Carbon::now())
->sum('net_partner_commission');
if($format){
$sum_net_amount = Util::formatNumber($sum_net_amount);
}
return $sum_net_amount;
}
/*
public static function getMontlyPartnerCommissionOpenByID($user_id, $date = null, $format = false, $addUserCreditMargin = false){
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user_id)
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '<', Carbon::now())
@ -131,38 +157,14 @@ class UserMarign
return $sum_net_amount;
}
*/
public static function getMontlyPartnerCommissionPending(User $user, $date = null, $format = false){
if(!$date){
$start = Carbon::parse('01.01.2021');
$end = Carbon::now();
$startDay = $start->startOfMonth()->toDateString();
$endDay = $end->endOfMonth()->toDateString();
}else{
$now = $date ? Carbon::parse($date) : Carbon::now();
$startDay = $now->startOfMonth()->toDateString();
$endDay = $now->endOfMonth()->toDateString();
}
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user->id)
->whereBetween('from', [$startDay, $endDay])
->wherePaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '>=', Carbon::now())
->sum('net_partner_commission');
if($format){
$sum_net_amount = Util::formatNumber($sum_net_amount);
}
return $sum_net_amount;
}
/*
public static function getMontlyPartnerCommissionPendingByID($user_id, $date = null, $format = false){
$sum_net_amount = ShoppingOrderMargin::whereMSponsorId($user_id)
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '>=', Carbon::now())
@ -173,33 +175,53 @@ class UserMarign
return $sum_net_amount;
}
*/
public static function getPartnerCommissionItems($user_id, $isPending = false){
public static function getOrderFromPartnerCommissionByID($user_id){
$ShoppingOrderMargins = ShoppingOrderMargin::whereMSponsorId($user_id)
->wherePaid(true)
$query = ShoppingOrderMargin::whereMSponsorId($user_id)
->whereOrderPaid(true)
->whereOutPaid(false)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '<', Carbon::now())
->get();
return $ShoppingOrderMargins;
->whereNotNull('partner_commission_pending_to');
if ($isPending) {
$query->where('partner_commission_pending_to', '>=', Carbon::now());
} else {
$query->where('partner_commission_pending_to', '<', Carbon::now());
}
return $query->get();
}
public static function getUserCreditMarginByID($user_id){
public static function getShopCommissionItems($user_id, $isPending = false){
$UserCreditMargin = UserCreditMargin::whereUserId($user_id)
->wherePaid(false)
->get();
return $UserCreditMargin;
$query = ShoppingOrderMargin::whereUserId($user_id)
->whereOrderPaid(true)
->whereOutPaid(false)
->whereCancellation(false)
->whereMarginPaid(false)
->whereNotNull('margin_pending_to');
if ($isPending) {
$query->where('margin_pending_to', '>=', Carbon::now());
} else {
$query->where('margin_pending_to', '<', Carbon::now());
}
return $query->get();
}
public static function getOrderFromPartnerCommissionPendingByID($user_id){
public static function getUserCreditMarginByUserID($user_id){
$query = UserCreditMargin::whereUserId($user_id)
->wherePaid(false);
return $query->get();
}
/*public static function getOrderFromPartnerCommissionPendingByID($user_id){
$ShoppingOrderMargins = ShoppingOrderMargin::whereMSponsorId($user_id)
->wherePaid(true)
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->where('partner_commission_pending_to', '>=', Carbon::now())
@ -207,4 +229,19 @@ class UserMarign
return $ShoppingOrderMargins;
}
*/
/*
public static function getOrderFromShopPendingByID($user_id){
$ShoppingOrderMargins = ShoppingOrderMargin::whereUserId($user_id)
->whereOrderPaid(true)
->whereCancellation(false)
->wherePartnerCommissionPaid(false)
->whereIn('status', [7, 8])
->where('partner_commission_pending_to', '>=', Carbon::now())
->get();
return $ShoppingOrderMargins;
}
*/
}

View file

@ -1,12 +1,20 @@
<?php
namespace App\Services;
use Yard;
use App\User;
use App\Models\PromotionUser;
use App\Models\ShippingCountry;
class UserService
{
public static $user_country;
public static $shipping_country;
public static $shipping_free = false;
public static $user_tax_free = false;
public static $user_reverse_charge = false;
public static function createConfirmationCode() {
$unique = false;
do{
@ -19,6 +27,136 @@ class UserService
return $confirmation_code;
}
public static function getTransChange(){
$langs = config('localization.supportedLocales');
$ret = [];
foreach($langs as $code => $lang){
$ret[strtolower($code)] = strtolower($lang['native']);
}
return $ret;
}
public static function initCustomerYard($shopping_user, $for){
self::$user_tax_free = false;
if($shopping_user->same_as_billing){
self::$user_country = $shopping_user->billing_country;
self::$shipping_country = $shopping_user->billing_country;
}else{
self::$user_country = $shopping_user->billing_country;
self::$shipping_country = $shopping_user->shipping_country;
}
if(self::$user_country->supply_country && self::$shipping_country->supply_country){
self::$user_tax_free = true;
}
$ShippingCountry = ShippingCountry::whereCountryId(self::$shipping_country->id)->first();
self::$shipping_free = $ShippingCountry->shipping ? $ShippingCountry->shipping->free : false;
self::$shipping_free = self::$shipping_free !== null ? self::$shipping_free : false;
Yard::instance('shopping')->setShippingCountryWithPrice($ShippingCountry->id, $for);
Yard::instance('shopping')->setUserPriceInfos(self::getYardInfo());
}
public static function initUserYard(User $user, $shipping_country_id, $for){
self::$shipping_free = false;
self::checkUserTaxShippingCountry($user, $shipping_country_id,);
Yard::instance('shopping')->setShippingCountryWithPrice($shipping_country_id, $for);
Yard::instance('shopping')->setUserPriceInfos(self::getYardInfo());
}
public static function checkUserTaxShippingCountry(User $user, $shipping_country_id) {
if(!$user->account || !$user->account->country_id){
abort(403, 'Error: User hat kein Land!');
}
$ShippingCountry = ShippingCountry::findOrFail($shipping_country_id);
self::$user_tax_free = self::performUserTaxShippingCountry($user, $ShippingCountry);
return $ShippingCountry;
/*
dump( self::$user_price_code );
dump( self::$user_tax_free );
dump( self::$user_reverse_charge );
*/
}
public static function performUserTaxShippingCountry($user, $ShippingCountry){
//preise für das Land
self::$user_country = $user->account->country;
self::$shipping_country = $ShippingCountry->country;
//ausgehend vom Land des Rechnungsempfänger $user->account->country
//ist der Rechnungsempfänger im Drittland?
if($user->account->country->supply_country){
if($ShippingCountry->country->supply_country){
//Lieferadresse im Drittland?
return true;
}
}
//Rechnungsempfänger in der EU
//Lieferland mit RSV
if($ShippingCountry->country->eu_country){
//Rechnungsempfänger mit valid aktiv RSV
if($user->account->reverse_charge && $user->account->reverse_charge_valid){
//Rechnungsland ist auch Lieferland, dann RSV
if(strtolower($user->account->reverse_charge_code) == strtolower($ShippingCountry->country->code)){
self::$user_reverse_charge = true;
return true;
}
}
}
//Lieferland ohne RSV
return false;
}
public static function getYardInfo(){
return [
'shipping_free' => self::$shipping_free,
'user_tax_free' => self::$user_tax_free,
'user_reverse_charge' => self::$user_reverse_charge,
'user_country_id' => self::$user_country->id,
'shipping_country_id' => self::$shipping_country->id,
];
}
public static function getTaxFree(){
return self::$user_tax_free ? true : false;
}
public static function getUserPriceInfos(){
return [
'user_tax_free' => self::$user_tax_free,
'user_reverse_charge' => self::$user_reverse_charge,
'user_country_id' => self::$user_country->id,
];
}
public static function getShippingCountryNameById($id){
$country = ShippingCountry::findOrFail($id);
return $country->country->getLocated();
}
public static function getOrderInfo($key = false){
if(!self::$user_country){
return '';
}
switch ($key) {
case 'billing_state':
return self::$user_country->getLocated();
break;
case 'shipping_state':
return self::$shipping_country->getLocated();
break;
case 'tax_free':
return self::$user_tax_free ? __('no') : __('yes');
break;
case 'user_reverse_charge':
return self::$user_reverse_charge ? __('yes') : __('no');
break;
}
}
public static function hasActivePromotion($user) {

View file

@ -4,6 +4,7 @@ namespace App\Services;
use App\Models\UserHistory;
use Illuminate\Support\Str;
use Yard;
use Request;
class Util
{
@ -170,7 +171,17 @@ class Util
return false;
}
public static function getMyMivitaUrl($protocol = true){
public static function isPromotionUrl($debug = false){
if($debug && config('app.debug')){
return false;
}
if(Request::getHost() === config('app.promo_domain')){
return true;
}
return false;
}
public static function getMyUrl($protocol = true){
$pro = $protocol ? config('app.protocol') : "";
return $pro.config('app.pre_url_crm').config('app.domain').config('app.tld_care');
}
@ -221,7 +232,7 @@ class Util
return url($uri);
}
public static function substr_ellipsis($str, $len=100, $clean, $ell="..."){
public static function substr_ellipsis($str, $len=100, $clean=false, $ell="..."){
if($clean){
$str = strip_tags($str);
}
@ -257,11 +268,7 @@ class Util
$clean = (strlen($clean) > 20) ? substr($clean,-20) : $clean;
}
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
return ($force_lowercase) ? ((function_exists('mb_strtolower')) ? mb_strtolower($clean, 'UTF-8') : strtolower($clean)) : $clean;
}
}

View file

@ -1,7 +1,10 @@
<?php
namespace App\Services;
use App\Models\Country;
use App\Models\Product;
use App\Models\Setting;
use App\Services\UserMarign;
use App\Services\UserService;
use App\Services\Yard\Margin;
use App\Models\ShippingCountry;
@ -49,6 +52,13 @@ class Yard extends Cart
private $global_tax_rate = 0;
private $shipping_option; //pick_up//dhl_shipping
private $user_tax_free;
private $shipping_free;
private $user_reverse_charge;
private $user_country_id;
private $user_country;
private $events;
public function __construct(SessionManager $session, Dispatcher $events)
{
$this->ysession = $session;
@ -105,6 +115,24 @@ class Yard extends Cart
$this->shipping_option = $this->getYardExtra('shipping_option');
}
if($this->getYardExtra('user_tax_free')){
$this->user_tax_free = $this->getYardExtra('user_tax_free');
}
if($this->getYardExtra('shipping_free')){
$this->shipping_free = $this->getYardExtra('shipping_free');
}
if($this->getYardExtra('user_reverse_charge')){
$this->user_reverse_charge = $this->getYardExtra('user_reverse_charge');
}
if($this->getYardExtra('user_country_id')){
$this->user_country_id = $this->getYardExtra('user_country_id');
}
if($this->getYardExtra('user_country')){
$this->user_country = $this->getYardExtra('user_country');
}
$this->events = $events;
parent::__construct($session, $events);
@ -194,6 +222,11 @@ class Yard extends Cart
{
return $this->shipping_country_id;
}
public function getShippingPrice()
{
return $this->shipping_price;
}
public function getYContent()
{
@ -203,6 +236,10 @@ class Yard extends Cart
return $this->ysession->get($this->yinstance);
}
public function getCartContent(){
return $this->getContent();
}
public function reCalculateShippingPrice(){
$this->calculateShippingPrice();
}
@ -314,6 +351,15 @@ class Yard extends Cart
//dump($margin);
}
public function setUser($user){
$this->user = $user;
$this->putYardExtra('user', $user);
}
public function sponsorHasCommisson(){
return $this->user->sponsorHasCommisson();
}
public function getYardMargin(){
return $this->yard_margin;
}
@ -330,7 +376,24 @@ class Yard extends Cart
$this->putYardExtra('shipping_is_for', $shipping_is_for);
$this->calculateShippingPrice();
}
public function setUserPriceInfos($setUserPriceInfos = [])
{
$this->shipping_free = isset($setUserPriceInfos['shipping_free']) ? $setUserPriceInfos['shipping_free'] : false;
$this->putYardExtra('shipping_free', $this->shipping_free);
$this->user_tax_free = $setUserPriceInfos['user_tax_free'];
$this->putYardExtra('user_tax_free', $this->user_tax_free);
$this->user_reverse_charge = $setUserPriceInfos['user_reverse_charge'];
$this->putYardExtra('user_reverse_charge', $this->user_reverse_charge);
$this->user_country_id = $setUserPriceInfos['user_country_id'];
$this->putYardExtra('user_country_id', $this->user_country_id);
$this->user_country = Country::findOrFail($setUserPriceInfos['user_country_id']);
$this->putYardExtra('user_country', $this->user_country);
}
public function setShoppingUser($user, $use_payment_credit = false){
@ -345,6 +408,45 @@ class Yard extends Cart
}
public function getUserPriceInfos(){
return [
'user_tax_free' =>$this->user_tax_free,
'user_reverse_charge' =>$this->user_reverse_charge,
'user_country_id' =>$this->user_country_id,
'shipping_free' => $this->shipping_free,
];
}
public function getUserCountryId()
{
return $this->user_country_id;
}
public function getUserCountry()
{
return $this->user_country;
}
public function getUserTaxFree()
{
return $this->user_tax_free ? true : false;
}
public function getShippingFree()
{
return $this->shipping_free;
}
public function getShippingFreeMissingValue()
{
if($this->shipping_free && $this->total(2, '.', '') < $this->shipping_free){
return $this->shipping_free - $this->total(2, '.', '');
}
return 0;
}
public function setReducePaymentCredit($reduce_payment_credit){
$this->reduce_payment_credit = $reduce_payment_credit;
$this->putYardExtra('reduce_payment_credit', $reduce_payment_credit);
@ -405,9 +507,12 @@ class Yard extends Cart
if($this->shipping_is_for === 'me' || $this->shipping_is_for === 'ot'){
$shipping_price_for = 1;
}
if($this->shipping_is_for === 'shop'){
if($this->shipping_is_for === 'prom'){
$shipping_price_for = 2;
}
if($this->shipping_is_for === 'shop'){
$shipping_price_for = 3;
}
if($this->weight() == 0){
$shipping_price = $shipping->getShippingPricesBy($shipping_price_for)->first();
if(!$shipping_price){
@ -459,9 +564,12 @@ class Yard extends Cart
}
$shipping = $shippingCountry->shipping;
$shipping_price_for = 1;
if($this->shipping_is_for === 'shop'){
if($this->shipping_is_for === 'prom'){
$shipping_price_for = 2;
}
if($this->shipping_is_for === 'shop'){
$shipping_price_for = 3;
}
if($this->weight() == 0){
$shipping_price = $shipping->getShippingPricesBy($shipping_price_for)->first();
if(!$shipping_price){