first commit

This commit is contained in:
Kevin Adametz 2021-01-08 17:48:20 +01:00
commit 0baac018a2
1011 changed files with 145854 additions and 0 deletions

View file

@ -0,0 +1,279 @@
<?php
namespace App\Services;
use App\Mail\MailCheckout;
use App\Mail\MailInfo;
use App\Models\ShoppingUser;
use App\Services\Shop;
use App\User;
use Auth;
use Illuminate\Support\Facades\Mail;
class CustomerPriority
{
protected static $start_number = 1000;
protected static $user_notice_key = 'like';
public static function checkForAll(){
//only extern no members with no numbers
$shopping_users = ShoppingUser::where('auth_user_id', '=', NULL)->where('number', '=', NULL)->orderBy('created_at', 'ASC')->get();
foreach ($shopping_users as $shopping_user){
if($shopping_user->shopping_order && $shopping_user->shopping_order->user_shop){
self::checkOne($shopping_user);
}
}
return $shopping_users;
}
public static function checkOne($shopping_user, $mail=false, $newCustomer = true){
//look for entry
if(self::entryExists($shopping_user)){
return 'exists';
}
if(self::entryLike($shopping_user)){
if($mail){ //send mail
Mail::to(config('app.info_mail'))->send(new MailInfo($shopping_user, 'check_is_like_customer'));
}
return 'like';
}
if($newCustomer){
self::newCustomer($shopping_user);
}
return 'new';
}
public static function setIsLike($shopping_user, $set_like_shopping_user, $send_member_mail, $change_shopping_user=false)
{
if ($shopping_user->id === $set_like_shopping_user->id) {
//set new customer for shopping_user
if($change_shopping_user){
self::newCustomerNumber($shopping_user);
$send_member_mail = false;
}else{
self::newCustomer($shopping_user);
}
} else {
//set existing customer for shopping_user
self::existingCustomer($shopping_user, $set_like_shopping_user);
}
self::clearIsLike($shopping_user);
//SEND MAIL TO MEMBER
if ($send_member_mail){
if ($shopping_user->shopping_order && $shopping_user->shopping_order->shopping_payments) {
Mail::to($shopping_user->member->email)->send(new MailCheckout($shopping_user->shopping_order->txaction, $shopping_user->shopping_order, $shopping_user->shopping_order->shopping_payments->last(), false, $shopping_user->shopping_order->mode));
}
}
return true;
}
public static function newMemberForOrder($shopping_order, $member_id, Bool $all = false){
if($all){
if($shopping_order->shopping_user && $shopping_order->shopping_user->number){
$shopping_users = ShoppingUser::where('number', '=', $shopping_order->shopping_user->number)->get();
$new_number = self::nextNumber();
foreach ($shopping_users as $shopping_user) {
self::changeCustomer($shopping_user, $member_id, $new_number);
}
}
}else{
$shopping_order->member_id = $member_id;
$shopping_order->save();
if($shopping_order->shopping_user){
$shopping_order->shopping_user->member_id = $member_id;
$shopping_order->shopping_user->number = self::nextNumber();
$shopping_order->shopping_user->save();
}
}
}
public static function newMemberForCustomer($shopping_user, $member_id, Bool $all = false){
if($all){
if($shopping_user && $shopping_user->number){
$shopping_users = ShoppingUser::where('number', '=', $shopping_user->number)->get();
$new_number = self::nextNumber();
foreach ($shopping_users as $s_user) {
self::changeCustomer($s_user, $member_id, $new_number);
}
}
}else{
$shopping_user->member_id = $member_id;
$shopping_user->number = self::nextNumber();
$shopping_user->save();
if($shopping_user->shopping_order){
$shopping_user->shopping_order->member_id = $member_id;
$shopping_user->shopping_order->save();
}
}
}
public static function checkChangeOne($shopping_user, $data, $mail=false){
$matches = [];
$change = [];
$ret = 'update';
//email geändert
if(isset($data['billing_email']) && $shopping_user->billing_email != $data['billing_email']){
$found = ShoppingUser::where('auth_user_id', '=', NULL)
->where('number', '!=', NULL) //has number
->where('id', '!=', $shopping_user->id)
->where('billing_email', '=', $data['billing_email'])
->get()->pluck('number', 'id')->unique()->toArray();
if($found && count($found)){
foreach ($found as $key=>$val){
$matches[$key] = $val;
}
$ret = 'exists';
$change['billing_email'] = $data['billing_email'];
}
}
//Anschrift geändert
if(isset($data['billing_lastname']) && isset($data['billing_zipcode']) && ($shopping_user->billing_lastname != $data['billing_lastname'] || $shopping_user->billing_zipcode != $data['billing_zipcode'])){
$found = ShoppingUser::select('*')
->where('auth_user_id', '=', NULL)
->where('number', '!=', NULL) //has number
->where('id', '!=', $shopping_user->id)
->where('billing_lastname', '=', $data['billing_lastname'])
->where('billing_zipcode', '=', $data['billing_zipcode'])
->get()->pluck('number', 'id')->unique()->toArray();
if($found && count($found)){
foreach ($found as $key=>$val){
$matches[$key] = $val;
}
$ret = 'like';
$change['billing_lastname'] = $data['billing_lastname'];
$change['billing_zipcode'] = $data['billing_zipcode'];
}
}
if($matches){
$shopping_user->is_like = true;
$shopping_user->setNotice(self::$user_notice_key, $matches);
$shopping_user->save();
}
//look for entry
if($matches && $mail){ //send mail
Mail::to(config('app.info_mail'))->send(new MailInfo($shopping_user, 'change_is_like_customer', $change));
}
return $ret;
}
public static function checkNewOne($shopping_user, $mail=false){
if(self::entryLike($shopping_user)){
if($mail){ //send mail
Mail::to(config('app.info_mail'))->send(new MailInfo($shopping_user, 'check_is_like_customer'));
}
//return 'like';
}
$shopping_user->number = self::nextNumber();
$shopping_user->save();
return true;
}
private static function entryExists($shopping_user){
//check same email
$matches = ShoppingUser::where('auth_user_id', '=', NULL)
->where('number', '!=', NULL) //has number
->where('id', '!=', $shopping_user->id)
->where('billing_email', '=', $shopping_user->billing_email)->get();
if($matches && count($matches)){
$match = $matches->last();
$shopping_user->member_id = $match->member_id;
$shopping_user->number = $match->number;
$shopping_user->save();
//has order
if($shopping_user->shopping_order){
$shopping_user->shopping_order->member_id = $match->member_id;
$shopping_user->shopping_order->save();
}
return true;
}
return false;
}
private static function entryLike($shopping_user){
//check same last name und PLZ
$matches = ShoppingUser::select('*')
->where('auth_user_id', '=', NULL)
->where('number', '!=', NULL) //has number
->where('id', '!=', $shopping_user->id)
->where('billing_lastname', '=', $shopping_user->billing_lastname)
->where('billing_zipcode', '=', $shopping_user->billing_zipcode)
->get()->pluck('number', 'id')->unique()->toArray();
if($matches && count($matches)){
$shopping_user->is_like = true;
$shopping_user->setNotice(self::$user_notice_key, $matches);
$shopping_user->save();
return true;
}
return false;
}
private static function newCustomer($shopping_user){
if($shopping_user->shopping_order && $shopping_user->shopping_order->user_shop) {
$member_id = $shopping_user->shopping_order->user_shop->user_id;
$shopping_user->member_id = $member_id;
$shopping_user->number = self::nextNumber();
$shopping_user->save();
$shopping_user->shopping_order->member_id = $member_id;
$shopping_user->shopping_order->save();
}
}
private static function newCustomerNumber($shopping_user)
{
\App\Services\Shop::newUserOrder($shopping_user->number);
$shopping_user->number = self::nextNumber();
$shopping_user->save();
\App\Services\Shop::newUserOrder($shopping_user->number);
}
private static function changeCustomer($shopping_user, $member_id, $number){
$old_number = $shopping_user->number;
$shopping_user->member_id = $member_id;
$shopping_user->number = $number;
$shopping_user->save();
if($shopping_user->shopping_order) {
$shopping_user->shopping_order->member_id = $member_id;
$shopping_user->shopping_order->save();
}
\App\Services\Shop::newUserOrder($old_number);
\App\Services\Shop::newUserOrder($number);
}
private static function existingCustomer($shopping_user, $set_like_shopping_user){
$old_number = $shopping_user->number;
$shopping_user->member_id = $set_like_shopping_user->member_id;
$shopping_user->number = $set_like_shopping_user->number;
$shopping_user->save();
if($shopping_user->shopping_order) {
$shopping_user->shopping_order->member_id = $set_like_shopping_user->member_id;
$shopping_user->shopping_order->save();
}
\App\Services\Shop::newUserOrder($old_number);
\App\Services\Shop::newUserOrder($set_like_shopping_user->number);
}
private static function clearIsLike($shopping_user){
$shopping_user->is_like = false;
$shopping_user->removeNotice(self::$user_notice_key);
$shopping_user->save();
}
private static function nextNumber (){
if(!$number = ShoppingUser::max('number')){
$number = self::$start_number;
}
return $number+1;
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace App\Services\Facade;
use Illuminate\Support\Facades\Facade;
class Yard extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return \App\Services\Yard::class;
}
}

352
app/Services/HTMLHelper.php Normal file
View file

@ -0,0 +1,352 @@
<?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;
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',
];
private static $roles = [
0 => 'Kunde',
1 => 'Admin',
2 => 'SuperAdmin',
3 => 'SySAdmin',
];
public static function getMonth($i){
return self::$months[intval($i)];
}
public static function getRoleLabel($role_id = 0){
return '<span class="badge badge-pill '.self::getLabel($role_id).'">'.self::$roles[$role_id].'</span>';
}
public static function getLabel($id){
switch ($id) {
case 0:
return 'badge-default';
break;
case 1:
return 'badge-warning';
break;
case 2:
return 'badge-primary';
break;
case 3:
return 'badge-primary';
break;
}
}
public static function getRolesOptions(){
$ret = "";
foreach (self::$roles as $role_id => $value){
$ret .= '<option value="'.$role_id.'">'.$value.'</option>\n';
}
return $ret;
}
public static function getYearSelectOptions(){
$start = date("Y", strtotime("-5 years", time()));
$end = date("Y", strtotime("+1 years", time()));
$values = range($start, $end);
$now = date("Y", time());
$ret = "";
foreach ($values as $value){
$attr = ($value == $now) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value.'" '.$attr.'>'.$value.'</option>\n';
}
return $ret;
}
public static function getAttributesWithoutParents($id = false, $sameId = false, $all = true){
$values = Attribute::where('parent_id', null)->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"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getCategoriesWithoutParents($id = false, $sameId = false, $all = true){
$values = Category::where('parent_id', null)->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"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getProductsOptions($ids = array(), $all = true){
if($ids == null){
$ids = array();
}
$values = Product::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"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getCategoriesOptions($ids = array(), $all = true){
$values = Category::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"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getProductIngredientsOptions($has_ids = array(), $all = true){
$values = Ingredient::where('active', 1)->get();
$ret = "";
$attr = "";
foreach ($values as $value){
if(!in_array($value->id, $has_ids)){
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
}
return $ret;
}
public static function getAttributesOptions($ids = array(), $all = true){
$values = Attribute::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"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->name.'</option>\n';
}
return $ret;
}
public static function getUserLevelOptions($id = false, $all = true){
$values = UserLevel::where('active', 1)->get();
$ret = "";
if($all){
$ret .= '<option value="">'.__('no').'</option>\n';
}
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 getCompanyOptions($company){
$options = array(1 => __('business'), 0 => __('private'), );
$ret = "";
foreach ($options as $id => $value){
$attr = ($id == $company) ? 'selected="selected"' : '';
$ret .= '<option value="'.$id.'" '.$attr.'>'.$value.'</option>\n';
}
return $ret;
}
public static function getContriesWithMore($id, $all=true){#
$values = Country::all();
$counter = 1;
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
if( $counter == 7){
$ret .= '<optgroup label="'.__('further countrie').'">';
}
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->getLocated().'</option>\n';
$counter ++;
}
$ret .= '</optgroup>';
return $ret;
}
public static function getContriesCodes($id, $all=true){#
$values = Country::all();
$counter = 1;
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
if(!$value->phone) continue;
if( $counter == 7){
$ret .= '<optgroup label="'.__('further countrie').'">';
}
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->phone.'('.$value->getLocated().')</option>\n';
$counter ++;
}
$ret .= '</optgroup>';
return $ret;
}
public static function getCountriesWithoutUsedShippings($all=true){#
$values = Country::all();
$country_ids = ShippingCountry::all()->pluck('country_id')->toArray();
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
if(!in_array($value->id, $country_ids)){
$ret .= '<option value="'.$value->id.'">'.$value->getLocated().'</option>\n';
}
}
return $ret;
}
public static function getCountryNameFormShipping($id){
$value = ShippingCountry::find($id);
if($value){
return $value->country->getLocated();
}
return "not defined";
}
public static function getCountriesForShipping($id, $all=false){#
$values = ShippingCountry::all();
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$value->country->getLocated().'</option>\n';
}
return $ret;
}
public static function getSalutation($id){
$values = array('mr' => __('MR'), 'ms' => __('MS'));
$ret = "";
$ret .= '<option value="">'.__('please select').'</option>\n';
foreach ($values as $key => $value){
$attr = ($key == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$key.'" '.$attr.'>'.$value.'</option>\n';
}
return $ret;
}
public static function getSalutationLang($id){
$values = array('mr' => __('MR'), 'ms' => __('MS'));
return (!empty($values[$id]) ? $values[$id] : '');
}
public static function getTaxSaleOptions($id){
$values = array('1' => __('taxable_sales_1'), '2' => __('taxable_sales_2'));
$ret = "";
$ret .= '<option value="">'.__('please select').'</option>\n';
foreach ($values as $key => $value){
$attr = ($key == $id) ? 'selected="selected"' : '';
$ret .= '<option value="'.$key.'" '.$attr.'>'.$value.'</option>\n';
}
return $ret;
}
public static function getMembersOptions($id, $all=false){
$values = User::where('active', '=', true)->where('blocked', '=', false)->where('payment_account', '>=', now())->get();
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$to="";
if($value->account){
$to = $value->account->first_name." ".$value->account->last_name." | ";
}
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$to.$value->email.' #'.$value->number.'</option>\n';
}
return $ret;
}
public static function getUserCustomerOptions($id, $all=false){
$values = ShoppingUser::select(['id', 'billing_firstname', 'billing_lastname', 'billing_email', 'number'])
->where('shopping_users.member_id', '=', \Auth::user()->id)->get();
$ret = "";
if($all){
$ret .= '<option value="">'.__('please select').'</option>\n';
}
foreach ($values as $value){
dump($value);
$attr = ($value->id == $id) ? 'selected="selected"' : '';
$to = $value->billing_firstname." ".$value->billing_lastname." | ".$value->billing_email;
$ret .= '<option value="'.$value->id.'" '.$attr.'>'.$to.' #'.$value->number.'</option>\n';
}
return $ret;
}
public static function getOptionRange($select, $from=1, $to=50){
$values = range($from, $to);
$ret = "";
foreach ($values as $value){
$attr = ($value == $select) ? 'selected="selected"' : '';
$ret .= '<option value="'.$value.'" '.$attr.'>'.$value.'</option>\n';
}
return $ret;
}
}

View file

@ -0,0 +1,369 @@
<?php
namespace App\Services;
use App\Models\Homeparty;
use App\Models\Product;
use App\Models\ShippingCountry;
class HomepartyCart
{
/*private $shipping_price = 0;
private $shipping_price_net = 0;
private $shipping_tax_rate = 0;
private $shipping_tax = 0;
private $shipping_country_id = 0; //default de
private $shipping_is_for;
private $num_comp;
private $ysession;
private $yinstance;
private $shopping_data = [];*/
public static $points = 0;
public static $price = 0;
public static $price_net = 0;
public static $ek_price = 0;
public static $income_price = 0;
private static $shipping_total = 0;
private static $shipping_net_total = 0;
private static $homeparty;
private static $userCarts = [];
public static $user_host_id;
public static $is_bonus = false;
public static $is_bonus_coupon = false;
private static $bonus_coupon = 0;
private static $bonus_value = 30;
private static $voucher_price = 0;
public static $voucher_name = "";
private static $bonus_diff = 0;
private static $bonus_points_diff = 0;
private static $bonus_coupon_fault = 0;
private static $bonus_coupon_next_step = 0;
private static $bonus_coupon_next_value = 0;
private static $bonus_start = 200;
private static $bonusTable = [
250 => 15,
300 => 20,
400 => 30,
500 => 35,
600 => 40,
700 => 50,
];
public static function calculateHomeparty(Homeparty $homeparty){
self::$homeparty = $homeparty;
foreach ($homeparty->homeparty_users as $homeparty_user){
if($homeparty_user->is_host){
self::$user_host_id = $homeparty_user->id;
}
self::$userCarts[$homeparty_user->id] = new HomepartyUserCart($homeparty_user);
self::addCart(self::$userCarts[$homeparty_user->id]);
}
self::caluclateShipping();
self::caluclateBonus();
self::calculateBonusHost();
}
public static function addCart(HomepartyUserCart $homepartyUserCart){
self::$points += $homepartyUserCart->points;
self::$price += $homepartyUserCart->price;
self::$price_net += $homepartyUserCart->price_net;
self::$ek_price += $homepartyUserCart->ek_price;
self::$income_price += $homepartyUserCart->income_price;
}
public static function getUserCart($id){
return isset(self::$userCarts[$id]) ? self::$userCarts[$id] : null;
}
private static function caluclateBonus(){
if(self::$price >= 200){
self::$is_bonus = true;
$proportional_voucher = Product::whereIdentifier('proportional_voucher')->first();
self::$voucher_price = $proportional_voucher->price;
self::$voucher_name = $proportional_voucher->getLang('name');
self::$price += self::$voucher_price;
self::$price_net += $proportional_voucher->getPriceWith(true, false);
$bonus_tmp = self::$price - self::$bonus_value;
//look up for coupon in table
foreach (self::$bonusTable as $val=>$coupon){
if($bonus_tmp >= $val){
self::$is_bonus_coupon = true;
self::$bonus_coupon = $coupon;
}else{
if(self::$bonus_coupon_fault === 0){
self::$bonus_coupon_fault = $val - $bonus_tmp;
self::$bonus_coupon_next_step = $val;
self::$bonus_coupon_next_value = $coupon;
}
}
}
$keys = array_keys(self::$bonusTable);
$step = $keys[count($keys)-1];
if($bonus_tmp > $step){
self::$bonus_coupon_next_step = $step;
self::$bonus_coupon_next_value =self::$bonusTable[$step];
}
}else{
self::$bonus_diff = 200 - self::$price;
}
}
private static function calculateBonusHost(){
if(self::$is_bonus){
$bonus_total = self::$bonus_value + self::$bonus_coupon;
$user_cart = self::getUserCart(self::$user_host_id);
//cart lower the bonus
if($user_cart->price <= $bonus_total){
self::$bonus_points_diff = $user_cart->points;
$user_cart->points = 0;
$user_cart->price = 0;
return;
}
$bonus_percent = (100/$user_cart->price*$bonus_total);
self::$bonus_points_diff = round($user_cart->points/100*$bonus_percent);
$user_cart->points -= self::$bonus_points_diff;
$user_cart->price -= $bonus_total;
$user_cart->price_net -= ($bonus_total / config('app.main_tax'));
self::$price -= $bonus_total;
self::$price_net -= ($bonus_total / config('app.main_tax'));
}
}
private static function caluclateShipping(){
//weight to the orders
//first host
$host_user_cart = self::getUserCart(self::$user_host_id);
$host_user_cart->shipping_weight = $host_user_cart->weight;
foreach (self::$homeparty->homeparty_users as $homeparty_user){
if(!$homeparty_user->is_host){
$user_cart = self::$userCarts[$homeparty_user->id];
if($homeparty_user->getDelivery() === 'direct'){
$user_cart->shipping_weight += $user_cart->weight;
}else{
$host_user_cart->shipping_weight += $user_cart->weight;
}
}
}
self::calculateShippingPrice();
}
private static function calculateShippingPrice(){
foreach (self::$homeparty->homeparty_users as $homeparty_user) {
$shipping = $homeparty_user->getShipping();
$user_cart = self::$userCarts[$homeparty_user->id];
if(!$shipping){
return;
}
if($user_cart->shipping_weight === 0){
$shipping_price = $shipping->shipping_prices->first();
$shipping_price->price = 0;
$shipping_price->shipping_price_net = 0;
}else{
//sec by weight
$shipping_price = self::shippingPriceByWeight($shipping->shipping_prices, $user_cart->shipping_weight);
//default
if(!$shipping_price){
$shipping_price = $shipping->shipping_prices->first();
}
}
if($shipping_price){
$price = $shipping_price->price;
$user_cart->shipping_price = $price;
$user_cart->shipping_tax_rate = $shipping_price->tax_rate;
$user_cart->shipping_price_net = round($price / ((100+$shipping_price->tax_rate) / 100), 2);
$user_cart->shipping_tax = round($price / (100+$shipping_price->tax_rate) * 100, 2);
}
//on the end, add prices for porto
$user_cart->price += $user_cart->shipping_price;
$user_cart->price_net += $user_cart->shipping_price_net;
self::$price += $user_cart->shipping_price;
self::$price_net += $user_cart->shipping_price_net;
self::$shipping_total += $user_cart->shipping_price;
self::$shipping_net_total += $user_cart->shipping_price_net;
}
}
private static function shippingPriceByWeight($prices, $weight){
foreach ($prices as $price){
if($price->weight_from > 0 && $price->weight_to > 0){
if($weight >= $price->weight_from && $weight <= $price->weight_to){
return $price;
}
}
}
return false;
}
public static function store($identifier, $date){
$data = [
'date' => $date,
'identifier' => $identifier,
'points' => self::$points,
'price' => round(self::$price, 2),
'price_net' => round(self::$price_net, 2),
'ek_price' => round(self::$ek_price, 2),
'income_price' => round(self::$income_price, 2),
'user_host_id' => self::$user_host_id,
'is_bonus' => self::$is_bonus,
'is_bonus_coupon' => self::$is_bonus_coupon,
'bonus_value' => self::$bonus_value,
'bonus_coupon' => self::$bonus_coupon,
'bonus_total' => self::$bonus_value + self::$bonus_coupon,
'shipping_price' => self::$shipping_total,
'shipping_price_net' => self::$shipping_net_total,
'bonus_points_diff' => self::$bonus_points_diff,
'voucher_price' => self::$voucher_price,
'voucher_name' => self::$voucher_name,
];
$user_data = [];
foreach (self::$homeparty->homeparty_users as $homeparty_user){
$user_cart = self::$userCarts[$homeparty_user->id];
$user_data[$homeparty_user->id] = [
'is_host' => $homeparty_user->is_host,
'points' => $user_cart->points,
'price' => round($user_cart->price, 2),
'price_net' => round($user_cart->price_net, 2),
'ek_price' => round($user_cart->ek_price, 2),
'income_price' => round($user_cart->income_price, 2),
'weight' => $user_cart->weight,
'shipping_weight' => $user_cart->shipping_weight,
'shipping_price' => round($user_cart->shipping_price, 2),
'shipping_tax_rate' => round($user_cart->shipping_tax_rate, 2),
'shipping_price_net' => round($user_cart->shipping_price_net, 2),
'shipping_tax' => $user_cart->shipping_tax,
];
}
$data['user_carts'] = $user_data;
self::$homeparty->order = $data;
self::$homeparty->save();
}
public static function getUserCartHost(){
return self::getUserCart(self::$user_host_id);
}
public static function getFormattedPoints()
{
return formatNumber(self::$points, 0);
}
public static function getFormattedPrice()
{
return formatNumber(self::$price);
}
public static function getFormattedPriceNet()
{
return formatNumber(self::$price_net);
}
public static function getFormattedEkPrice()
{
return formatNumber(self::$ek_price);
}
public static function getFormattedIncomePrice()
{
return formatNumber(self::$income_price);
}
public static function getFormattedPriceTax(){
return formatNumber(self::$price - self::$price_net);
}
public static function getFormattedBonusPrice()
{
return formatNumber(self::$voucher_price);
}
public static function getFormattedBonusStart(){
return formatNumber(self::$bonus_start);
}
public static function getFormattedBonusValue(){
return formatNumber(self::$bonus_value);
}
public static function getFormattedBonusDiff(){
return formatNumber(self::$bonus_diff);
}
public static function getFormattedBonusCoupon(){
return formatNumber(self::$bonus_coupon);
}
public static function getFormattedBonusCouponFault(){
return formatNumber(self::$bonus_coupon_fault);
}
public static function getFormattedBonusCouponNextStep(){
return formatNumber(self::$bonus_coupon_next_step);
}
public static function getFormattedBonusCouponNextValue(){
return formatNumber(self::$bonus_coupon_next_value);
}
public static function getFormattedBonusTotal(){
if(self::$is_bonus){
return formatNumber(self::$bonus_value + self::$bonus_coupon);
}
return formatNumber(0);
}
public static function getFormattedBonusPointsDiff(){
return formatNumber( self::$bonus_points_diff, 0 );
}
protected function numberFormat($value, $decimals, $decimalPoint, $thousandSeperator)
{
if(is_null($decimals)){
$decimals = is_null(config('cart.format.decimals')) ? 2 : config('cart.format.decimals');
}
if(is_null($decimalPoint)){
$decimalPoint = is_null(config('cart.format.decimal_point')) ? '.' : config('cart.format.decimal_point');
}
if(is_null($thousandSeperator)){
$thousandSeperator = is_null(config('cart.format.thousand_seperator')) ? ',' : config('cart.format.thousand_seperator');
}
return number_format($value, $decimals, $decimalPoint, $thousandSeperator);
}
}

View file

@ -0,0 +1,123 @@
<?php
namespace App\Services;
use App\Models\HomepartyUser;
use App\Models\Product;
use App\Models\ShippingCountry;
use \Gloudemans\Shoppingcart\Cart;
use Gloudemans\Shoppingcart\CartItem;
use Gloudemans\Shoppingcart\Contracts\Buyable;
use Illuminate\Session\SessionManager;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Collection;
class HomepartyUserCart
{
/*private $shipping_price = 0;
private $shipping_price_net = 0;
private $shipping_tax_rate = 0;
private $shipping_tax = 0;
private $shipping_country_id = 0; //default de
private $shipping_is_for;
private $num_comp;
private $ysession;
private $yinstance;
private $shopping_data = [];*/
public $points;
public $price;
public $price_net;
public $ek_price;
public $income_price;
public $weight;
public $shipping_weight;
public $shipping_price;
public $shipping_tax_rate;
public $shipping_price_net;
public $shipping_tax;
private $homepartyUser;
public function __construct(HomepartyUser $homepartyUser)
{
$this->homepartyUser = $homepartyUser;
//is all total
$this->points = 0;
$this->price = 0;
$this->price_net = 0;
$this->ek_price = 0;
$this->income_price = 0;
$this->weight = 0;
$this->shipping_weight = 0;
$this->shipping_price = 0;
$this->shipping_tax_rate = 0;
$this->shipping_price_net = 0;
$this->shipping_tax = 0;
$this->calculateUserCart();
}
public function calculateUserCart(){
foreach ($this->homepartyUser->homeparty_user_order_items as $order_item) {
$this->points += $order_item->getTotalPoints();
$this->price += $order_item->getTotalPrice();
$this->price_net += $order_item->geTotalPriceNet();
$this->ek_price += $order_item->geTotalEKPrice();
$this->income_price += $order_item->geTotalIncomePrice();
$this->weight += ($order_item->product->weight * $order_item->qty);
}
}
public function getFormattedPoints()
{
return formatNumber($this->points, 0);
}
public function getFormattedPrice()
{
return formatNumber($this->price);
}
public function getFormattedPriceNet()
{
return formatNumber($this->price_net);
}
public function getFormattedEkPrice()
{
return formatNumber($this->ek_price);
}
public function getFormattedIncomePrice()
{
return formatNumber($this->income_price);
}
public function getFormattedShippingPrice()
{
return formatNumber($this->shipping_price);
}
protected function numberFormat($value, $decimals, $decimalPoint, $thousandSeperator)
{
if(is_null($decimals)){
$decimals = is_null(config('cart.format.decimals')) ? 2 : config('cart.format.decimals');
}
if(is_null($decimalPoint)){
$decimalPoint = is_null(config('cart.format.decimal_point')) ? '.' : config('cart.format.decimal_point');
}
if(is_null($thousandSeperator)){
$thousandSeperator = is_null(config('cart.format.thousand_seperator')) ? ',' : config('cart.format.thousand_seperator');
}
return number_format($value, $decimals, $decimalPoint, $thousandSeperator);
}
}

151
app/Services/Payment.php Normal file
View file

@ -0,0 +1,151 @@
<?php
namespace App\Services;
use App\Mail\MailCheckout;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\User;
use Illuminate\Support\Facades\Mail;
class Payment
{
public static $txaction_text = [
'paid' => "bezahlt",
'appointed' => "offen",
'failed' => "abbruch",
'extern' => "extern",
'invoice_open' => "Re. offen",
'invoice_paid' => "Re. bezahlt",
'invoice_non' => "keine Zahlung",
'NULL' => 'keine Zahlung',
];
public static $txaction_invoice = [
'invoice_open' => "Re. offen",
'invoice_paid' => "Re. bezahlt",
'invoice_non' => 'keine Zahlung',
];
public static $txaction_color = [
'paid' => "success",
'appointed' => "warning",
'failed' => "danger",
'extern' => "success",
'invoice_open' => "warning",
'invoice_paid' => "success",
'invoice_non' => "failed",
];
public static function getFormattedTxaction($txaction){
if($txaction && isset(self::$txaction_text[$txaction])){
return self::$txaction_text[$txaction];
}
return self::$txaction_text['NULL'];
}
public static function getFormattedTxactionColor($txaction){
if($txaction && isset(self::$txaction_color[$txaction])){
return self::$txaction_color[$txaction];
}
return "warning";
}
public static function getShoppingOrderBadge(ShoppingOrder $shopping_order){
if($shopping_order->mode === 'test'){
return '<span class="badge badge-pill badge-default">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
if($shopping_order->mode === 'dev'){
return '<span class="badge badge-pill badge-info">'.strtoupper($shopping_order->mode).' - '.self::getFormattedTxaction($shopping_order->txaction).'</span>';
}
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_order->txaction).'">'.self::getFormattedTxaction($shopping_order->txaction).'</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>';
}
return '<span class="badge badge-pill badge-'.self::getFormattedTxactionColor($shopping_payment->txaction).'">'.self::getFormattedTxaction($shopping_payment->txaction).'</span>';
}
/* public static function paymentStatusPaidAction(ShoppingOrder $shopping_order, $paid){
$send_link = false;
$shopping_order->setUserHistoryValue(['status' => 8]);
Shop::userOrders();
$shopping_order->paid = $paid;
$shopping_order->save();
//if product has actions
if($shopping_order->shopping_order_items && $shopping_order->auth_user_id){
foreach($shopping_order->shopping_order_items as $shopping_order_item){
if($shopping_order_item->product){
if($shopping_order_item->product->action){
$user = User::findOrFail($shopping_order->auth_user_id);
$user->save();
$send_link = true;
//new date
$date = \Carbon::now()->modify('1 year');
if($user->payment_account && $user->daysActiveAccount()>0){
$date = \Carbon::parse($user->payment_account)->modify('1 year');
}
foreach ($shopping_order_item->product->action as $do){
if($shopping_order_item->product->getActionName($do) === 'payment_for_account'){
$user->payment_order_id = $shopping_order_item->product->id; //34
$user->payment_account = $date;
$user->wizard = 100;
$shopping_order->setUserHistoryValue(['status' => 9]);
}
if($shopping_order_item->product->getActionName($do) === 'payment_for_shop'){
$user->payment_order_id = $shopping_order_item->product->id; //35
$user->payment_shop = $date;
$user->wizard = 100;
$shopping_order->setUserHistoryValue(['status' => 9]);
}
if($shopping_order_item->product->getActionName($do) === 'payment_for_shop_upgrade'){
if($shopping_order_item->product->upgrade_to_id){
$user->payment_order_id = $shopping_order_item->product->upgrade_to_id;
}
$user->payment_shop = $user->payment_account; //same Date, is upgrade
$shopping_order->setUserHistoryValue(['status' => 9]);
}
if($shopping_order_item->product->getActionName($do) === 'payment_for_lead_upgrade'){
if($shopping_order_item->product->upgrade_to_id){
$user->m_level = $shopping_order_item->product->upgrade_to_id;
}
}
$user->save();
}
}
}
}
}
return $send_link;
}*/
public static function paymentStatusSendMail(ShoppingOrder $shopping_order, $shopping_payment, $data){
$bcc = [];
$billing_email = $shopping_order->shopping_user->billing_email;
if(!$billing_email){
if($data['mode'] === 'test'){
$billing_email = config('app.checkout_test_mail');
}else{
$billing_email = config('app.checkout_mail');
}
}
if($data['mode'] === 'test'){
$bcc[] = config('app.checkout_test_mail');
}else{
$bcc[] = config('app.checkout_mail');
}
if(!$shopping_order->shopping_user->is_like && $shopping_order->shopping_user->member){
$bcc[] = $shopping_order->shopping_user->member->email;
}
Mail::to($billing_email)->bcc($bcc)->send(new MailCheckout($data['txaction'], $shopping_order, $shopping_payment, $data['send_link'], $data['mode']));
}
}

66
app/Services/Shop.php Normal file
View file

@ -0,0 +1,66 @@
<?php
namespace App\Services;
use App\Models\Country;
use App\Models\ShippingCountry;
use App\Models\ShoppingUser;
use Gloudemans\Shoppingcart\CartItem;
class Shop
{
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');
})->where('orders', '=', NULL)->get();
foreach ($shopping_users as $shopping_user) {
if ($shopping_user->number) {
$orders = ShoppingUser::where('number', '=', $shopping_user->number)->max('orders');
$orders = $orders + 1;
} else {
$orders = ShoppingUser::where('billing_email', '=', $shopping_user->billing_email)->max('orders');
$orders = $orders + 1;
}
$shopping_user->orders = $orders;
$shopping_user->save();
}
}
public static function newUserOrder($number){
if($number > 0){
$shopping_users = ShoppingUser::where('number', '=', $number)->get();
$orders = 1;
foreach ($shopping_users as $shopping_user) {
if($shopping_user->shopping_order && ($shopping_user->shopping_order->txaction === 'paid' || $shopping_user->shopping_order->txaction === 'appointed' || $shopping_user->shopping_order->txaction === 'extern')){
$shopping_user->orders = $orders++;
}else{
$shopping_user->orders = NULL;
}
$shopping_user->save();
}
}
}
public static function getShippingCountryCountryId($shipping_country_id){
$shippingCountry = ShippingCountry::find($shipping_country_id);
if($shippingCountry && $shippingCountry->country){
return $shippingCountry->country->id;
}
return 1; //default DE
}
public static function getCountryShippingCountryId($country_id){
$shippingCountry = ShippingCountry::whereCountryId($country_id)->first();
if($shippingCountry){
return $shippingCountry->id;
}
if($ShippingCountry = ShippingCountry::all()->first()){
$ShippingCountry->id;
}
return 1;
}
}

257
app/Services/Slim.php Normal file
View file

@ -0,0 +1,257 @@
<?php
namespace App\Services;
abstract class SlimStatus {
const FAILURE = 'failure';
const SUCCESS = 'success';
}
class Slim {
public static function getImages($inputName = 'slim') {
$values = Slim::getPostData($inputName);
// test for errors
if ($values === false) {
return false;
}
// determine if contains multiple input values, if is singular, put in array
$data = array();
if (!is_array($values)) {
$values = array($values);
}
// handle all posted fields
foreach ($values as $value) {
$inputValue = Slim::parseInput($value);
if ($inputValue) {
array_push($data, $inputValue);
}
}
// return the data collected from the fields
return $data;
}
// $value should be in JSON format
private static function parseInput($value) {
// if no json received, exit, don't handle empty input values.
if (empty($value)) {return null;}
// If magic quotes enabled
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// The data is posted as a JSON String so to be used it needs to be deserialized first
$data = json_decode($value);
// shortcut
$input = null;
$actions = null;
$output = null;
$meta = null;
if (isset ($data->input)) {
$inputData = null;
if (isset($data->input->image)) {
$inputData = Slim::getBase64Data($data->input->image);
}
else if (isset($data->input->field)) {
$filename = $_FILES[$data->input->field]['tmp_name'];
if ($filename) {
$inputData = file_get_contents($filename);
}
}
$input = array(
'data' => $inputData,
'name' => $data->input->name,
'type' => $data->input->type,
'size' => $data->input->size,
'width' => $data->input->width,
'height' => $data->input->height,
);
}
if (isset($data->output)) {
$outputDate = null;
if (isset($data->output->image)) {
$outputData = Slim::getBase64Data($data->output->image);
}
else if (isset ($data->output->field)) {
$filename = $_FILES[$data->output->field]['tmp_name'];
if ($filename) {
$outputData = file_get_contents($filename);
}
}
$output = array(
'data' => $outputData,
'name' => $data->output->name,
'type' => $data->output->type,
'width' => $data->output->width,
'height' => $data->output->height
);
}
if (isset($data->actions)) {
$actions = array(
'crop' => $data->actions->crop ? array(
'x' => $data->actions->crop->x,
'y' => $data->actions->crop->y,
'width' => $data->actions->crop->width,
'height' => $data->actions->crop->height,
'type' => $data->actions->crop->type
) : null,
'size' => $data->actions->size ? array(
'width' => $data->actions->size->width,
'height' => $data->actions->size->height
) : null,
'rotation' => $data->actions->rotation,
'filters' => $data->actions->filters ? array(
'sharpen' => $data->actions->filters->sharpen
) : null
);
}
if (isset($data->meta)) {
$meta = $data->meta;
}
// We've sanitized the base64data and will now return the clean file object
return array(
'input' => $input,
'output' => $output,
'actions' => $actions,
'meta' => $meta
);
}
// $path should have trailing slash
public static function saveFile($data, $name, $path = 'tmp/', $uid = true) {
// Add trailing slash if omitted
if (substr($path, -1) !== '/') {
$path .= '/';
}
// Test if directory already exists
if(!is_dir($path)){
mkdir($path, 0755, true);
}
// Sanitize characters in file name
$name = Slim::sanitizeFileName($name);
// Let's put a unique id in front of the filename so we don't accidentally overwrite other files
if ($uid) {
$name = uniqid() . '_' . $name;
}
// Add name to path, we need the full path including the name to save the file
$path = $path . $name;
// store the file
Slim::save($data, $path);
// return the files new name and location
return array(
'name' => $name,
'path' => $path
);
}
/**
* Get data from remote URL
* @param $url
* @return string
*/
public static function fetchURL($url, $maxFileSize) {
if (!ini_get('allow_url_fopen')) {
return null;
}
$content = null;
try {
$content = @file_get_contents($url, false, null, 0, $maxFileSize);
} catch(Exception $e) {
return false;
}
return $content;
}
public static function outputJSON($data) {
header('Content-Type: application/json');
echo json_encode($data);
}
/**
* http://stackoverflow.com/a/2021729
* Remove anything which isn't a word, whitespace, number
* or any of the following characters -_~,;[]().
* If you don't need to handle multi-byte characters
* you can use preg_replace rather than mb_ereg_replace
* @param $str
* @return string
*/
public static function sanitizeFileName($str) {
// Basic clean up
$str = preg_replace('([^\w\s\d\-_~,;\[\]\(\).])', '', $str);
// Remove any runs of periods
$str = preg_replace('([\.]{2,})', '', $str);
$str = (strlen($str) > 33) ? substr($str,-33) : $str;
return $str;
}
/**
* Gets the posted data from the POST or FILES object. If was using Slim to upload it will be in POST (as posted with hidden field) if not enhanced with Slim it'll be in FILES.
* @param $inputName
* @return array|bool
*/
private static function getPostData($inputName) {
$values = array();
if (isset($_POST[$inputName])) {
$values = $_POST[$inputName];
}
else if (isset($_FILES[$inputName])) {
// Slim was not used to upload this file
return false;
}
return $values;
}
/**
* Saves the data to a given location
* @param $data
* @param $path
* @return bool
*/
private static function save($data, $path) {
if (!file_put_contents($path, $data)) {
return false;
}
return true;
}
/**
* Strips the "data:image..." part of the base64 data string so PHP can save the string as a file
* @param $data
* @return string
*/
private static function getBase64Data($data) {
return base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
}
}

78
app/Services/SysLog.php Normal file
View file

@ -0,0 +1,78 @@
<?php
namespace App\Services;
use App\Mail\MailSyS;
use App\Models\Logger;
use Illuminate\Support\Facades\Mail;
class SysLog
{
/* protected $user_id;
protected $model;
protected $model_id;
protected $message;
protected $action;
protected $channel;
protected $level;*/
protected $log;
public $levelTypes = [
1 => 'debug',
2 => 'info',
3 => 'notice',
4 => 'warning',
5 => 'error',
6 => 'critical',
7 => 'alert',
];
function __construct($action = null, $channel = 'default', $level = 1)
{
$this->log = new Logger();
$this->log->action = $action;
$this->log->channel = $channel;
$this->log->level = $level;
}
public static function action($action = null, $channel = 'default', $level = 1)
{
//Return new instance of this model
return new self($action, $channel, $level);
}
public function setModel($id, $model){
$this->log->model_id = $id;
$this->log->model = $model;
return $this;
}
public function setUserId($user_id){
$this->log->user_id = $user_id;
return $this;
}
public function setMessage($message){
$this->log->message = $message;
return $this;
}
public function save(){
$this->log->save();
//send Mail
if($this->log->level >= 3){
$mail = config('app.info_test_mail');
Mail::to($mail)->send(new MailSyS($this->log, 'log'));
}
}
public function getLevelType(){
return $this->levelTypes[$this->log->level];
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Services;
use App\User;
class UserService
{
public static function createConfirmationCode() {
$unique = false;
do{
$confirmation_code = str_random(30);
if(User::where('confirmation_code', '=', $confirmation_code)->count() == 0){
$unique = true;
}
}
while(!$unique);
return $confirmation_code;
}
}

241
app/Services/Util.php Normal file
View file

@ -0,0 +1,241 @@
<?php
namespace App\Services;
use App\Models\UserHistory;
use Illuminate\Support\Str;
use Yard;
class Util
{
private static $postRoute = 'base.';
public static function getToken()
{
return hash_hmac('sha256', str_random(40), config('app.key'));
}
public static function uuidToken()
{
$uuid = (string) Str::uuid();
$e_uuid = explode("-", $uuid);
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"){
return 'yyyy-mm-dd';
}
return 'dd.mm.yyyy';
}
public static function formatDateDB(){
if(\App::getLocale() === "en"){
return 'Y-m-d';
}
return 'd.m.Y';
}
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){
return preg_replace("/[^0-9,]/", "", $value);
}
public static function reFormatNumber($value){
return (float) str_replace(',', '.', self::_format_number($value));
}
public static function formatNumber($value, $dec=2){
if(\App::getLocale() === "en"){
return number_format($value, $dec, '.', ',');
}
return number_format($value, $dec, ',', '.');
}
public static function utf8ize( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = self::utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
public static function getPostRoute(){
return self::$postRoute;
}
public static function setPostRoute($postRoute){
self::$postRoute = $postRoute;
}
public static function getUserShop(){
if(\Session::has('user_shop')){
if($user_shop = \Session::get('user_shop')){
return $user_shop;
}
}
return false;
}
public static function getAuthUser(){
if(\Auth::check() && \Auth::user()){
return \Auth::user();
}
if(\Session::has('auth_user')){
if($auth_user = \Session::get('auth_user')){
return $auth_user;
}
}
return false;
}
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 getUserHistory(){
$auth_user = self::getAuthUser();
$user_shop_identifier = self::getUserShopIdentifier();
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){
$user_history->{$key} = $val;
}
$user_history->save();
}
}
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()){
return 'test';
}
}
return 'live';
}
public static function addRoute($p = []){
$b = [];
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 isCheckout(){
if(\Session::has('isCheckout')){
if(\Session::get('isCheckout') == true){
return true;
}
}
return false;
}
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');
}
public static function getUserPaymentFor(){
if(Yard::instance('shopping')->getYardExtra('user_shop_payment')){
return Yard::instance('shopping')->getYardExtra('user_shop_payment');
}
if(\Session::has('user_shop_payment')){
return \Session::get('user_shop_payment');
}
return null;
}
public static function getUserShopBackUrl($reference = ""){
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;
}
}
return url("/");
}
public static function getUserCardBackUrl($uri){
if(\Session::has('user_shop')){
if(\Session::has('user_shop_domain')){
if(\Session::has('back_link')){
return \Session::get('back_link');
}
if(self::getUserPaymentFor() === 3){
return \Session::get('user_shop_domain')."/user/membership";
}
if(self::getUserPaymentFor() === 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;
}
}
return url($uri);
}
public static function sanitize($string, $force_lowercase = true, $anal = false, $substr = false)
{
$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;
}
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
}

472
app/Services/Yard.php Normal file
View file

@ -0,0 +1,472 @@
<?php
namespace App\Services;
use App\Models\Product;
use App\Models\ShippingCountry;
use Gloudemans\Shoppingcart\Cart;
use Gloudemans\Shoppingcart\CartItem;
use Gloudemans\Shoppingcart\Contracts\Buyable;
use Illuminate\Session\SessionManager;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Collection;
class Yard extends Cart
{
private $shipping_price = 0;
private $shipping_price_net = 0;
private $shipping_tax_rate = 0;
private $shipping_tax = 0;
private $shipping_country_id = 0; //default de
private $shipping_is_for;
private $num_comp;
private $ysession;
private $yinstance;
private $shopping_data = [];
public function __construct(SessionManager $session, Dispatcher $events)
{
$this->ysession = $session;
$this->yinstance = sprintf('%s.%s', 'cart', 'shipping_extras');
if($this->getYardExtra('shipping_price')){
$this->shipping_price = (float) ($this->getYardExtra('shipping_price'));
}
if($this->getYardExtra('shipping_price_net')){
$this->shipping_price_net = (float) ($this->getYardExtra('shipping_price_net'));
}
if($this->getYardExtra('shipping_tax_rate')){
$this->shipping_tax_rate = (float) ($this->getYardExtra('shipping_tax_rate'));
}
if($this->getYardExtra('shipping_tax')){
$this->shipping_tax = (float) ($this->getYardExtra('shipping_tax'));
}
if($this->getYardExtra('shipping_country_id')){
$this->shipping_country_id = $this->getYardExtra('shipping_country_id');
}
if($this->getYardExtra('shipping_is_for')){
$this->shipping_is_for = $this->getYardExtra('shipping_is_for');
}
if($this->getYardExtra('num_comp')){
$this->num_comp = $this->getYardExtra('num_comp');
}
parent::__construct($session, $events);
if(gettype($this->shipping_country_id) !== 'object' && $this->shipping_country_id == 0){
$shippingCountry = ShippingCountry::first();
if($shippingCountry){
$this->shipping_country_id = $shippingCountry->id;
}
}
if($this->shipping_price == 0){
self::instance('shopping')->setShippingCountryWithPrice($this->shipping_country_id, $this->shipping_is_for);
}
}
public static function getTaxRate()
{
return config('cart.tax');
}
public function putYardExtra($key, $value){
$content = $this->getYContent();
$content->put($key, $value);
$this->ysession->put($this->yinstance, $content);
}
public function getYardExtra($key){
$content = $this->getYContent();
if ($content->has($key)){
return $content->get($key);
}
return false;
}
public function getShippingCountryName(){
$shippingCountry = ShippingCountry::find($this->shipping_country_id);
if($shippingCountry && $shippingCountry->country){
return $shippingCountry->country->getLocated();
}
return "";
}
public function getShippingCountryCountryId()
{
$shippingCountry = ShippingCountry::find($this->shipping_country_id);
if($shippingCountry && $shippingCountry->country){
return $shippingCountry->country->id;
}
return 1; //default DE
}
public function getShippingCountryId()
{
return $this->shipping_country_id;
}
public function getYContent()
{
if (is_null($this->ysession->get($this->yinstance))) {
return new Collection([]);
}
return $this->ysession->get($this->yinstance);
}
public function reCalculateShippingPrice(){
$this->calculateShippingPrice();
}
public function setShippingCountryWithPrice($shipping_country_id, $shipping_is_for = 'ot')
{
$this->shipping_country_id = $shipping_country_id;
$this->putYardExtra('shipping_country_id', $shipping_country_id);
$this->shipping_is_for = $shipping_is_for;
$this->putYardExtra('shipping_is_for', $shipping_is_for);
$this->calculateShippingPrice();
}
private function calculateShippingPrice(){
$shippingCountry = ShippingCountry::find($this->shipping_country_id);
if(!$shippingCountry){
return;
}
$shipping = $shippingCountry->shipping;
if($this->weight() == 0){
$shipping_price = $shipping->shipping_prices->first();
$shipping_price->price = 0;
$shipping_price->price_comp = 0;
}else{
//first by price
$shipping_price = $this->shippingPriceByTotal($shipping->shipping_prices, $this->total(2, '.', ''));
//sec by weight
if(!$shipping_price){
$shipping_price = $this->shippingPriceByWeight($shipping->shipping_prices, $this->weight());
}
//default
if(!$shipping_price){
$shipping_price = $shipping->shipping_prices->first();
}
}
if($shipping_price){
$price = $shipping_price->price;
$this->num_comp = 0;
if($this->shipping_is_for === 'me'){
$price = $shipping_price->price_comp;
$this->num_comp = $shipping_price->num_comp;
}
$this->shipping_price = $price;
$this->shipping_tax_rate = $shipping_price->tax_rate;
$this->shipping_price_net = round($price / ((100+$shipping_price->tax_rate) / 100), 2);
$this->shipping_tax = round($price / (100+$shipping_price->tax_rate) * 100, 2);
$this->putYardExtra('num_comp', $this->num_comp);
$this->putYardExtra('shipping_price', $this->shipping_price);
$this->putYardExtra('shipping_tax_rate', $this->shipping_tax_rate);
$this->putYardExtra('shipping_tax', $this->shipping_tax);
$this->putYardExtra('shipping_price_net', $this->shipping_price_net);
}
}
private function shippingPriceByTotal($prices, $total){
foreach ($prices as $price){
if($price->total_from > 0 && $price->total_to > 0){
if($total >= $price->total_from && $total <= $price->total_to){
return $price;
}
}
}
return false;
}
private function shippingPriceByWeight($prices, $weight){
foreach ($prices as $price){
if($price->weight_from > 0 && $price->weight_to > 0){
if($weight >= $price->weight_from && $weight <= $price->weight_to){
return $price;
}
}
}
return false;
}
/**
* @param null $decimals
* @param null $decimalPoint
* @param null $thousandSeperator
* @return string
*/
public function shipping($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->shipping_price, $decimals, $decimalPoint, $thousandSeperator);
}
public function shippingNet($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->shipping_price_net, $decimals, $decimalPoint, $thousandSeperator);
}
//
private function shippingTax($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
return $this->numberFormat($this->shipping_tax, $decimals, $decimalPoint, $thousandSeperator);
}
/* private function subShipping($decimals = null, $decimalPoint = null, $thousandSeperator = null){
$subShipping = $this->shipping_price_net
return $this->numberFormat($subShipping, $decimals, $decimalPoint, $thousandSeperator);
}*/
//netto
public function subtotalWithShipping($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$subtotal = (float) $this->shipping_price_net + $this->subtotal(2, '.', '');
return $this->numberFormat($subtotal, $decimals, $decimalPoint, $thousandSeperator);
}
public function taxWithShipping($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$total = $this->totalWithShipping(2, '.', '');
// $totalTax = (float) $this->tax(2, '.', '') + $this->shipping_tax;
$totalTax = $this->subtotalWithShipping(2, '.', '');
return $this->numberFormat(($total - $totalTax), $decimals, $decimalPoint, $thousandSeperator);
}
public function totalWithShipping($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$total = (float) ($this->total(2, '.', '')) + $this->shipping_price;
return $this->numberFormat($total, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the total price of the items in the cart.
*
* @param int $decimals
* @param string $decimalPoint
* @param string $thousandSeperator
* @return string
*/
public function weight($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$content = $this->getContent();
$total = $content->reduce(function ($total, CartItem $cartItem) {
return $total + ($cartItem->options->weight ? ($cartItem->options->weight*$cartItem->qty) : 0);
}, 0);
return $total;
}
public function points()
{
$content = $this->getContent();
$total = $content->reduce(function ($total, CartItem $cartItem) {
return $total + ($cartItem->options->points ? ($cartItem->options->points * $cartItem->qty) : 0);
}, 0);
return $total;
}
public function compCount()
{
$content = $this->getContent();
$count = parent::count();
$comp_count = $content->reduce(function ($comp_count, CartItem $cartItem) {
return $cartItem->options->comp ? $comp_count + 1 : $comp_count;
}, 0);
return $count-$comp_count;
}
/**
* Get the total price of the items in the cart.
*
* @param int $decimals
* @param string $decimalPoint
* @param string $thousandSeperator
* @return string
*/
public function total($decimals = null, $decimalPoint = null, $thousandSeperator = null, $withFees = false)
{
$content = $this->getContent();
$total = $content->reduce(function ($total, CartItem $cartItem) {
return $total + ($cartItem->qty * $cartItem->price);
}, 0);
if ($withFees === true) {
$fees = $this->feeTotal(null, null, null, true);
$total = $total + $fees;
}
return $this->numberFormat($total, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the total tax of the items in the cart.
*
* @param int $decimals
* @param string $decimalPoint
* @param string $thousandSeperator
* @return float
*/
public function tax($decimals = null, $decimalPoint = null, $thousandSeperator = null, $withFees = false)
{
$content = $this->getContent();
$tax = $content->reduce(function ($tax, CartItem $cartItem) {
$priceTax = $cartItem->price / (100 + $cartItem->taxRate) * $cartItem->taxRate;
return $tax + ($cartItem->qty * $priceTax);
}, 0);
if ($withFees === true) {
$fees = $this->feeTax();
$tax = $tax + floatval($fees);
}
return $this->numberFormat($tax, $decimals, $decimalPoint, $thousandSeperator);
}
/**
* Get the subtotal (total - tax) of the items in the cart.
*
* @param int $decimals
* @param string $decimalPoint
* @param string $thousandSeperator
* @return float
*/
public function subtotal($decimals = null, $decimalPoint = null, $thousandSeperator = null)
{
$content = $this->getContent();
$subTotal = $content->reduce(function ($subTotal, CartItem $cartItem) {
$price_net = $cartItem->price / ((100 + $cartItem->taxRate) / 100);
return $subTotal + ($cartItem->qty * $price_net);
}, 0);
return $this->numberFormat($subTotal, $decimals, $decimalPoint, $thousandSeperator);
}
public function getCartItemByProduct($product_id, $set_price='with'){
if($product = Product::find($product_id)) {
$image = "";
if ($product->images->count()) {
$image = $product->images->first()->slug;
}
$price = $product->price;
if($set_price === 'with'){
$price = $product->getPriceWith(false, true);
}
$cartItem = $this->getCartItem($product->id, $product->getLang('name'), 1, $price, ['image' => $image, 'slug' => $product->slug, 'weight' => $product->weight, 'points' => $product->points]);
$content = $this->getContent();
if ($content->has($cartItem->rowId)){
return $content->get($cartItem->rowId);
}
return $cartItem;
}
return null;
}
public function getCartItem($id, $name = null, $qty = null, $price = null, array $options = []){
if ($id instanceof Buyable) {
$cartItem = CartItem::fromBuyable($id, $qty ?: []);
} elseif (is_array($id)) {
$cartItem = CartItem::fromArray($id);
} else {
$cartItem = CartItem::fromAttributes($id, $name, $price, $options);
}
return $cartItem;
}
public function destroy()
{
$this->ysession->remove($this->yinstance);
parent::destroy();
}
public function rowPriceNet(CartItem $row, $decimals = null, $decimalPoint = null, $thousandSeperator = null){
$price = round($row->price / ((100 + $row->taxRate) /100), 4);
return $this->numberFormat($price, $decimals, $decimalPoint, $thousandSeperator);
}
public function rowSubtotalNet(CartItem $row, $decimals = null, $decimalPoint = null, $thousandSeperator = null){
$price = round($row->price / ((100 + $row->taxRate) /100), 4);
return $this->numberFormat(($price * $row->qty), $decimals, $decimalPoint, $thousandSeperator);
}
public function getNumComp(){
return $this->num_comp;
}
public function getCompProductBy($comp, $product_id=false){
foreach ($this->content() as $row) {
if($row->options->comp == $comp) {
return $row->options->product_id;
}
}
return false;
}
public function getContentByOrder(){
$ret = [];
$comp = [];
foreach ($this->content() as $row) {
if($row->options->comp){
$comp[100+$row->options->comp] = $row;
}else{
$ret[] = $row;
}
}
ksort($comp);
$ret = array_merge($ret, $comp);
return $ret;
}
/**
* Get the Formated number
*
* @param $value
* @param $decimals
* @param $decimalPoint
* @param $thousandSeperator
* @return string
*/
protected function numberFormat($value, $decimals, $decimalPoint, $thousandSeperator)
{
if(is_null($decimals)){
$decimals = is_null(config('cart.format.decimals')) ? 2 : config('cart.format.decimals');
}
if(is_null($decimalPoint)){
$decimalPoint = is_null(config('cart.format.decimal_point')) ? '.' : config('cart.format.decimal_point');
}
if(is_null($thousandSeperator)){
$thousandSeperator = is_null(config('cart.format.thousand_seperator')) ? ',' : config('cart.format.thousand_seperator');
}
return number_format($value, $decimals, $decimalPoint, $thousandSeperator);
}
}