update 20.10.2025

This commit is contained in:
Kevin Adametz 2025-10-20 17:42:08 +02:00
parent 8c11130b5d
commit a939cd51ef
616 changed files with 84821 additions and 4121 deletions

View file

@ -0,0 +1,89 @@
<?php
namespace App\Repositories;
use Carbon;
use App\Models\UserAbo;
use App\Services\AboHelper;
class AboRepository extends BaseRepository {
public function __construct()
{
//$this->model = $model;
}
public function setModel(UserAbo $model){
$this->model = $model;
}
public function update($data)
{
if(isset($data['action'])){
if($data['action'] === 'abo_update_settings'){
if($this->validate($data)){
$this->updateStatus($data);
$this->model->abo_interval = $data['abo_interval'];
$this->model->next_date = AboHelper::setNextDate(now(), $data['abo_interval']);
$this->model ->save();
\Session()->flash('alert-success', 'Einstellungen gespeichert');
return true;
}
return false;
}
}
return false;
}
public function create($data){
}
private function updateStatus($data){
$active = (isset($data['abo_is_active']) && $data['abo_is_active']) ? true : false;
//if status is active and active is false, set status to inactive
if($this->model->active && !$active){
if($this->model->status = 2){ //okay
$this->model->status = 6; //
}
}
if(!$this->model->active && $active){
if($this->model->status = 6){ //inactive
$this->model->status = 2; //okay
}
}
$this->model->active = $active;
return;
}
private function validate($data){
if($data['view'] !== 'admin'){
if($this->model->is_for === 'me' && $this->model->user_id !== \Auth::user()->id){
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if($this->model->is_for === 'ot' && $this->model->member_id !== \Auth::user()->id){
\Session()->flash('alert-error', 'Unauthorized action. User ID does not match.');
return false;
}
if($data['view'] === 'me' && $this->model->is_for !== 'me'){
\Session()->flash('alert-error', 'Unauthorized action. Is not for me');
return false;
}
if($data['view'] === 'ot' && $this->model->is_for !== 'ot'){
\Session()->flash('alert-error', 'Unauthorized action. Is not your customer');
return false;
}
}
if(!in_array($data['abo_interval'], \App\Models\UserAbo::$aboDeliveryDays)){
//to check if user is not admin
\Session()->flash('alert-error', __('abo.error_abo_interval'));
return false;
}
return true;
}
}

View file

@ -0,0 +1,68 @@
<?php
namespace App\Repositories;
abstract class BaseRepository {
/**
* The Model instance.
*
* @var Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* Get number of records.
*
* @return array
*/
public function getNumber()
{
$total = $this->model->count();
$new = $this->model->whereSeen(0)->count();
return compact('total', 'new');
}
/**
* Destroy a model.
*
* @param int $id
* @return void
*/
public function destroy($id)
{
$this->getById($id)->delete();
}
/**
* Get Model by id.
*
* @param int $id
* @return App\Models\Model
*/
public function getById($id)
{
return $this->model->findOrFail($id);
}
/**
* Get Model by id.
*
* @param int $id
* @return App\Models\Model
*/
public function getAll()
{
return $this->model->all();
}
/**
* @return Illuminate\Database\Eloquent\Model
*/
public function getModel()
{
return $this->model;
}
}

View file

@ -0,0 +1,463 @@
<?php
namespace App\Repositories;
use Yard;
use App\Services\Util;
use App\Models\ShoppingUser;
use App\Models\Homeparty;
use App\Models\ShoppingCollectOrder;
use App\Models\PaymentMethod;
use App\Models\ShoppingOrder;
use Illuminate\Session\SessionManager;
use App\Models\ShoppingOrderItem;
use Illuminate\Support\Collection;
class CheckoutRepository extends BaseRepository {
private $session;
private $instance;
public function __construct(SessionManager $session)
{
$this->session = $session;
$this->instance = 'checkout';
}
public function makeShoppingOrder($shopping_user, $data){
$user_shop = Util::getUserShop();
if($shopping_user->is_from === 'homeparty'){
//get data
$homeparty = Homeparty::find($shopping_user->homeparty_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
'country_id' => Yard::instance($this->instance)->getShippingCountryId(),
'language' => \App::getLocale(),
'user_shop_id' => $user_shop->id,
'payment_for' => $shopping_user->getOrderPaymentFor(),
'homeparty_id' => $shopping_user->homeparty_id,
'total' => $total,
'subtotal' => $homeparty->order['ek_price_net'],
'shipping' => $homeparty->order['shipping_price'],
'shipping_net' => $homeparty->order['shipping_price_net'],
'subtotal_ws' => 0,
'tax' => $total - $homeparty->order['ek_price_net'],
'total_shipping' => Yard::instance($this->instance)->totalWithShipping(2, '.', ''),
'points' => $homeparty->order['points'] - $homeparty->order['bonus_points_diff'],
'weight' => 0,
'txaction' => 'prev',
'mode' => Util::getUserShoppingMode(),
];
}elseif($shopping_user->is_from === 'collection'){
//get data
$ShoppingCollectOrder = ShoppingCollectOrder::find($shopping_user->shopping_collect_order_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
'country_id' => Yard::instance($this->instance)->getShippingCountryId(),
'language' => \App::getLocale(),
'user_shop_id' => $user_shop->id,
'payment_for' => $shopping_user->getOrderPaymentFor(),
'total' => $total,
'subtotal' => $ShoppingCollectOrder->price_total_net,
'shipping' => 0,
'shipping_net' => 0,
'subtotal_ws' => $ShoppingCollectOrder->price_total_net,
'tax' => $ShoppingCollectOrder->tax_total,
'tax_split' => $ShoppingCollectOrder->tax_split,
'total_shipping' => Yard::instance($this->instance)->totalWithShipping(2, '.', ''),
'points' => $ShoppingCollectOrder->points,
'weight' => 0,
'txaction' => 'prev',
'mode' => Util::getUserShoppingMode(),
];
}else{
$data = [
'shopping_user_id' => $shopping_user->id,
'auth_user_id' => $shopping_user->auth_user_id,
'country_id' => Yard::instance($this->instance)->getShippingCountryId(),
'language' => \App::getLocale(),
'user_shop_id' => $user_shop->id,
'payment_for' => $shopping_user->getOrderPaymentFor(),
'total' => Yard::instance($this->instance)->total(2, '.', ''),
'subtotal' => Yard::instance($this->instance)->subtotal(2, '.', ''),
'shipping' => Yard::instance($this->instance)->shipping(2, '.', ','),
'shipping_net' => Yard::instance($this->instance)->shippingNet(2, '.', ''),
'subtotal_ws' => Yard::instance($this->instance)->subtotalWithShipping(2, '.', ''),
'tax' => Yard::instance($this->instance)->taxWithShipping(2, '.', ''),
'total_shipping' => Yard::instance($this->instance)->totalWithShipping(2, '.', ''),
'points' => Yard::instance($this->instance)->points(),
'weight' => Yard::instance($this->instance)->weight(),
'is_abo' => isset($data['is_abo']) ? $data['is_abo'] : false,
'abo_interval' => isset($data['abo_interval']) ? $data['abo_interval'] : null,
'txaction' => 'prev',
'mode' => Util::getUserShoppingMode(),
];
}
$shopping_order= false;
if($this->getSessionPayments('shopping_order_id')){
$shopping_order = ShoppingOrder::find($this->getSessionPayments('shopping_order_id'));
if($shopping_order){
$shopping_order->fill($data);
$shopping_order->save();
}
}
if(!$shopping_order){
$shopping_order = ShoppingOrder::create($data);
if($shopping_user->is_from === 'collection' && $ShoppingCollectOrder){
$ShoppingCollectOrder->shopping_order_id = $shopping_order->id;
$ShoppingCollectOrder->save();
}
}
$this->putSessionPayments('shopping_order_id', $shopping_order->id);
$items = Yard::instance($this->instance)->getContentByOrder();
$shopping_order->shopping_order_items()->each(function($model) use ($items, $shopping_order, $shopping_user) {
foreach ($items as $item) {
if ($model->row_id === $item->rowId) {
$price_net = Yard::instance($this->instance)->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
'price' => $item->price,
'price_net' => $price_net,
'tax_rate' => $item->taxRate,
'tax' => $tax,
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug,
];
if($shopping_user->is_from === 'homeparty'){
$data['homeparty_id'] = (int) $shopping_user->homeparty_id;
$data['product_id'] = null;
}
if($shopping_user->is_from === 'collection'){
$data['shopping_collect_order_id'] = (int) $shopping_user->shopping_collect_order_id;
$data['product_id'] = null;
}
$model->fill($data)->save();
return false;
}
}
return $model->delete();
});
foreach ($items as $item) {
if (!ShoppingOrderItem::where('shopping_order_id', $shopping_order->id)->where('row_id', $item->rowId)->count()){
$price_net = Yard::instance($this->instance)->rowPriceNet($item, 2, '.', '');
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
'price' => $item->price,
'price_net' => $price_net,
'tax_rate' => $item->taxRate,
'tax' => $tax,
'price_vk_net' => $shopping_order->getPriceVkNetBy($item->id),
'discount' => $item->options->no_commission ? 0 : $shopping_order->getUserDiscount(),
'points' => $item->options->points,
'slug' => $item->options->slug
];
if($shopping_user->is_from === 'homeparty'){
$data['homeparty_id'] = (int) $shopping_user->homeparty_id;
$data['price_vk_net'] = 0;
$data['product_id'] = null;
}
if($shopping_user->is_from === 'collection'){
$data['price_vk_net'] = 0;
$data['shopping_collect_order_id'] = (int) $shopping_user->shopping_collect_order_id;
$data['product_id'] = null;
}
$shopping_order_item = ShoppingOrderItem::create($data);
}
}
if($shopping_user->is_from === 'homeparty'){
$shopping_order->makeHomepartyTaxSplit();
}elseif($shopping_user->is_from === 'collection'){
//is set on create / filll.
}else{
$shopping_order->makeTaxSplit();
}
return $shopping_order;
}
public function makeShoppingUser($data){
$data['same_as_billing'] = isset($data['same_as_billing']) ? false : true; //reinvert
$data['accepted_data_checkbox'] = isset($data['accepted_data_checkbox']) ? true : false;
$shopping_user = false;
if($this->getSessionPayments('shopping_user_id')){
$shopping_user = ShoppingUser::find($this->getSessionPayments('shopping_user_id'));
if($shopping_user){
$shopping_user->fill($data);
$shopping_user->mode = null;
$shopping_user->save();
}
}
if(!$shopping_user){
$shopping_user = ShoppingUser::create($data);
}
$this->putSessionPayments('shopping_user_id', $shopping_user->id);
return $shopping_user;
}
public function getPaymentsMethods($is_from, $is_abo = false){
$payment_methods = [];
if($is_from !== 'shopping' && Util::getAuthUser()){
$user = Util::getAuthUser();
$payment_methods['default'] = $user->payment_methods;
$payment_methods['data'] = $user->account->payment_data;
}else{
$payment_methods['default'] = PaymentMethod::getDefaultAsArray($is_abo)->toArray();
$payment_methods['data'] = false;
}
if($is_abo){
$payment_methods['active'] = \App\Models\PaymentMethod::where('active', true)->where('is_abo', true)->get()->pluck( 'id', 'short')->toArray();
}else{
$payment_methods['active'] = \App\Models\PaymentMethod::where('active', true)->get()->pluck( 'id', 'short')->toArray();
}
return $payment_methods;
}
public function isPaymentsMethodsActive($payment_method, $is_from, $is_abo = false){
$payment_names = ['wlt#PPE' => 'PP', 'cc' => 'CC', 'sb#PNT' => 'SB', 'elv' => 'SEPA', 'vor' => 'VOR', 'fnc#MIV' => 'FNC'];
$payment_methods = $this->getPaymentsMethods($is_from, $is_abo);
if(isset($payment_names[$payment_method])){
$payment_with = $payment_names[$payment_method];
if(array_key_exists($payment_with, $payment_methods['active']) && in_array($payment_methods['active'][$payment_with], $payment_methods['default'])){
return true;
}
}
abort(404);
}
public function makeCustomerShoppingUser($shopping_data, $is_for, $is_from){
// $shopping_user = ShoppingUser::findOrFail($shopping_data['shopping_user_id']);
$shopping_user = new ShoppingUser();
$shopping_user->fill($shopping_data);
$shopping_user->faker_mail = false;
$shopping_user->auth_user_id = null;
$shopping_user->homeparty_id = null;
$shopping_user->same_as_billing = $shopping_user->same_as_billing ? false : true; //reinvert
// $shopping_user->id = null;
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
return $shopping_user;
}
public function initShoppingUser($is_for, $is_from, $homeparty_id = null)
{
$shopping_user = new ShoppingUser();
$shopping_user->homeparty_id = $homeparty_id;
$shopping_user->language = \App::getLocale();
//eingeloggter Kunde
if(\Auth::guard('customers')->check()){
$shopping_user = $this->shoppingUserByAuthCustomer(\Auth::guard('customers')->user());
}
//eingeloggter User Berater
if(\Auth::guard('user')->check()){
$shopping_user = $this->shoppingUserByAuthUser(\Auth::guard('user')->user(), $is_from, $is_for);
}
$shopping_user->mode = 'prev';
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
return $shopping_user;
}
public function shoppingUserByAuthCustomer(\App\Models\Customer $user){
//clone shopping user!
if($user->shopping_user_id){
$find_shopping_user = ShoppingUser::find($user->shopping_user_id);
if($find_shopping_user){
$shopping_user = $find_shopping_user->replicate();
$shopping_user->billing_country_id = null;
$shopping_user->shipping_country_id = null;
}
}else{
$shopping_user = new ShoppingUser();
$shopping_user->language = \App::getLocale();
}
return $shopping_user;
}
public function shoppingUserByAuthUser(\App\User $user, $is_from, $is_for){
$shopping_user = new ShoppingUser();
$shopping_user->language = \App::getLocale();
$shopping_user->billing_salutation = $user->account->salutation;
$shopping_user->billing_company = $user->account->company;
$shopping_user->billing_firstname = $user->account->first_name;
$shopping_user->billing_lastname = $user->account->last_name;
$shopping_user->billing_address = $user->account->address;
$shopping_user->billing_address_2 = $user->account->address_2;
$shopping_user->billing_zipcode = $user->account->zipcode;
$shopping_user->billing_city = $user->account->city;
//$shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->accepted_data_checkbox = 1;
//Lieferadresse
$shopping_user->same_as_billing = $user->account->same_as_billing ? false : true;
$shopping_user->shipping_salutation = $user->account->shipping_salutation;
$shopping_user->shipping_company = $user->account->shipping_company;
$shopping_user->shipping_firstname = $user->account->shipping_firstname;
$shopping_user->shipping_lastname = $user->account->shipping_lastname;
$shopping_user->shipping_address = $user->account->shipping_address;
$shopping_user->shipping_address_2 = $user->account->shipping_address_2;
$shopping_user->shipping_zipcode = $user->account->shipping_zipcode;
$shopping_user->shipping_city = $user->account->shipping_city;
//$shopping_user->shipping_country_id = $user->account->shipping_country_id;
$shopping_user->shipping_phone = $user->account->shipping_phone;
return $shopping_user;
}
public function shoppingUserAuthData($is_from, $is_for, $data = []){
$user = Util::getAuthUser();
$shopping_user = new ShoppingUser();
$shopping_user->auth_user_id = $user->id;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
$shopping_user->billing_salutation = $user->account->salutation;
$shopping_user->billing_company = $user->account->company;
$shopping_user->billing_firstname = $user->account->first_name;
$shopping_user->billing_lastname = $user->account->last_name;
$shopping_user->billing_address = $user->account->address;
$shopping_user->billing_address_2 = $user->account->address_2;
$shopping_user->billing_zipcode = $user->account->zipcode;
$shopping_user->billing_city = $user->account->city;
$shopping_user->billing_country_id = $user->account->country_id;
$shopping_user->billing_phone = $user->account->phone;
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
$shopping_user->is_from = $is_from;
$shopping_user->homeparty_id = isset($data['homeparty_id']) ? $data['homeparty_id'] : null;
$shopping_user->shopping_collect_order_id = isset($data['shopping_collect_order_id']) ? $data['shopping_collect_order_id'] : null;
//Lieferadresse
if($is_from === 'user_order'){
if(isset($data['shopping_user_id']) && strpos($data['is_for'], 'ot') !== false){
$s_user = ShoppingUser::findOrFail($data['shopping_user_id']);
/* $shopping_user->billing_salutation = $s_user->billing_salutation;
$shopping_user->billing_company = $s_user->billing_company;
$shopping_user->billing_firstname = $s_user->billing_firstname;
$shopping_user->billing_lastname = $s_user->billing_lastname;
$shopping_user->billing_address = $s_user->billing_address;
$shopping_user->billing_address_2 = $s_user->billing_address_2;
$shopping_user->billing_zipcode = $s_user->billing_zipcode;
$shopping_user->billing_city = $s_user->billing_city;
$shopping_user->billing_country_id = $s_user->billing_country_id;
$shopping_user->billing_phone = $s_user->billing_phone;
$shopping_user->billing_email = $s_user->billing_email;
;*/
$shopping_user->faker_mail = $s_user->faker_mail;
if(!$s_user->faker_mail){
$shopping_user->shipping_email = $s_user->billing_email;
}
$shopping_user->shopping_user_id = $data['shopping_user_id'];
$shopping_user->member_id = $s_user->member_id;
}
$shopping_user->same_as_billing = true;
$shopping_user->shipping_salutation = isset($data['shipping_salutation']) ? $data['shipping_salutation'] : '';
$shopping_user->shipping_company = isset($data['shipping_company']) ? $data['shipping_company'] : '';
$shopping_user->shipping_firstname = isset($data['shipping_firstname']) ? $data['shipping_firstname'] : '';
$shopping_user->shipping_lastname = isset($data['shipping_lastname']) ? $data['shipping_lastname'] : '';
$shopping_user->shipping_address = isset($data['shipping_address']) ? $data['shipping_address'] : '';
$shopping_user->shipping_address_2 = isset($data['shipping_address_2']) ? $data['shipping_address_2'] : '';
$shopping_user->shipping_zipcode = isset($data['shipping_zipcode']) ? $data['shipping_zipcode'] : '';
$shopping_user->shipping_city = isset($data['shipping_city']) ? $data['shipping_city'] : '';
$shopping_user->shipping_country_id = Yard::instance($this->instance)->getShippingCountryCountryId();
$shopping_user->shipping_phone = isset($data['shipping_phone']) ? $data['shipping_phone'] : '';
}else{
$shopping_user->same_as_billing = $user->account->same_as_billing ? false : true;
$shopping_user->shipping_salutation = $user->account->shipping_salutation;
$shopping_user->shipping_company = $user->account->shipping_company;
$shopping_user->shipping_firstname = $user->account->shipping_firstname;
$shopping_user->shipping_lastname = $user->account->shipping_lastname;
$shopping_user->shipping_address = $user->account->shipping_address;
$shopping_user->shipping_address_2 = $user->account->shipping_address_2;
$shopping_user->shipping_zipcode = $user->account->shipping_zipcode;
$shopping_user->shipping_city = $user->account->shipping_city;
$shopping_user->shipping_country_id = $user->account->shipping_country_id;
$shopping_user->shipping_phone = $user->account->shipping_phone;
}
return $shopping_user;
}
public function putSessionPayments($key, $value){
$content = $this->getContent();
$content->put($key, $value);
$this->session->put($this->instance, $content);
}
public function getSessionPayments($key){
$content = $this->getContent();
if ($content->has($key)){
return $content->get($key);
}
return false;
}
public function sessionDestroy($with_shopping = false)
{
if($with_shopping){
if(session('user_shop_payment') === 1){ //ShoppingInstance payment 1 = webshop
Yard::instance('webshop')->destroy();
}else{
Yard::instance('shopping')->destroy();
}
}
$this->session->remove($this->instance);
}
private function getContent()
{
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
}

View file

@ -0,0 +1,144 @@
<?php
namespace App\Repositories;
use App\Libraries\ContractPDF;
use App\Models\File;
use App\User;
use Storage;
class ContractPDFRepository extends BaseRepository {
protected $disk;
protected $dir;
protected $user_id;
protected $identifier;
public function __construct(User $model){
$this->model = $model;
}
public function _set($name, $value){
$this->{$name} = $value;
}
private function convert($str){
$search = array('Ő', 'ő', 'Ű', 'ű');
$replace = array('Ö', 'ö', 'Ü', 'ü');
$str = str_replace($search, $replace, $str);
return iconv('UTF-8', 'windows-1252//IGNORE', $str);
}
public function createContractPDF() {
$pdf = new ContractPDF();
$pdf->AddPage('P', array(210, 297));
$pdf->SetFont('Helvetica', '', 11);
$pdf->SetDrawColor(160, 160, 160);
$x1 = 16.5;
$x2 = 109;
$y = 70;
$nl = 17.5;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->m_account));
$pdf->SetXY($x2, $y);
$pdf->Write(0, now()->format("d.m.Y"));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->company));
$pdf->SetXY($x2, $y);
$pre = $this->model->account->pre_phone_id != "" ? $this->convert($this->model->account->pre_phone->phone)." " : "";
$pdf->Write(0, $pre.$this->convert($this->model->account->phone));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->m_first_name));
$pdf->SetXY($x2, $y);
$pre = $this->model->account->pre_mobil_id != "" ? $this->convert($this->model->account->pre_mobil->phone)." " : "";
$pdf->Write(0, $pre.$this->convert($this->model->account->mobil));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->m_last_name));
$pdf->SetXY($x2, $y);
$pdf->Write(0, $this->convert($this->model->email));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->address));
$pdf->SetXY($x2, $y);
$pdf->Write(0, $this->convert($this->model->account->birthday));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->zipcode)." ".$this->convert($this->model->account->city));
$y += $nl;
$pdf->SetXY($x1, $y);
$pre = $this->model->account->country_id ? $this->convert($this->model->account->country->de)." " : "";
$pdf->Write(0, $pre);
if($this->model->m_sponsor && $this->model->user_sponsor->account){
$y += 48;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->company));
$pdf->SetXY($x2, $y);
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->m_account));
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->user_sponsor->account->m_first_name)." ".$this->convert($this->model->user_sponsor->account->m_last_name));
$website = $this->model->user_sponsor->shop()->count() ? $this->model->user_sponsor->shop->getSubdomain(false) : "www.mivita.care";
}else{
$website = "www.mivita.care";
}
$pdf->AddPage('P', array(210, 297));
$pdf->SetFont('Helvetica', '', 10);
$pdf->SetDrawColor(160, 160, 160);
$pdf->SetXY(52, 56);
$pdf->Write(0, $website);
$pdf->SetXY($x1, 65);
$pdf->Write(0, $this->convert($this->model->account->m_first_name)." ".$this->convert($this->model->account->m_last_name));
$pdf->SetXY($x2, 65);
$pdf->Write(0, $this->convert($this->model->account->m_account));
$pdf->AddPage('P', array(210, 297));
if(!Storage::disk($this->disk)->exists( $this->dir )){
Storage::disk($this->disk)->makeDirectory($this->dir); //creates directory
}
$filename = "MIVITA_Beratervertrag.pdf";
Storage::disk($this->disk)->put($this->dir.$filename, $pdf->Output('S'));
$size = Storage::disk($this->disk)->size($this->dir.$filename);
$mine = Storage::disk($this->disk)->mimeType($this->dir.$filename);
File::create([
'user_id' => $this->model->id,
'identifier' => $this->identifier,
'filename' => $filename,
'dir' => $this->dir,
'original_name' => $filename,
'ext' => "pdf",
'mine' => $mine,
'size' => $size
]);
return true;
}
}

View file

@ -0,0 +1,369 @@
<?php
namespace App\Repositories;
use PDF;
use Storage;
use App\User;
use App\Services\Credit;
use App\Models\UserCredit;
use Response;
use App\Libraries\MyPDFMerger;
use App\Models\UserCreditItem;
use App\Models\UserSalesVolume;
use App\Libraries\CreditDetailsPDF;
use App\Services\BusinessPlan\TreeCalcBot;
class CreditRepository extends BaseRepository {
private $user_credit;
public function __construct(User $model)
{
$this->model = $model;
}
public function create($request = [])
{
//need invoice $data
$number = Credit::getCreditNumber();
$credit_date = isset($request['credit_date']) ? $request['credit_date'] : \Carbon::now()->format("d.m.Y");
$credit_send_mail = isset($request['credit_send_mail']) ? true: false;
$credit_number = Credit::createCreditNumber($number, $credit_date);
$this->user_credit = new UserCredit();
$user_credit_items = $this->makeUserCredit();
if(!count($user_credit_items)){
return false;
}
$data = [
'user' => $this->model,
'credit_date' => $credit_date,
'credit_number' => $credit_number,
'user_credits' => $this->user_credit,
'user_credit_items' => $user_credit_items,
];
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$dir = Credit::getCreditStorageDir($credit_date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
}
$path = Storage::disk('public')->path('');
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
Storage::disk('public')->put($dir.$filename, $file);
$this->user_credit->user_id = $this->model->id;
$this->user_credit->year = \Carbon::parse($credit_date)->format('Y');
$this->user_credit->month = \Carbon::parse($credit_date)->format('n');
$this->user_credit->date = $credit_date;
$this->user_credit->filename = $filename;
$this->user_credit->dir = $dir;
$this->user_credit->disk = 'public';
$this->user_credit->number = $number;
$this->user_credit->full_number = $credit_number;
$this->user_credit->save();
if($credit_send_mail){
Credit::sendCreditMail($this->user_credit);
}
$this->finishUserCredit($this->user_credit->id, $user_credit_items);
return true;
}
private function finishUserCredit($user_credit_id, $user_credit_items){
//next credits
Credit::makeNextCreditNumber();
//mark as payed
//$UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach($user_credit_items as $user_credit_item){
$user_credit_item->paid = true;
$user_credit_item->user_credit_id = $user_credit_id;
$user_credit_item->save();
}
}
private function makeUserCredit(){
$this->user_credit->net = 0;
$this->user_credit->infos = [];
$infos = [];
$user_credit_items = [];
$UserCreditItems = UserCreditItem::where('user_id', $this->model->id)->wherePaid(false)->get();
foreach($UserCreditItems as $userCreditItem){
$user_credit_items[] = $userCreditItem;
$infos[] = ['id' => $userCreditItem->id, 'credit' => $userCreditItem->credit];
$this->user_credit->net += $userCreditItem->credit;
}
/* taxable_sales //user tax
1 //umsatzsteuerpflichtig / DE
2 // nicht umsatzsteuerpflichtig /DE
3 // nicht umsatzsteuerpflichtig / Ausland
*/
if($this->model->account){
$this->user_credit->taxable = $this->model->account->taxable_sales;
if($this->model->account->country_id !== 1){
$this->user_credit->taxable = 3;
}
if($this->user_credit->taxable === 1){
$this->user_credit->tax_rate = config('app.main_tax_rate');
$this->user_credit->total = round($this->user_credit->net * config('app.main_tax'), 2);
$this->user_credit->tax = $this->user_credit->total - $this->user_credit->net;
}else{
$this->user_credit->tax_rate = 0;
$this->user_credit->total = $this->user_credit->net;
$this->user_credit->tax = 0;
}
}
$this->user_credit->infos = $infos;
return $user_credit_items;
}
/*
Erstellt einen detalierten Report zur Gutschrift
Alle Postionen werden einzeln aufgelistet
//$do ?= html, pdf
*/
public function create_report(UserCredit $user_credit, $do = 'html')
{
//collect all data
$collection = new \stdClass();
$collection->calc_bot = [];
$collection->commission_shop = [];
$collection->commission_payline = [];
$collection->commission_growth_bonus = [];
$collection->own_order = [];
$collection->commission_registration = [];
$collection->commission_credit = [];
$dates = [];
/* für jede Postion aus der Gutschrift nach Status */
foreach($user_credit->user_credit_items as $user_credit_item){
$date = $user_credit_item->from_month.'-'.$user_credit_item->from_year;
if(!isset($dates[$date])){
$dates[$date] = ['year' => $user_credit_item->from_year, 'month' => $user_credit_item->from_month];
}
/*
//calc bot for the month year
*/
if(!isset($collection->calc_bot[$date])){
$TreeCalcBot = new TreeCalcBot($user_credit_item->from_month, $user_credit_item->from_year, 'admin');
$TreeCalcBot->initBusinesslUserDetail($user_credit->user);
$TreeCalcBot->initStructureUser($user_credit->user->id);
$collection->calc_bot[$date] = $TreeCalcBot;
}
/*
status === 1 commission_shop
Auswertung der Shopbestellungen vom User für einen Monat / Jahr
Auslistung der Positonen / Gesamter Umsatz / Marge / Provision
*/
if($user_credit_item->status === 1){
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) //'shoporder', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$user_sales_volumes_total = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 2) //'shoporder', //hinzugefügt aus
->orderBy('id', 'DESC')->first();
$obj = new \stdClass();
$obj->user_sales_volumes = $user_sales_volumes;
$obj->user_sales_volumes_total = $user_sales_volumes_total;
$obj->user_credit_item = $user_credit_item;
$collection->commission_shop[$date] = $obj;
/*
UserSalesVolume::status
4 => 'credit', //hinzugefügt aus //VE == status_turnover 2 shop verrechnung
Listen der hinzufegügten Gutschriften vom User für einen Monat / Jahr
*/
$user_sales_volumes_credit = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $user_credit_item->from_month)
->where('year', $user_credit_item->from_year)
->where('status', 4) //'credit', //hinzugefügt aus
->where('status_turnover', 2) //VE shop
->orderBy('id', 'ASC')->get();
$collection->commission_credit[$date] = $user_sales_volumes_credit;
}
/*
status === 2 commission_payline
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
/*
status === 5 commission_growth_bonus
Auswertung der Payline nach der Struktur vom User für einen Monat / Jahr
Auslistung aller Berater mit Gesamter Umsatz / Provision / rang
*/
}
/*
nicht enhalten in der Gutschrift
für alle Monate / Jahr die in der Gutschrift enthalten sind
*/
foreach($dates as $date => $dateObj){
/*
UserSalesVolume::status
1 => 'advisor_order', own_order //hinzugefügt aus
Listen der Beraterbestellungen vom User für einen Monat / Jahr
*/
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->sum('total_net'); //sum('total_net');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 1) //'own_order', //hinzugefügt aus
->sum('points'); //sum('points');
if($user_sales_volumes->count() > 0){
$obj = new \stdClass();
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->own_order[$date] = $obj;
}
/*
UserSalesVolume::status
5 => 'registration', //hinzugefügt aus
Listen der Gutschriften aus Reg vom User für einen Monat / Jahr
Enthält nur Punkte wird separat aufgeführt
turnover = immer E / 1 verrechnung mit Eigenem Umsatz
*/
$user_sales_volumes = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->orderBy('id', 'ASC')->get();
$credit_total_net = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->sum('total_net'); //sum('total_net');
$credit_total_points = UserSalesVolume::where('user_id', $user_credit_item->user_id)
->where('month', $dateObj['month'])
->where('year', $dateObj['year'])
->where('status', 5) //'registration', //hinzugefügt aus
->sum('points'); //sum('points');
if($user_sales_volumes->count() > 0){
$obj = new \stdClass();
$obj->user_sales_volumes = $user_sales_volumes;
$obj->credit_total_net = $credit_total_net;
$obj->credit_total_points = $credit_total_points;
$collection->commission_registration[$date] = $obj;
}
}
/*
//need this?
$user_credit_item->status = 3; //credit_added
$user_credit_item->status = 4; //commission
*/
$data = [
'dates' => $dates,
'user_credit' => $user_credit,
'collection' => $collection,
];
if($do === 'html'){
return view('admin.payment.credit_detail', $data);
}
if($do === 'pdf'){
$dir = Credit::getCreditDetailStorageDir($user_credit->date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
}
$path = Storage::disk('public')->path('');
$filename = Credit::makeCreditDetailFilename($user_credit->full_number);
$pdf = new CreditDetailsPDF('pdf.credit_details');
//return $pdf->create($data, 'credit_details.pdf', 'stream');
$pdf->create($data, $filename, 'save', $path.$dir);
/*$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);*/
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_report_de');
Storage::disk('public')->put($dir.$filename, $file);
$path = $dir.$filename;
//$file = Storage::disk('public')->get($path);
$mime = Storage::disk('public')->mimeType($path);
return Response::make($file, 200)
->header("Content-Type", $mime)
->header('Content-disposition','inline; filename="'.$filename.'"');
//return $dir.$filename;
/*
$dir = Credit::getCreditStorageDir($credit_date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
}
$path = Storage::disk('public')->path('');
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
Storage::disk('public')->put($dir.$filename, $file);
*/
}
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace App\Repositories;
class CustomerRepository extends BaseRepository {
public function __construct()
{
//$this->model = $model;
}
public function update($data)
{
/*if($data['user_id'] === "new" || $data['user_id'] == 0){
$this->model = User::create([
'email' => $data['email'],
'password' => env('APP_KEY'),
]);
}
else{
$this->model = $this->getById($data['user_id']);
}
if(!$this->model->account_id){
$account = new UserAccount();
}else{
$account = $this->model->account;
}
$data['same_as_billing'] = !isset($data['same_as_billing']) ? 0 : 1;
$account->fill($data)->save();
if(!$this->model->account_id){
$this->model->account_id = $account->id;
$this->model->save();
}*/
return true;
}
public function create($data){
/* $this->model = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$account = UserAccount::create([
'm_salutation' => $data['salutation'],
'm_first_name' => $data['first_name'],
'm_last_name' => $data['last_name'],
'salutation' => $data['salutation'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
]);
$this->model->account_id = $account->id;
$this->model->save();
return $this->model;*/
}
}

View file

@ -0,0 +1,219 @@
<?php
namespace App\Repositories\DC;
use App\Models\DcFile;
use App\Services\Util;
use App\Models\DcFileTag;
use App\Repositories\BaseRepository;
use Intervention\Image\ImageManager;
use Imagick;
use ImagickException;
class FileRepository extends BaseRepository {
private const ALLOWED_IMAGE_TYPES = [
'image/jpeg',
'image/gif',
'image/png'
];
private const ALLOWED_PDF_TYPES = [
'application/pdf'
];
private const THUMB_WIDTH = 542;
private const THUMB_HEIGHT = 360;
private const BIG_WIDTH = 1600;
private const BIG_HEIGHT = 900;
public function uploadFile(array $form_data): DcFile
{
if (!isset($form_data['file']) || !$form_data['file']->isValid()) {
throw new \InvalidArgumentException('Invalid file provided');
}
$file = $form_data['file'];
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$mine = $file->getClientMimeType();
$size = $file->getSize();
$originalNameWithoutExt = substr($originalName, 0, strlen($originalName) - strlen($extension) - 1);
$filename = Util::sanitize($originalNameWithoutExt, true, false, true);
$allowed_filename = uniqid() . '_' . $filename.".".$extension;
$file->storeAs('dc/files', $allowed_filename, 'public');
// $store = $file->store('files/');
$dc_file = DcFile::create([
'filename' => $allowed_filename,
'original_name' => $originalName,
'ext' => $extension,
'mine' => $mine,
'size' => $size
]);
$this->makeThumbFromFile($dc_file);
return $dc_file;
}
public function makeThumb(int $id): bool
{
$file = DcFile::findOrFail($id);
$this->makeThumbFromFile($file);
return true;
}
public function makeThumbFromFile(DcFile $file): bool
{
try {
$path = $file->getFile(true);
if (!file_exists($path)) {
throw new \Exception('File not found');
}
$filename = $file->filename;
$mime = \File::mimeType($path);
if (in_array($mime, self::ALLOWED_IMAGE_TYPES)) {
$this->processImage($path, $filename);
} elseif (in_array($mime, self::ALLOWED_PDF_TYPES)) {
$this->processPdf($path, $filename);
}
return true;
} catch (\Exception $e) {
\Log::error('Thumbnail creation failed: ' . $e->getMessage());
return false;
}
}
private function processImage(string $path, string $filename): void
{
// ImageManager initialisieren (standardmäßig mit GD)
$manager = ImageManager::gd();
// Thumbnail
$thumbImage = $manager->read($path);
$thumbImage->scaleDown(width: self::THUMB_WIDTH, height: self::THUMB_HEIGHT);
\Storage::disk('public')->put('dc/thumb/'.basename($filename), (string) $thumbImage->toJpeg());
// Big image
$bigImage = $manager->read($path);
$bigImage->scaleDown(width: self::BIG_WIDTH, height: self::BIG_HEIGHT);
\Storage::disk('public')->put('dc/big/'.basename($filename), (string) $bigImage->toJpeg());
// Ressourcen freigeben nicht mehr nötig in v3
// $thumbImage->destroy();
// $bigImage->destroy();
}
private function processPdf(string $path, string $filename): void
{
try {
// PDF mit höherer Auflösung rendern
$imagick = new \Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage($path.'[0]');
// Grundlegende Bildoptimierungen
$imagick->setImageBackgroundColor('#ffffff');
$imagick->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$imagick->setImageFormat('jpg');
$imagick->setImageCompression(\Imagick::COMPRESSION_JPEG);
$imagick->setImageCompressionQuality(80);
// Große Version erstellen
$bigImage = clone $imagick;
$bigImage->resizeImage(self::BIG_WIDTH, self::BIG_HEIGHT, \Imagick::FILTER_LANCZOS, 1, true);
$bigImage->writeImage(\Storage::disk('public')->path('dc/big/').basename($filename).'.jpg');
$bigImage->clear();
// Thumbnail erstellen
$imagick->resizeImage(self::THUMB_WIDTH, self::THUMB_HEIGHT, \Imagick::FILTER_LANCZOS, 1, true);
$imagick->writeImage(\Storage::disk('public')->path('dc/thumb/').basename($filename).'.jpg');
// Ressourcen freigeben
$imagick->clear();
} catch (\ImagickException $e) {
\Log::error('PDF Verarbeitung fehlgeschlagen: ' . $e->getMessage());
throw new \RuntimeException('PDF Verarbeitung fehlgeschlagen: ' . $e->getMessage());
} finally {
if (isset($bigImage)) {
$bigImage->destroy();
}
if (isset($imagick)) {
$imagick->destroy();
}
}
}
public function tagsUpdate($id, array $tags = []): bool
{
$file = DcFile::findOrFail($id);
// Get existing tags
$existingTags = DcFileTag::where('file_id', $file->id)
->pluck('tag_id')
->toArray();
// Delete removed tags
$tagsToDelete = array_diff($existingTags, $tags);
if (!empty($tagsToDelete)) {
DcFileTag::where('file_id', $file->id)
->whereIn('tag_id', $tagsToDelete)
->delete();
}
// Add new tags
$tagsToAdd = array_diff($tags, $existingTags);
$newTags = [];
foreach ($tagsToAdd as $tagId) {
$newTags[] = [
'file_id' => $file->id,
'tag_id' => $tagId
];
}
if (!empty($newTags)) {
DcFileTag::insert($newTags);
}
return true;
}
private function deleteFileIfExists(string $path): void
{
if (file_exists($path)) {
unlink($path);
}
}
public function deleteThumb($id): bool
{
try {
$file = DcFile::findOrFail($id);
$this->deleteFileIfExists($file->getThumb(true));
$this->deleteFileIfExists($file->getBig(true));
return true;
} catch (\Exception $e) {
\Log::error('Thumbnail deletion failed: ' . $e->getMessage());
return false;
}
}
public function deleteFile(int $id): bool
{
try {
$file = DcFile::findOrFail($id);
$this->deleteFileIfExists($file->getThumb(true));
$this->deleteFileIfExists($file->getBig(true));
$this->deleteFileIfExists($file->getFile(true));
$file->delete();
return true;
} catch (\Exception $e) {
\Log::error('File deletion failed: ' . $e->getMessage());
return false;
}
}
}

View file

@ -0,0 +1,141 @@
<?php
namespace App\Repositories\DC;
use Request;
use App\Models\DcTag;
use App\Models\DcCategory;
use App\Repositories\BaseRepository;
class TagRepository extends BaseRepository {
public function __construct()
{
}
public function storeItem($obj, $data)
{
if($obj === 'category' && isset($data['dc_category_name'])){
$category = new DcCategory;
$category->name = $data['dc_category_name'];
$category->pos = 0 ;
$category->save();
\Session()->flash('alert-success', 'Kategorie erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'tag' && isset($data['dc_tag_name'])){
$data = Request::all();
$tag = new DcTag;
$tag->name = $data['dc_tag_name'];
$tag->pos = 0;
$tag->save();
\Session()->flash('alert-success', 'Tag erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'structure' && isset($data['nestable'])){
$bool = $this->updateStructure($data);
if(Request::ajax()){
return response()->json([
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true])
]);
}
}
if($obj === 'update_ajax' && isset($data['action'])){
$active = $this->updateAjax($data);
if(Request::ajax()){
return response()->json([
'success' => $data['action'],
'active' => $active,
]);
}
}
return true;
}
protected function updateAjax($data){
if($data['action'] == 'update-tag-active' && isset($data['id'])){
$tag = DcTag::findOrFail($data['id']);
$tag->active = $tag->active ? 0 : 1;
$tag->save();
return $tag->active;
}
if($data['action'] == 'update-category-active' && isset($data['id'])){
$category = DcCategory::findOrFail($data['id']);
$category->active = $category->active ? 0 : 1;
$category->save();
return $category->active;
}
return false;
}
protected function updateStructure($data)
{
if(empty($data['nestable']) || !is_array($data['nestable'])){
return false;
}
$tags = DcTag::all();
foreach ($tags as $value) {
$value->category_id = null;
$value->pos = NULL;
$value->save();
}
$this->saveStructureLevel($data['nestable']);
return true;
}
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false){
foreach ($nestable as $key => $value) {
if($value['id'] == 0){
continue;
}
if($deep == 0){
$cat = DcCategory::findOrFail($value['id']);
$cat->pos = $key;
$cat->save();
}
if($deep == 1){
$tag = DcTag::findOrFail($value['id']);
$tag->category_id = $category_id;
$tag->pos = $key;
$tag->save();
}
if(!empty($value['children'])){
$this->saveStructureLevel($value['children'], $deep+1, $value['id']);
}
}
}
public function deleteItem($obj, $id){
if($obj == 'category'){
$this->deleteCategory($id);
}
if($obj == 'tag'){
$this->deleteTag($id);
}
}
public function deleteCategory($id){
$cat = DcCategory::findOrFail($id);
$tags = DcTag::where('category_id', $cat->id)->get();
foreach ($tags as $tag) {
$this->deleteTag($tag->id);
}
$cat->delete();
}
public function deleteTag($id){
$tag = DcTag::findOrFail($id);
$tag->delete();
}
}

View file

@ -0,0 +1,151 @@
<?php
namespace App\Repositories;
use Request;
use App\Models\DcTag;
use App\Models\DcFile;
use App\Models\DcCategory;
class DcRepository extends BaseRepository {
public function __construct()
{
}
public function makeThumb($id){
$file = DcFile::findOrFail($id);
$file->makeThumb();
}
public function deleteFile($id){
$file = DcFile::findOrFail($id);
$file->delete();
}
public function storeItem($obj, $data)
{
if($obj === 'category' && isset($data['dc_category_name'])){
$category = new DcCategory;
$category->name = $data['dc_category_name'];
$category->pos = 0 ;
$category->save();
\Session()->flash('alert-success', 'Kategorie erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'tag' && isset($data['dc_tag_name'])){
$data = Request::all();
$tag = new DcTag;
$tag->name = $data['dc_tag_name'];
$tag->pos = 0;
$tag->save();
\Session()->flash('alert-success', 'Tag erstellt');
return redirect(route('admin_downloadcenter_tags'));
}
if($obj === 'structure' && isset($data['nestable'])){
$bool = $this->updateStructure($data);
if(Request::ajax()){
return response()->json([
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true])
]);
}
}
if($obj === 'update_ajax' && isset($data['action'])){
$active = $this->updateAjax($data);
if(Request::ajax()){
return response()->json([
'success' => $data['action'],
'active' => $active,
]);
}
}
return true;
}
protected function updateAjax($data){
if($data['action'] == 'update-tag-active' && isset($data['id'])){
$tag = DcTag::findOrFail($data['id']);
$tag->active = $tag->active ? 0 : 1;
$tag->save();
return $tag->active;
}
if($data['action'] == 'update-category-active' && isset($data['id'])){
$category = DcCategory::findOrFail($data['id']);
$category->active = $category->active ? 0 : 1;
$category->save();
return $category->active;
}
return false;
}
protected function updateStructure($data)
{
if(empty($data['nestable']) || !is_array($data['nestable'])){
return false;
}
$tags = DcTag::all();
foreach ($tags as $value) {
$value->category_id = null;
$value->pos = NULL;
$value->save();
}
$this->saveStructureLevel($data['nestable']);
return true;
}
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false){
foreach ($nestable as $key => $value) {
if($value['id'] == 0){
continue;
}
if($deep == 0){
$cat = DcCategory::findOrFail($value['id']);
$cat->pos = $key;
$cat->save();
}
if($deep == 1){
$tag = DcTag::findOrFail($value['id']);
$tag->category_id = $category_id;
$tag->pos = $key;
$tag->save();
}
if(!empty($value['children'])){
$this->saveStructureLevel($value['children'], $deep+1, $value['id']);
}
}
}
public function deleteItem($obj, $id){
if($obj == 'category'){
$this->deleteCategory($id);
}
if($obj == 'tag'){
$this->deleteTag($id);
}
}
public function deleteCategory($id){
$cat = DcCategory::findOrFail($id);
$tags = DcTag::where('category_id', $cat->id)->get();
foreach ($tags as $tag) {
$this->deleteTag($tag->id);
}
$cat->delete();
}
public function deleteTag($id){
$tag = DcTag::findOrFail($id);
$tag->delete();
}
}

View file

@ -0,0 +1,93 @@
<?php
namespace App\Repositories;
use App\Models\File;
use Request;
use Response;
use Storage;
use Util;
use Validator;
class FileRepository extends BaseRepository {
protected $rules;
protected $messages;
protected $disk;
protected $dir;
protected $user_id;
protected $identifier;
public function __construct(File $model){
$this->model = $model;
$this->rules = [
'file' => 'required|mimes:pdf,jpeg,png|max:32768'
];
$this->messages = [
'file.mimes' => 'Datei ist kein PDF Format',
'file.required' => 'PDF-Datei wird benötigt'
];
}
public function _set($name, $value){
$this->{$name} = $value;
}
public function uploadFile( $form_data )
{
$validator = Validator::make($form_data, $this->rules, $this->messages);
if ($validator->fails()) {
return Response::json([
'error' => true,
'message' => $validator->messages()->first(),
'code' => 400
], 400);
}
$file = $form_data['file'];
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$mine = $file->getClientMimeType();
$size = $file->getSize();
$originalNameWithoutExt = substr($originalName, 0, strlen($originalName) - strlen($extension) - 1);
$filename = Util::sanitize($originalNameWithoutExt, true, false, true);
$allowed_filename = uniqid() . '_' . $filename.".".$extension;
//$dir = $this->model->getInvoiceStorageAttDir();
if(!Storage::disk($this->disk)->exists( $this->dir )){
Storage::disk($this->disk)->makeDirectory($this->dir); //creates directory
}
Storage::disk($this->disk)->put($this->dir.$allowed_filename, file_get_contents($file->getRealPath()));
File::create([
'user_id' => $this->user_id,
'identifier' => $this->identifier,
'filename' => $allowed_filename,
'dir' => $this->dir,
'original_name' => $originalName,
'ext' => $extension,
'mine' => $mine,
'size' => $size
]);
return Response::json([
'error' => false,
'filename' => $allowed_filename,
'filedata' => 'pdf',
'redirect' => $form_data['redirect'],
'code' => 200
], 200);
}
}

View file

@ -0,0 +1,154 @@
<?php
namespace App\Repositories;
use App\Models\Country;
use App\Models\ShoppingUser;
use Validator;
use Response;
use Excel;
use Storage;
use App\Models\Import;
class ImportRepository extends BaseRepository {
public function __construct(){
}
public function upload( $form_data )
{
$validator = Validator::make($form_data, Import::$rules, Import::$messages);
if ($validator->fails()) {
return Response::json([
'error' => true,
'message' => $validator->messages()->first(),
'code' => 400
], 400);
}
$file = $form_data['file'];
$originalName = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$originalNameWithoutExt = substr($originalName, 0, strlen($originalName) - strlen($extension) - 1);
$filename = $this->sanitize($originalNameWithoutExt);
$allowed_filename = $filename.".".$extension;
Storage::disk('import')->put($allowed_filename, file_get_contents($file->getRealPath()));
return Response::json([
'error' => false,
'filename' => $allowed_filename,
'filedata' => 'xls',
'redirect' => url(route('sysadmin_import_show', ['xls', $allowed_filename])),
'code' => 200
], 200);
}
public function read($type, $file, $skip, $limit)
{
if(!Storage::disk('import')->has($file)){
return false;
}
return $this->import(storage_path("app/import/").$file, $file, $skip, $limit);
}
protected function import($file_path, $file, $skip, $limit){
$salutation = array(1 => 'mr', 2 => 'ms', 3=>null);
$ret = [
'count' => 0,
'not' => 0,
'imported' => [],
'has_imported' => [],
];
/*
* wp_order_number
wp_order_date
billing_company
billing_salutation
billing_firstname
billing_lastname
billing_address
billing_address_2
billing_zipcode
billing_city
billing_country_code
billing_country
billing_email
billing_phone
shipping_salutation
shipping_company
shipping_firstname
shipping_lastname
shipping_address
shipping_address_2
shipping_zipcode
shipping_city
shipping_country_code
shipping_country
*/
$rows = Excel::toArray(new \App\Imports\ImportCollection(), $file_path);
foreach ($rows[0] as $row){
$ret['count']++;
if(isset($row['billing_email'])){
if(ShoppingUser::where('billing_email', '=', $row['billing_email'])->count() > 0){
$ssuser = ShoppingUser::where('billing_email', '=', $row['billing_email'])->first();
if($ssuser->member_id){
$ret['has_imported'][] = $row['billing_email']." - ".$ssuser->member->email;
continue;
}
}
$row['billing_salutation'] = $salutation[$row['billing_salutation']];
$row['billing_country_id'] = Country::getCountryIdByCodeOrOne($row['billing_country_code']);
$row['billing_phone'] = strlen($row['billing_phone']) <= 3 ? '' : $row['billing_phone'];
$row['same_as_billing'] = true;
if(isset($row['shipping_salutation']) && $row['shipping_salutation'] > 0){
$row['shipping_salutation'] = $salutation[$row['shipping_salutation']];
$row['shipping_country_id'] = Country::getCountryIdByCodeOrOne($row['shipping_country_code']);
$row['same_as_billing'] = false;
}
$row['member_id'] = 3;
$row['number'] = ShoppingUser::max('number') + 1;
$row['has_buyed'] = true;
$row['subscribed'] = false;
$ret['imported'][] = $row['billing_email'];
ShoppingUser::create($row);
}else{
$ret['not']++;
}
}
return $ret;
}
public function sanitize($string, $force_lowercase = true, $anal = 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 ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
}

View file

@ -0,0 +1,163 @@
<?php
namespace App\Repositories;
use PDF;
use Storage;
use App\Services\Invoice;
use App\Models\UserInvoice;
use App\Libraries\InvoicePDF;
use App\Models\ShoppingOrder;
use App\Libraries\MyPDFMerger;
use App\Services\UserService;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\SalesPointsVolume;
class InvoiceRepository extends BaseRepository {
/** @var \App\Models\ShoppingOrder */
protected $model;
private $invoice_date;
private $invoice_number;
private $filename;
private $dir;
private $user_sales_volume;
private $delivery_dir;
private $delivery_filename;
public function __construct(ShoppingOrder $model)
{
$this->model = $model;
}
public function create($request = [])
{
//need invoice $data
$number = Invoice::getInvoiceNumber();
if($payt = $this->model->getLastShoppingPaymentTransaction()){
$invoice_date = $payt->created_at->format("d.m.Y");
}
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $invoice_date;
$invoice_send_mail = isset($request['invoice_send_mail']) ? false : true;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->delivery_dir = Invoice::getDeliveryStorageDir($this->invoice_date);
$this->delivery_filename = Invoice::makeDeliveryFilename($this->invoice_number);
$this->makePDF();
$user_invoice = UserInvoice::create([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($this->invoice_date)->format('Y'),
'month' => \Carbon::parse($this->invoice_date)->format('m'),
'date' => $this->invoice_date,
'full_number' => $this->invoice_number,
'number' => $number,
'filename' => $this->filename,
'dir' => $this->dir,
'delivery_filename' => $this->delivery_filename,
'delivery_dir' => $this->delivery_dir,
'disk' => 'public',
'status' => $this->model->getStatusByOrder()
]);
Invoice::makeNextInvoiceNumber();
if($invoice_send_mail){
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
}
public function update($request = []){
if($user_invoice = $this->model->user_invoice){
$number = $user_invoice->number;
$this->invoice_date = isset($request['invoice_date']) ? $request['invoice_date'] : $user_invoice->date;
$invoice_send_mail = isset($request['invoice_send_mail']) ? false: true;
$this->invoice_number = Invoice::createInvoiceNumber($number, $this->invoice_date);
$this->dir = Invoice::getInvoiceStorageDir($this->invoice_date);
$this->filename = Invoice::makeInvoiceFilename($this->invoice_number);
$this->delivery_dir = Invoice::getDeliveryStorageDir($this->invoice_date);
$this->delivery_filename = Invoice::makeDeliveryFilename($this->invoice_number);
$this->user_sales_volume = UserSalesVolume::where('user_invoice_id', $this->model->user_invoice->id)->first();
$this->makePDF();
$user_invoice->fill([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($this->invoice_date)->format('Y'),
'month' => \Carbon::parse($this->invoice_date)->format('m'),
'date' => $this->invoice_date,
'full_number' => $this->invoice_number,
'number' => $number,
'filename' => $this->filename,
'dir' => $this->dir,
'delivery_filename' => $this->delivery_filename,
'delivery_dir' => $this->delivery_dir,
'disk' => 'public',
])->save();
if($invoice_send_mail){
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
}
return null;
}
private function makePDF(){
$data = [
'shopping_order' => $this->model,
'invoice_date' => $this->invoice_date,
'invoice_number' => $this->invoice_number,
'user_sales_volume' => $this->user_sales_volume,
];
if($this->model->auth_user_id){
UserService::checkUserTaxShippingCountry($this->model->auth_user, $this->model->country_id);
$data = array_merge($data, UserService::getYardInfo());
}
if(!Storage::disk('public')->exists( $this->dir )){
Storage::disk('public')->makeDirectory($this->dir); //creates directory
}
if(!Storage::disk('public')->exists( $this->delivery_dir )){
Storage::disk('public')->makeDirectory($this->delivery_dir); //creates directory
}
$path = Storage::disk('public')->path('');
//invoice
$pdf_file = new InvoicePDF('pdf.invoice');
$pdf_file->create($data, $this->filename, 'save', $path.$this->dir);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$this->dir.$this->filename);
$file = $pdfMerger->myMerge('string', $this->filename, 'template_invoice_de');
Storage::disk('public')->put($this->dir.$this->filename, $file);
if(!$this->model->shopping_collect_order){
$pdf_file = new InvoicePDF('pdf.delivery');
$pdf_file->create($data, $this->delivery_filename, 'save', $path.$this->delivery_dir);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$this->delivery_dir.$this->delivery_filename);
$file = $pdfMerger->myMerge('string', $this->delivery_filename, 'template_invoice_de');
Storage::disk('public')->put($this->delivery_dir.$this->delivery_filename, $file);
}
}
public function userSalesVolume()
{
}
public function createAndSalesVolume($request = [])
{
$this->user_sales_volume = SalesPointsVolume::addSalesPointsVolumeUser($this->model);
$user_invoice = $this->create($request);
$this->user_sales_volume->user_invoice_id = $user_invoice->id;
$this->user_sales_volume->save();
}
}

View file

@ -0,0 +1,202 @@
<?php
namespace App\Repositories;
use App\Models\CountryPrice;
use App\Models\Product;
use App\Models\ProductAttribute;
use App\Models\ProductCategory;
use App\Models\ProductImage;
use App\Models\ProductIngredient;
class ProductRepository extends BaseRepository {
public function __construct(Product $model)
{
$this->model = $model;
}
/**
* refresh.
*/
public function update($data)
{
$data['active'] = isset($data['active']) ? 1 : 0;
$data['shipping_addon'] = isset($data['shipping_addon']) ? 1 : 0;
$data['no_commission'] = isset($data['no_commission']) ? 1 : 0;
$data['no_free_shipping'] = isset($data['no_free_shipping']) ? 1 : 0;
$data['buying_restriction'] = isset($data['buying_restriction']) ? 1 : 0;
$data['sponsor_buying_points'] = isset($data['sponsor_buying_points']) ? 1 : 0;
$data['show_on'] = isset($data['show_on']) ? $data['show_on'] : null;
if($data['id'] === "new"){
$this->model = Product::create($data);
}
else{
$this->model = $this->getById($data['id']);
$this->model->slug = null;
$this->model->fill($data);
$this->model->save();
}
$this->updateCategories(isset($data['categories']) ? $data['categories'] : array());
$this->updateAttributes(isset($data['attributes']) ? $data['attributes'] : array());
$this->updateIngredients(isset($data['product_ingredients']) ? $data['product_ingredients'] : array());
$this->updateCountryPrices($data);
return $this->model;
}
public function updateIngredients($data = array())
{
$ProductIngredient = $this->model->p_ingredients()->pluck('ingredient_id')->toArray();
//set attr
if(is_array($data)){
foreach ($data as $id) {
//not use
if(!in_array($id, $ProductIngredient)){
ProductIngredient::create([
'product_id' => $this->model->id,
'ingredient_id' => $id,
]);
}
}
}
return true;
}
public function updateCategories($data = array())
{
foreach ($this->model->categories as $category) {
if(($pos = array_search($category->category_id, $data)) !== FALSE){
unset($data[$pos]);
}else{
$category->delete();
}
}
//set attr
if(is_array($data)){
foreach ($data as $id) {
ProductCategory::create([
'product_id' => $this->model->id,
'category_id' => $id,
]);
}
}
return true;
}
public function updateAttributes($data = array())
{
foreach ($this->model->attributes as $attribute) {
if(($pos = array_search($attribute->attribute_id, $data)) !== FALSE){
unset($data[$pos]);
}else{
$attribute->delete();
}
}
//set attr
if(is_array($data)){
foreach ($data as $id) {
ProductAttribute::create([
'product_id' => $this->model->id,
'attribute_id' => $id,
]);
}
}
return true;
}
public function updateCountryPrices($data)
{
if(!isset($data['country_prices']) || !is_array($data['country_prices'])){
return false;
}
foreach ($data['country_prices'] as $k => $country_id) {
$cp = CountryPrice::updateOrCreate([
'country_id' => $country_id,
'product_id' => $this->model->id,
],
[
'c_price' => isset($data['c_price'][$country_id]) ? reFormatNumber($data['c_price'][$country_id]) : null,
'c_tax' => isset($data['c_tax'][$country_id]) ? reFormatNumber($data['c_tax'][$country_id]) : null,
'c_price_old' => isset($data['c_price_old'][$country_id]) ? reFormatNumber($data['c_price_old'][$country_id]) : null,
'c_currency' => isset($data['c_currency'][$country_id]) ? reFormatNumber($data['c_currency'][$country_id]) : null,
]);
}
return true;
}
public function copy($model)
{
$this->model = $model->replicate();
$this->model->name = "Kopie: ".$this->model->name;
$this->model->wp_number = null;
$this->model->save();
//categories
foreach ($model->categories as $category){
ProductCategory::create([
'product_id' => $this->model->id,
'category_id' => $category->category_id,
]);
}
//attributes
foreach ($model->attributes as $attribute){
ProductAttribute::create([
'product_id' => $this->model->id,
'attribute_id' => $attribute->attribute_id,
]);
}
//images
foreach ($model->images as $image){
$name = \App\Services\Slim::sanitizeFileName($image->original_name);
$name = uniqid() . '_' . $name;
//copy
$data = \Storage::disk('public')->copy(
'images/product/'.$image->product_id.'/'.$image->filename,
'images/product/'.$this->model->id.'/'.$name
);
ProductImage::create([
'product_id' => $this->model->id,
'filename' => $name,
'original_name' => $image->original_name,
'ext' => $image->ext,
'mine' => $image->mine,
'size' => $image->size
]);
}
return $this->model;
}
public function delete()
{
}
}

View file

@ -0,0 +1,144 @@
<?php
namespace App\Repositories;
use App\Models\ShoppingOrder;
use App\Services\ShopApiOrderCart;
use App\Services\UserService;
use App\Services\Util;
use App\Models\UserHistory;
use App\Models\ShippingCountry;
use App\Models\ShoppingInstance;
use Auth;
use Yard;
use App\User;
class ShopApiRepository extends BaseRepository {
private $shopApiOrderCart;
public function __construct()
{
//$this->model = $model;
}
public function order($data)
{
$this->shopApiOrderCart = new ShopApiOrderCart();
$this->performOrderActionList($data, 0);
return $this->shopApiOrderCart;
}
public function remove($data){
$this->performActionList($data, 5);
return true;
}
public function reset($data){
$this->performActionList($data, 0);
return true;
}
public function checkout($data)
{
$user = User::find(Auth::user()->id);
$shopApiOrderCart = $this->performCheckout($data);
$time = time();
$date = date('d.m.Y H:i:s', $time);
Yard::instance('shopping')->destroy();
$cartItem = Yard::instance('shopping')->add($shopApiOrderCart->id, 'Sammelbestellung Extern '.$date, 1, $shopApiOrderCart->price_total, false, false, ['image' => "", 'slug' => $time, 'weight' => 0]);
Yard::setTax($cartItem->rowId, 0);
do {
$identifier = Util::getToken();
} while( ShoppingInstance::where('identifier', $identifier)->count() );
$shipping_country = ShippingCountry::whereCountryId($user->account->country_id)->first();
UserService::checkUserTaxShippingCountry($user, $shipping_country->id);
$data = [];
$data['is_from'] = 'collection';
$data['shop_price'] = $shopApiOrderCart->price_total;
$data['shop_price_net'] = $shopApiOrderCart->price_total_net;
$data['shop_price_tax'] = $shopApiOrderCart->tax_total;
$data['user_tax_free'] = false;
$data['shopping_collect_order_id'] = $shopApiOrderCart->id;
$data['is_for'] = 'co'; //colection
$data['user_price_infos'] = UserService::getYardInfo();
ShoppingInstance::create([
'identifier' => $identifier,
'user_shop_id' => 1, //is first faker shop for nuy intern
'auth_user_id' => $user->id,
'payment' => 2, //Berater Shop
'subdomain' => url('/'),
'country_id' => Yard::instance('shopping')->getShippingCountryId(),
'language' => \App::getLocale(),
'shopping_data' => $data,
'back' => route('user_shop_api_orders'),
]);
Yard::instance('shopping')->store($identifier);
$path = route('checkout.checkout_card', ['identifier'=>$identifier]);
UserHistory::create(['user_id' => $user->id, 'action'=>'payment_collection', 'status'=>1, 'referenz'=>$shopApiOrderCart->id, 'identifier'=>$identifier]);
//$path = str_replace('http', 'https', $path);
return redirect()->secure($path);
}
private function performCheckout($data){
$this->shopApiOrderCart = new ShopApiOrderCart();
$this->performOrderCheckoutList($data, 1);
return $this->shopApiOrderCart;
}
private function performActionList($data, $status){
if(isset($data['api_action_list'])){
foreach($data['api_action_list'] as $orderItemId=>$v){
$ShoppingOrder = ShoppingOrder::findOrFail($orderItemId);
$ShoppingOrder->api_status = $status;
$ShoppingOrder->save();
}
}
}
private function performOrderActionList($data, $status){
if(isset($data['api_action_list'])){
foreach($data['api_action_list'] as $orderItemId=>$v){
$ShoppingOrder = ShoppingOrder::findOrFail($orderItemId);
$this->shopApiOrderCart->add($ShoppingOrder);
$ShoppingOrder->api_status = $status; //<- no status change is the show list
$ShoppingOrder->save();
}
$this->shopApiOrderCart->calculate();
return $this->shopApiOrderCart;
}
}
private function performOrderCheckoutList($data, $status){
if(isset($data['api_action_list'])){
foreach($data['api_action_list'] as $k=>$orderItemId){
$ShoppingOrder = ShoppingOrder::findOrFail($orderItemId);
$this->shopApiOrderCart->add($ShoppingOrder);
$ShoppingOrder->api_status = $status;
$ShoppingOrder->save();
}
$this->shopApiOrderCart->calculate();
$this->shopApiOrderCart->store();
return $this->shopApiOrderCart;
}
}
}

View file

@ -0,0 +1,206 @@
<?php
namespace App\Repositories;
use Util;
use Request;
use App\User;
use Validator;
use App\Services\UserUtil;
use App\Models\UserAccount;
use App\Models\PaymentMethod;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Api\KasController;
class UserRepository extends BaseRepository
{
public function __construct(User $model)
{
$this->model = $model;
}
public function update($data)
{
if ($data['user_id'] === "new" || $data['user_id'] == 0) {
$this->model = User::create([
'email' => $data['email'],
'password' => env('APP_KEY'),
]);
$this->model->payment_methods = PaymentMethod::getDefaultAsArray();
$this->model->save();
} else {
$this->model = $this->getById($data['user_id']);
}
if (!$this->model->account_id) {
$account = new UserAccount();
} else {
$account = $this->model->account;
}
$data['same_as_billing'] = !isset($data['same_as_billing']) ? 0 : 1;
$account->fill($data)->save();
if (!$this->model->account_id) {
$this->model->account_id = $account->id;
$this->model->save();
}
return true;
}
public function create($data)
{
$this->model = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$account = UserAccount::create([
'm_salutation' => $data['salutation'],
'm_first_name' => $data['first_name'],
'm_last_name' => $data['last_name'],
'salutation' => $data['salutation'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
]);
$this->model->account_id = $account->id;
$this->model->payment_methods = PaymentMethod::getDefaultAsArray();
$this->model->save();
return $this->model;
}
public function deleteUser(User $user, $complete = false)
{
$active_sponsor = UserUtil::findNextActiveSponsor($user->id);
if ($active_sponsor) {
UserUtil::setNewSponsorToChilds($user->id, $active_sponsor->id);
UserUtil::setShoppingUserToNewMember($user->id, $active_sponsor->id);
}
UserUtil::deleteUser($user, $complete);
}
public function reverse_charge_validate($data, $user, $route)
{
if (isset($data['action']) && $data['action'] == 'reverse_charge_validate') {
$rules = array(
'tax_identification_number' => 'required',
);
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
$data = [
'user' => $user,
];
return redirect($route . '#user-vat-validation')->withErrors($validator)->withInput($data);
}
$ret = $this->reverse_charge_activate($data, $user);
if ($ret === 'error') {
$validator = Validator::make($data, []);
$validator->errors()->add('tax_identification_number_validated', __('msg.VATID_could_not_be_validated'));
$data['reverse_charge'] = 0;
$data = [
'user' => $user,
];
return redirect($route . '#user-vat-validation')->withErrors($validator)->withInput($data);
}
if ($ret === 'valid') {
\Session()->flash('alert-success', __('msg.VATID_successfully_entered'));
return redirect($route . '#user-vat-validation')->withInput($data);
return redirect($route . '#user-vat-validation')->withInput($data);
}
}
}
public function reverse_charge_delete($data, $user, $route)
{
if (isset($data['action']) && $data['action'] == 'reverse_charge_delete') {
$user->account->tax_identification_number = '';
$user->account->reverse_charge = 0;
$user->account->reverse_charge_code = null;
$user->account->reverse_charge_valid = null;
$user->account->save();
$data['tax_identification_number'] = '';
\Session()->flash('alert-success', __('msg.reverse_charge_procedure_and_VATID_deleted'));
return redirect($route . '#user-vat-validation')->withInput($data);
}
}
public function reverse_charge_activate($data, $user)
{
/* 'AT' => 'AT-Oesterreich',
'BE' => 'BE-Belgien',
'BG' => 'BG-Bulgarien',
'CY' => 'CY-Zypern',
'CZ' => 'CZ-Tschechische Republik',
'DE' => 'DE-Deutschland',
'DK' => 'DK-Dänemark',
'EE' => 'EE-Estland',
'EL' => 'EL-Griechenland',
'ES' => 'ES-Spanien',
'FI' => 'FI-Finnland',
'FR' => 'FR-Frankreich ',
'HR' => 'HR-Kroatien ',
'HU' => 'HU-Ungarn',
'IE' => 'IE-Irland',
'IT' => 'IT-Italien',
'LT' => 'LT-Litauen',
'LU' => 'LU-Luxemburg',
'LV' => 'LV-Lettland',
'MT' => 'MT-Malta',
'NL' => 'NL-Niederlande',
'PL' => 'PL-Polen',
'PT' => 'PT-Portugal',
'RO' => 'RO-Rumänien',
'SE' => 'SE-Schweden',
'SI' => 'SI-Slowenien',
'SK' => 'SK-Slowakei',
'XI' => 'XI-Nordirland', */
$countryCode = 'DE';
if ($user->account->country_id) {
$countryCode = $user->account->country->code;
}
$vatid = str_replace(array(' ', '.', '-', ',', ', '), '', trim($data['tax_identification_number']));
$cc = substr($vatid, 0, 2);
$vatNo = substr($vatid, 2);
$options = [
'cache_wsdl' => WSDL_CACHE_NONE,
'trace' => 1,
'stream_context' => stream_context_create(
[
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]
)
];
$client = new \SoapClient("https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl", $options);
$result = $client->checkVat(['countryCode' => $countryCode, 'vatNumber' => $vatNo]);
if ($result->valid == true) {
$user->account->tax_identification_number = $data['tax_identification_number'];
$user->account->reverse_charge = 1;
$user->account->reverse_charge_code = $countryCode;
$user->account->reverse_charge_valid = now();
$user->account->save();
return 'valid';
} else {
return 'error';
}
}
}