20-02-2026

This commit is contained in:
Kevin Adametz 2026-02-20 17:55:06 +01:00
parent a8b395e20d
commit a00c42e770
252 changed files with 28785 additions and 8907 deletions

View file

@ -2,20 +2,16 @@
namespace App\Repositories;
use Carbon;
use App\Models\UserAbo;
use App\Services\AboHelper;
class AboRepository extends BaseRepository
{
public function __construct()
{
//$this->model = $model;
// $this->model = $model;
}
public function setModel(UserAbo $model)
{
$this->model = $model;
@ -28,14 +24,17 @@ class AboRepository extends BaseRepository
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->next_date = AboHelper::setNextDate(now(), $data['abo_interval']);
$this->model->save();
\Session()->flash('alert-success', 'Einstellungen gespeichert');
return true;
}
return false;
}
}
return false;
}
@ -50,52 +49,57 @@ class AboRepository extends BaseRepository
$this->model->active = false;
$this->model->cancel_date = now();
$this->model->save();
return;
}
$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; //inactive
// 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; // inactive
$this->model->active = false;
$this->model->save();
}
}
if (!$this->model->active && $active) {
if ($this->model->status = 6) { //inactive
$this->model->status = 2; //okay
if (! $this->model->active && $active) {
if ($this->model->status = 6) { // inactive
$this->model->status = 2; // okay
$this->model->active = true;
$this->model->save();
}
}
$this->model->active = $active;
return;
}
private function validate($data)
{
if ($data['view'] !== 'admin') {
if ($data['view'] !== 'admin' && $data['view'] !== 'portal') {
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
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;
}
@ -104,8 +108,9 @@ class AboRepository extends BaseRepository
// da setNextDate das nächste Ausführungsdatum sonst auf den nächsten Monat setzt und dieser Monat übersprungen wird.
$executedThisMonth = $this->model->last_date && \Carbon\Carbon::parse($this->model->last_date)->isCurrentMonth();
if (!$executedThisMonth && $data['abo_interval'] <= now()->day) {
if (! $executedThisMonth && $data['abo_interval'] <= now()->day) {
\Session()->flash('alert-error', __('abo.error_abo_interval_in_the_past'));
return false;
}

View file

@ -2,24 +2,22 @@
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\ShoppingCollectOrder;
use App\Models\ShoppingOrder;
use Illuminate\Session\SessionManager;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Services\Util;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Collection;
use Yard;
class CheckoutRepository extends BaseRepository
{
private $session;
private $instance;
private $instance;
public function __construct(SessionManager $session)
{
@ -33,10 +31,10 @@ class CheckoutRepository extends BaseRepository
$user_shop = Util::getUserShop();
if ($shopping_user->is_from === 'homeparty') {
//get data
// get data
$homeparty = Homeparty::find($shopping_user->homeparty_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
// 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,
@ -44,7 +42,7 @@ class CheckoutRepository extends BaseRepository
'language' => \App::getLocale(),
'user_shop_id' => $user_shop->id,
'payment_for' => $shopping_user->getOrderPaymentFor(),
'homeparty_id' => $shopping_user->homeparty_id,
'homeparty_id' => $shopping_user->homeparty_id,
'total' => $total,
'subtotal' => $homeparty->order['ek_price_net'],
'shipping' => $homeparty->order['shipping_price'],
@ -58,10 +56,10 @@ class CheckoutRepository extends BaseRepository
'mode' => Util::getUserShoppingMode(),
];
} elseif ($shopping_user->is_from === 'collection') {
//get data
// get data
$ShoppingCollectOrder = ShoppingCollectOrder::find($shopping_user->shopping_collect_order_id);
//set Data!
$total = Yard::instance($this->instance)->total(2, '.', ''); //ek_price
// 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,
@ -75,7 +73,7 @@ class CheckoutRepository extends BaseRepository
'shipping_net' => 0,
'subtotal_ws' => $ShoppingCollectOrder->price_total_net,
'tax' => $ShoppingCollectOrder->tax_total,
'tax_split' => $ShoppingCollectOrder->tax_split,
'tax_split' => $ShoppingCollectOrder->tax_split,
'total_shipping' => Yard::instance($this->instance)->totalWithShipping(2, '.', ''),
'points' => round($ShoppingCollectOrder->points, 2),
'weight' => 0,
@ -114,7 +112,7 @@ class CheckoutRepository extends BaseRepository
$shopping_order->save();
}
}
if (!$shopping_order) {
if (! $shopping_order) {
$shopping_order = ShoppingOrder::create($data);
if ($shopping_user->is_from === 'collection' && $ShoppingCollectOrder) {
$ShoppingCollectOrder->shopping_order_id = $shopping_order->id;
@ -131,7 +129,7 @@ class CheckoutRepository extends BaseRepository
$tax = $item->price - $price_net;
$data = [
'shopping_order_id' => $shopping_order->id,
'row_id' => $item->rowId,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
@ -153,20 +151,22 @@ class CheckoutRepository extends BaseRepository
$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()) {
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,
'row_id' => $item->rowId,
'product_id' => $item->id,
'comp' => $item->options->comp,
'qty' => $item->qty,
@ -177,7 +177,7 @@ class CheckoutRepository extends BaseRepository
'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
'slug' => $item->options->slug,
];
if ($shopping_user->is_from === 'homeparty') {
@ -196,16 +196,18 @@ class CheckoutRepository extends BaseRepository
if ($shopping_user->is_from === 'homeparty') {
$shopping_order->makeHomepartyTaxSplit();
} elseif ($shopping_user->is_from === 'collection') {
//is set on create / filll.
// 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['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')) {
@ -216,7 +218,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->save();
}
}
if (!$shopping_user) {
if (! $shopping_user) {
$shopping_user = ShoppingUser::create($data);
}
$this->putSessionPayments('shopping_user_id', $shopping_user->id);
@ -240,6 +242,7 @@ class CheckoutRepository extends BaseRepository
} else {
$payment_methods['active'] = \App\Models\PaymentMethod::where('active', true)->get()->pluck('id', 'short')->toArray();
}
return $payment_methods;
}
@ -259,44 +262,46 @@ class CheckoutRepository extends BaseRepository
public function makeCustomerShoppingUser($shopping_data, $is_for, $is_from)
{
// $shopping_user = ShoppingUser::findOrFail($shopping_data['shopping_user_id']);
$shopping_user = new ShoppingUser();
$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->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 = new ShoppingUser;
$shopping_user->homeparty_id = $homeparty_id;
$shopping_user->language = \App::getLocale();
//eingeloggter Kunde
// eingeloggter Kunde
if (\Auth::guard('customers')->check()) {
$shopping_user = $this->shoppingUserByAuthCustomer(\Auth::guard('customers')->user());
}
//eingeloggter User Berater
// 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!
// clone shopping user!
if ($user->shopping_user_id) {
$find_shopping_user = ShoppingUser::find($user->shopping_user_id);
if ($find_shopping_user) {
@ -305,7 +310,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->shipping_country_id = null;
}
} else {
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
}
@ -315,7 +320,7 @@ class CheckoutRepository extends BaseRepository
public function shoppingUserByAuthUser(\App\User $user, $is_from, $is_for)
{
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->language = \App::getLocale();
$shopping_user->billing_salutation = $user->account->salutation;
@ -326,16 +331,16 @@ class CheckoutRepository extends BaseRepository
$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_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->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
//Lieferadresse
// 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;
@ -345,11 +350,10 @@ class CheckoutRepository extends BaseRepository
$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_country_id = $user->account->shipping_country_id;
$shopping_user->shipping_phone = $user->account->shipping_phone;
$shopping_user->shipping_postnumber = $user->account->shipping_postnumber;
return $shopping_user;
}
@ -357,7 +361,7 @@ class CheckoutRepository extends BaseRepository
{
$user = Util::getAuthUser();
$shopping_user = new ShoppingUser();
$shopping_user = new ShoppingUser;
$shopping_user->auth_user_id = $user->id;
$shopping_user->mode = 'prev';
$shopping_user->language = \App::getLocale();
@ -375,6 +379,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $user->email;
$shopping_user->faker_mail = false;
$shopping_user->shipping_email = $user->email;
$shopping_user->language = $user->account->getLocale();
$shopping_user->accepted_data_checkbox = 1;
$shopping_user->is_for = $is_for;
@ -382,7 +387,7 @@ class CheckoutRepository extends BaseRepository
$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
// 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']);
@ -399,7 +404,7 @@ class CheckoutRepository extends BaseRepository
$shopping_user->billing_email = $s_user->billing_email;
;*/
$shopping_user->faker_mail = $s_user->faker_mail;
if (!$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'];
@ -449,13 +454,14 @@ class CheckoutRepository extends BaseRepository
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
if (session('user_shop_payment') === 1) { // ShoppingInstance payment 1 = webshop
Yard::instance('webshop')->destroy();
} else {
Yard::instance('shopping')->destroy();
@ -469,6 +475,7 @@ class CheckoutRepository extends BaseRepository
if (is_null($this->session->get($this->instance))) {
return new Collection([]);
}
return $this->session->get($this->instance);
}
}

View file

@ -7,37 +7,77 @@ use App\Models\File;
use App\User;
use Storage;
class ContractPDFRepository extends BaseRepository {
class ContractPDFRepository extends BaseRepository
{
protected $disk;
protected $dir;
protected $user_id;
protected $identifier;
public function __construct(User $model){
protected $locale;
protected $contract_date;
public function __construct(User $model)
{
$this->model = $model;
// Benutzersprache aus Account ermitteln (mit Fallback auf de)
$this->locale = $model->account && $model->account->language
? $model->account->language
: 'de';
}
public function _set($name, $value){
public function _set($name, $value)
{
$this->{$name} = $value;
}
private function convert($str){
$search = array('Ő', 'ő', 'Ű', 'ű');
$replace = array('Ö', 'ö', 'Ü', 'ü');
private function convert($str)
{
$search = ['Ő', 'ő', 'Ű', 'ű'];
$replace = ['Ö', 'ö', 'Ü', 'ü'];
$str = str_replace($search, $replace, $str);
return iconv('UTF-8', 'windows-1252//IGNORE', $str);
return iconv('UTF-8', 'windows-1252//IGNORE', $str);
}
public function createContractPDF() {
public function createContractPDF()
{
$pdf = new ContractPDF();
if (! Storage::disk($this->disk)->exists($this->dir)) {
Storage::disk($this->disk)->makeDirectory($this->dir); // creates directory
}
$pdf->AddPage('P', array(210, 297));
// Lösche alle alten Vertrags-Einträge für diesen User
File::where('user_id', $this->model->id)
->where('identifier', $this->identifier)
->delete();
// 1. IMMER deutsches Original erstellen
$this->createContractPDFForLocale('de');
// 2. Wenn Benutzersprache != DE, lokalisierte Version erstellen
if ($this->locale && $this->locale !== 'de') {
$this->createContractPDFForLocale($this->locale);
}
return true;
}
/**
* Erstellt einen Beratervertrag in der angegebenen Sprache
*/
private function createContractPDFForLocale(string $locale)
{
$pdf = new ContractPDF;
$pdf->setLocale($locale);
$pdf->AddPage('P', [210, 297]);
$pdf->SetFont('Helvetica', '', 11);
$pdf->SetDrawColor(160, 160, 160);
@ -48,22 +88,21 @@ class ContractPDFRepository extends BaseRepository {
$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"));
$contractDate = $this->contract_date ?? now();
$pdf->Write(0, $contractDate->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)." " : "";
$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)." " : "";
$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;
@ -80,14 +119,14 @@ class ContractPDFRepository extends BaseRepository {
$y += $nl;
$pdf->SetXY($x1, $y);
$pdf->Write(0, $this->convert($this->model->account->zipcode)." ".$this->convert($this->model->account->city));
$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)." " : "";
$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){
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));
@ -96,49 +135,44 @@ class ContractPDFRepository extends BaseRepository {
$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));
$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";
$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->AddPage('P', [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->Write(0, $website.' (ID: '.$this->convert($this->model->account->m_account).')');
$pdf->AddPage('P', array(210, 297));
$pdf->SetXY($x1, 80);
$pdf->Write(0, $this->convert($this->model->account->m_first_name));
$pdf->SetXY($x2, 80);
$pdf->Write(0, $this->convert($this->model->account->m_last_name));
$pdf->AddPage('P', [210, 297]);
// Dateiname mit übersetztem Vertragsnamen
$contractName = __('pdf.contract_filename', [], $locale);
$filename = "MIVITA_{$contractName}.pdf";
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);
$size = Storage::disk($this->disk)->size($this->dir.$filename);
$mine = Storage::disk($this->disk)->mimeType($this->dir.$filename);
// Erstelle Datenbank-Eintrag für diesen Vertrag
File::create([
'user_id' => $this->model->id,
'identifier' => $this->identifier,
'filename' => $filename,
'dir' => $this->dir,
'original_name' => $filename,
'ext' => "pdf",
'ext' => 'pdf',
'mine' => $mine,
'size' => $size
'size' => $size,
]);
return true;
}
}
}

View file

@ -2,21 +2,22 @@
namespace App\Repositories;
use PDF;
use Storage;
use App\User;
use App\Services\Credit;
use App\Models\UserCredit;
use Response;
use App\Libraries\CreditDetailsPDF;
use App\Libraries\MyPDFMerger;
use App\Models\UserCredit;
use App\Models\UserCreditItem;
use App\Models\UserSalesVolume;
use App\Libraries\CreditDetailsPDF;
use App\Services\BusinessPlan\TreeCalcBot;
use App\Services\Credit;
use App\User;
use PDF;
use Response;
use Storage;
class CreditRepository extends BaseRepository {
class CreditRepository extends BaseRepository
{
private $user_credit;
public function __construct(User $model)
{
$this->model = $model;
@ -24,16 +25,16 @@ class CreditRepository extends BaseRepository {
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;
// 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();
$this->user_credit = new UserCredit;
$user_credit_items = $this->makeUserCredit();
if(!count($user_credit_items)){
return false;
if (! count($user_credit_items)) {
return false;
}
$data = [
'user' => $this->model,
@ -42,24 +43,33 @@ class CreditRepository extends BaseRepository {
'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
if (! Storage::disk('public')->exists($dir)) {
Storage::disk('public')->makeDirectory($dir); // creates directory
}
$path = Storage::disk('public')->path('');
// Benutzersprache ermitteln
$userLocale = $this->model->account ? $this->model->account->getLocale() : 'de';
$originalLocale = \App::getLocale();
// Deutsches Original-Dateiname (wird in DB gespeichert)
$filename = Credit::makeCreditFilename($credit_number);
$pdf->save($path.$dir.$filename);
// 1. IMMER deutsches Original erstellen (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createCreditPDF($data, $path, $dir, $filename, 'de', false);
$pdfMerger = new MyPDFMerger();
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, 'template_invoice_de');
Storage::disk('public')->put($dir.$filename, $file);
// 2. Wenn Benutzersprache != DE, Kopie in Benutzersprache erstellen
if ($userLocale && $userLocale !== 'de') {
\App::setLocale($userLocale);
$localizedFilename = Credit::makeCreditFilenameLocale($credit_number, $userLocale);
$this->createCreditPDF($data, $path, $dir, $localizedFilename, $userLocale, true);
}
// Locale zurücksetzen
\App::setLocale($originalLocale);
$this->user_credit->user_id = $this->model->id;
$this->user_credit->year = \Carbon::parse($credit_date)->format('Y');
@ -72,35 +82,76 @@ class CreditRepository extends BaseRepository {
$this->user_credit->full_number = $credit_number;
$this->user_credit->save();
if($credit_send_mail){
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
/**
* Erstellt eine Gutschrift-PDF-Datei.
*
* @param string $locale Sprachcode für das Template (de, en, es, fr)
* @param bool $is_copy Ob es sich um eine Kopie handelt (nicht das Original)
*/
private function createCreditPDF(array $data, string $path, string $dir, string $filename, string $locale = 'de', bool $is_copy = false)
{
// Kopie-Flag an Template übergeben
$data['is_copy'] = $is_copy;
$pdf = PDF::loadView('pdf.credit', $data);
$pdf->setPaper('A4', 'portrait');
$pdf->save($path.$dir.$filename);
// Template basierend auf Locale
$template = $this->getTemplateForLocale($locale);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$dir.$filename);
$file = $pdfMerger->myMerge('string', $filename, $template);
Storage::disk('public')->put($dir.$filename, $file);
}
/**
* Gibt das PDF-Template für die angegebene Locale zurück.
* Verfügbare Templates werden aus config/localization.php geladen.
*/
private function getTemplateForLocale(string $locale): string
{
$availableTemplates = config('localization.availableTemplates', ['de']);
if (in_array($locale, $availableTemplates)) {
return 'template_invoice_'.$locale;
}
return 'template_invoice_de';
}
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){
// 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(){
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){
foreach ($UserCreditItems as $userCreditItem) {
$user_credit_items[] = $userCreditItem;
$infos[] = ['id' => $userCreditItem->id, 'credit' => $userCreditItem->credit];
$this->user_credit->net += $userCreditItem->credit;
@ -108,37 +159,37 @@ class CreditRepository extends BaseRepository {
/* taxable_sales //user tax
1 //umsatzsteuerpflichtig / DE
2 // nicht umsatzsteuerpflichtig /DE
3 // nicht umsatzsteuerpflichtig / Ausland
3 // nicht umsatzsteuerpflichtig / Ausland
*/
if($this->model->account){
if ($this->model->account) {
$this->user_credit->taxable = $this->model->account->taxable_sales;
if($this->model->account->country_id !== 1){
if ($this->model->account->country_id !== 1) {
$this->user_credit->taxable = 3;
}
if($this->user_credit->taxable === 1){
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{
} 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;
return $user_credit_items;
}
/*
Erstellt einen detalierten Report zur Gutschrift
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();
public function create_report(UserCredit $user_credit, $do = 'html')
{
// collect all data
$collection = new \stdClass;
$collection->calc_bot = [];
$collection->commission_shop = [];
$collection->commission_payline = [];
@ -147,48 +198,45 @@ class CreditRepository extends BaseRepository {
$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){
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])){
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])){
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
Auswertung der Shopbestellungen vom User für einen Monat / Jahr
Auslistung der Positonen / Gesamter Umsatz / Marge / Provision
*/
if($user_credit_item->status === 1){
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();
->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();
->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 = 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;
@ -200,165 +248,155 @@ class CreditRepository extends BaseRepository {
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();
->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
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){
/*
foreach ($dates as $date => $dateObj) {
/*
UserSalesVolume::status
1 => 'advisor_order', own_order //hinzugefügt aus
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');
$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();
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;
}
/*
$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
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)
$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
->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_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');
$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;
}
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
*/
/*
//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'){
if ($do === 'html') {
return view('admin.payment.credit_detail', $data);
}
if($do === 'pdf'){
if ($do === 'pdf') {
$dir = Credit::getCreditDetailStorageDir($user_credit->date);
if(!Storage::disk('public')->exists( $dir )){
Storage::disk('public')->makeDirectory($dir); //creates directory
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');
// 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 = 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);
// $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.'"');
->header('Content-Type', $mime)
->header('Content-disposition', 'inline; filename="'.$filename.'"');
//return $dir.$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');
@ -366,4 +404,4 @@ class CreditRepository extends BaseRepository {
*/
}
}
}
}

View file

@ -2,140 +2,153 @@
namespace App\Repositories\DC;
use Request;
use App\Models\DcTag;
use App\Models\DcCategory;
use App\Models\DcTag;
use App\Repositories\BaseRepository;
use Request;
class TagRepository extends BaseRepository {
public function __construct()
{
}
class TagRepository extends BaseRepository
{
public function __construct() {}
public function storeItem($obj, $data)
{
if($obj === 'category' && isset($data['dc_category_name'])){
if ($obj === 'category' && isset($data['dc_category_name'])) {
$category = new DcCategory;
$category->name = $data['dc_category_name'];
$category->pos = 0 ;
$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'])){
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'])){
if ($obj === 'structure' && isset($data['nestable'])) {
$bool = $this->updateStructure($data);
if(Request::ajax()){
if (Request::ajax()) {
return response()->json([
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true])
]);
'success' => $bool,
'redirect' => route('admin_downloadcenter_tags', ['flash' => true]),
]);
}
}
if($obj === 'update_ajax' && isset($data['action'])){
if ($obj === 'update_ajax' && isset($data['action'])) {
$active = $this->updateAjax($data);
if(Request::ajax()){
if (Request::ajax()) {
return response()->json([
'success' => $data['action'],
'active' => $active,
]);
'success' => $data['action'],
'active' => $active,
]);
}
}
return true;
}
}
protected function updateAjax($data){
protected function updateAjax($data)
{
if($data['action'] == 'update-tag-active' && isset($data['id'])){
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'])){
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'])){
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->pos = null;
$value->save();
}
$this->saveStructureLevel($data['nestable']);
return true;
}
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false){
protected function saveStructureLevel($nestable, $deep = 0, $category_id = false)
{
foreach ($nestable as $key => $value) {
if($value['id'] == 0){
if ($value['id'] == 0) {
continue;
}
if($deep == 0){
$cat = DcCategory::findOrFail($value['id']);
$cat->pos = $key;
$cat->save();
if ($deep == 0) {
$cat = DcCategory::find($value['id']);
if (! $cat) {
// Kategorie existiert nicht mehr, überspringen
continue;
}
$cat->pos = $key;
$cat->save();
}
if($deep == 1){
$tag = DcTag::findOrFail($value['id']);
if ($deep == 1) {
$tag = DcTag::find($value['id']);
if (! $tag) {
// Tag existiert nicht mehr, überspringen
continue;
}
$tag->category_id = $category_id;
$tag->pos = $key;
$tag->save();
}
if(!empty($value['children'])){
$this->saveStructureLevel($value['children'], $deep+1, $value['id']);
if (! empty($value['children'])) {
$this->saveStructureLevel($value['children'], $deep + 1, $value['id']);
}
}
}
public function deleteItem($obj, $id){
if($obj == 'category'){
public function deleteItem($obj, $id)
{
if ($obj == 'category') {
$this->deleteCategory($id);
}
if($obj == 'tag'){
$this->deleteTag($id);
if ($obj == 'tag') {
$this->deleteTag($id);
}
}
public function deleteCategory($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);
$this->deleteTag($tag->id);
}
$cat->delete();
}
}
public function deleteTag($id){
public function deleteTag($id)
{
$tag = DcTag::findOrFail($id);
$tag->delete();
}
}
}
}

View file

@ -2,31 +2,34 @@
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\ShoppingOrder;
use App\Models\UserInvoice;
use App\Models\UserSalesVolume;
use App\Services\BusinessPlan\SalesPointsVolume;
use App\Services\Invoice;
use App\Services\UserService;
use Storage;
class InvoiceRepository extends BaseRepository {
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;
private $delivery_filename;
public function __construct(ShoppingOrder $model)
{
@ -35,54 +38,60 @@ class InvoiceRepository extends BaseRepository {
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);
// Wrap entire invoice creation in transaction to ensure atomicity
return \DB::transaction(function () use ($request) {
// Get and increment invoice number atomically (includes its own lock)
$number = Invoice::makeNextInvoiceNumber();
$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;
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']) && $request['invoice_send_mail'] ? true : false;
$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 = 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(),
]);
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([
@ -99,16 +108,23 @@ class InvoiceRepository extends BaseRepository {
'disk' => 'public',
])->save();
if($invoice_send_mail){
if ($invoice_send_mail) {
Invoice::sendInvoiceMail($this->model, $user_invoice);
}
return $user_invoice;
}
return $user_invoice;
}
return null;
}
private function makePDF(){
/**
* Erstellt die PDFs für Rechnung und Lieferschein.
* Das deutsche Original wird immer erstellt (Finanzamt-Anforderung).
* Bei anderer Kundensprache wird zusätzlich eine Kopie in der Kundensprache erstellt.
*/
private function makePDF()
{
$data = [
'shopping_order' => $this->model,
'invoice_date' => $this->invoice_date,
@ -116,43 +132,89 @@ class InvoiceRepository extends BaseRepository {
'user_sales_volume' => $this->user_sales_volume,
];
if($this->model->auth_user_id){
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
}
if (! Storage::disk('public')->exists($this->dir)) {
Storage::disk('public')->makeDirectory($this->dir);
}
if (! Storage::disk('public')->exists($this->delivery_dir)) {
Storage::disk('public')->makeDirectory($this->delivery_dir);
}
// Kundensprache ermitteln
$customerLocale = $this->model->shopping_user ? $this->model->shopping_user->getLocale() : 'de';
$originalLocale = \App::getLocale();
// 1. IMMER deutsches Original erstellen (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createPDFFiles($data, 'de');
// 2. Wenn Kundensprache != DE, Kopie in Kundensprache erstellen
if ($customerLocale && $customerLocale !== 'de') {
\App::setLocale($customerLocale);
$this->createPDFFiles($data, $customerLocale);
}
// Locale zurücksetzen
\App::setLocale($originalLocale);
}
/**
* Erstellt die PDF-Dateien für eine bestimmte Sprache.
*/
private function createPDFFiles(array $data, string $locale)
{
$path = Storage::disk('public')->path('');
//invoice
// Dateinamen für diese Sprache
$invoiceFilename = Invoice::makeInvoiceFilenameLocale($this->invoice_number, $locale);
$deliveryFilename = Invoice::makeDeliveryFilenameLocale($this->invoice_number, $locale);
// Kopie-Flag: true wenn nicht Deutsch (das Original)
$data['is_copy'] = ($locale !== 'de');
// Template basierend auf Locale
$template = $this->getTemplateForLocale($locale);
// Rechnung erstellen
$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->create($data, $invoiceFilename, 'save', $path.$this->dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$this->dir.$invoiceFilename);
$file = $pdfMerger->myMerge('string', $invoiceFilename, $template);
Storage::disk('public')->put($this->dir.$invoiceFilename, $file);
// Lieferschein erstellen (außer bei Sammelbestellung)
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);
$pdf_file->create($data, $deliveryFilename, 'save', $path.$this->delivery_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$this->delivery_dir.$deliveryFilename);
$file = $pdfMerger->myMerge('string', $deliveryFilename, $template);
Storage::disk('public')->put($this->delivery_dir.$deliveryFilename, $file);
}
}
public function userSalesVolume()
/**
* Gibt das PDF-Template für die angegebene Locale zurück.
* Verfügbare Templates werden aus config/localization.php geladen.
*/
private function getTemplateForLocale(string $locale): string
{
$availableTemplates = config('localization.availableTemplates', ['de']);
if (in_array($locale, $availableTemplates)) {
return 'template_invoice_'.$locale;
}
return 'template_invoice_de';
}
public function userSalesVolume() {}
public function createAndSalesVolume($request = [])
{
$this->user_sales_volume = SalesPointsVolume::addSalesPointsVolumeUser($this->model);
@ -160,4 +222,225 @@ class InvoiceRepository extends BaseRepository {
$this->user_sales_volume->user_invoice_id = $user_invoice->id;
$this->user_sales_volume->save();
}
}
/**
* Erstellt eine Stornorechnung mit Punktekorrektur
*
* @param array $request
* @return UserInvoice
*/
public function createCancellation($request = [])
{
return \DB::transaction(function () use ($request) {
$original_invoice = $this->model->user_invoice;
if (! $original_invoice) {
throw new \Exception('Keine Originalrechnung gefunden.');
}
// Nächste Rechnungsnummer für Storno holen
$number = Invoice::makeNextInvoiceNumber();
// Stornodatum
$cancellation_date = isset($request['cancellation_date'])
? $request['cancellation_date']
: now()->format('d.m.Y');
$cancellation_send_mail = isset($request['cancellation_send_mail']) && $request['cancellation_send_mail'] ? true : false;
// Rechnungsnummer erstellen
$cancellation_number = Invoice::createInvoiceNumber($number, $cancellation_date);
$cancellation_dir = Invoice::getInvoiceStorageDir($cancellation_date);
$cancellation_filename = Invoice::makeCancellationFilename($cancellation_number);
$cancellation_delivery_dir = Invoice::getDeliveryStorageDir($cancellation_date);
$cancellation_delivery_filename = Invoice::makeCancellationDeliveryFilename($cancellation_number);
// Stornorechnung PDF erstellen
$this->makeCancellationPDF(
$cancellation_date,
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename,
$original_invoice
);
// Stornorechnung in DB speichern
$cancellation_invoice = UserInvoice::create([
'shopping_order_id' => $this->model->id,
'year' => \Carbon::parse($cancellation_date)->format('Y'),
'month' => \Carbon::parse($cancellation_date)->format('m'),
'date' => $cancellation_date,
'full_number' => $cancellation_number,
'number' => $number,
'filename' => $cancellation_filename,
'dir' => $cancellation_dir,
'delivery_filename' => $cancellation_delivery_filename,
'delivery_dir' => $cancellation_delivery_dir,
'disk' => 'public',
'cancellation' => true,
'status' => $original_invoice->status === 1 ? 11 : 12, // 11 = storniert B., 12 = storniert Shop
]);
// Original-Rechnung als storniert markieren
$original_invoice->cancellation = true;
$original_invoice->cancellation_id = $cancellation_invoice->id;
$original_invoice->cancellation_date = $cancellation_date;
$original_invoice->save();
// Bestellstatus auf "storniert" setzen
$this->model->txaction = 'cancelled';
// Versandstatus auf "storniert" (10) setzen, wenn noch nicht versendet
if (in_array($this->model->shipped, [0, 1])) {
$this->model->shipped = 10;
}
$this->model->save();
\Log::info('Bestellstatus aktualisiert nach Storno', [
'order_id' => $this->model->id,
'txaction' => $this->model->txaction,
'shipped' => $this->model->shipped,
]);
// Punktekorrektur durchführen (nach Erstellung der Stornorechnung)
$this->correctPointsForCancellation($original_invoice, $cancellation_invoice);
// Optional: E-Mail versenden
if ($cancellation_send_mail) {
Invoice::sendInvoiceMail($this->model, $cancellation_invoice);
}
return $cancellation_invoice;
});
}
/**
* Erstellt die Storno-PDFs (Rechnung und Lieferschein)
*/
private function makeCancellationPDF(
$cancellation_date,
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename,
$original_invoice
) {
$data = [
'shopping_order' => $this->model,
'invoice_date' => $cancellation_date,
'invoice_number' => $cancellation_number,
'original_invoice' => $original_invoice,
'is_cancellation' => true,
];
if ($this->model->auth_user_id) {
UserService::checkUserTaxShippingCountry($this->model->auth_user, $this->model->country_id);
$data = array_merge($data, UserService::getYardInfo());
}
// Verzeichnisse erstellen
if (! Storage::disk('public')->exists($cancellation_dir)) {
Storage::disk('public')->makeDirectory($cancellation_dir);
}
if (! Storage::disk('public')->exists($cancellation_delivery_dir)) {
Storage::disk('public')->makeDirectory($cancellation_delivery_dir);
}
// Kundensprache ermitteln
$customerLocale = $this->model->shopping_user ? $this->model->shopping_user->getLocale() : 'de';
$originalLocale = \App::getLocale();
// Deutsches Original (Finanzamt-Anforderung)
\App::setLocale('de');
$this->createCancellationPDFFiles(
$data,
'de',
$cancellation_number,
$cancellation_dir,
$cancellation_filename,
$cancellation_delivery_dir,
$cancellation_delivery_filename
);
// Lokalisierte Version wenn gewünscht
if ($customerLocale && $customerLocale !== 'de') {
\App::setLocale($customerLocale);
$data['is_copy'] = true;
$localizedFilename = str_replace('.pdf', '-'.$customerLocale.'.pdf', $cancellation_filename);
$localizedDeliveryFilename = str_replace('.pdf', '-'.$customerLocale.'.pdf', $cancellation_delivery_filename);
$this->createCancellationPDFFiles(
$data,
$customerLocale,
$cancellation_number,
$cancellation_dir,
$localizedFilename,
$cancellation_delivery_dir,
$localizedDeliveryFilename
);
}
\App::setLocale($originalLocale);
}
/**
* Erstellt die PDF-Dateien für eine Stornorechnung in einer bestimmten Sprache
*/
private function createCancellationPDFFiles(
array $data,
string $locale,
string $cancellation_number,
string $cancellation_dir,
string $cancellation_filename,
string $cancellation_delivery_dir,
string $cancellation_delivery_filename
) {
$path = Storage::disk('public')->path('');
$template = $this->getTemplateForLocale($locale);
// Stornorechnung erstellen
$pdf_file = new InvoicePDF('pdf.cancellation');
$pdf_file->create($data, $cancellation_filename, 'save', $path.$cancellation_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$cancellation_dir.$cancellation_filename);
$file = $pdfMerger->myMerge('string', $cancellation_filename, $template);
Storage::disk('public')->put($cancellation_dir.$cancellation_filename, $file);
// Storno-Lieferschein erstellen (außer bei Sammelbestellung)
if (! $this->model->shopping_collect_order) {
$pdf_file = new InvoicePDF('pdf.cancellation_delivery');
$pdf_file->create($data, $cancellation_delivery_filename, 'save', $path.$cancellation_delivery_dir);
$pdfMerger = new MyPDFMerger;
$pdfMerger->addPDF($path.$cancellation_delivery_dir.$cancellation_delivery_filename);
$file = $pdfMerger->myMerge('string', $cancellation_delivery_filename, $template);
Storage::disk('public')->put($cancellation_delivery_dir.$cancellation_delivery_filename, $file);
}
}
/**
* Korrigiert die Punkte nach Stornierung einer Rechnung
* Nutzt den SalesPointsVolume Service für konsistente Berechnung
*
* @param UserInvoice $original_invoice Die ursprüngliche Rechnung
* @param UserInvoice $cancellation_invoice Die Stornorechnung
*/
private function correctPointsForCancellation($original_invoice, $cancellation_invoice)
{
// Original UserSalesVolume finden
$original_sales_volume = UserSalesVolume::where('user_invoice_id', $original_invoice->id)->first();
if (! $original_sales_volume) {
\Log::warning('Keine UserSalesVolume gefunden für Rechnung', [
'invoice_id' => $original_invoice->id,
'order_id' => $this->model->id,
]);
return;
}
// Service-Methode verwenden für konsistente Punktekorrektur
SalesPointsVolume::cancelSalesPointsVolume($original_sales_volume, $cancellation_invoice->id);
}
}

View file

@ -27,6 +27,8 @@ class ProductRepository extends BaseRepository
$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['free_shipping_consultant'] = isset($data['free_shipping_consultant']) ? 1 : 0;
$data['is_membership_only'] = isset($data['is_membership_only']) ? 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;
@ -217,7 +219,7 @@ class ProductRepository extends BaseRepository
public function copy($model)
{
$this->model = $model->replicate();
$this->model->name = 'Kopie: ' . $this->model->name;
$this->model->name = 'Kopie: '.$this->model->name;
$this->model->wp_number = null;
$this->model->save();
@ -240,12 +242,12 @@ class ProductRepository extends BaseRepository
// images
foreach ($model->images as $image) {
$name = \App\Services\Slim::sanitizeFileName($image->original_name);
$name = uniqid() . '_' . $name;
$name = uniqid().'_'.$name;
// copy
$data = \Storage::disk('public')->copy(
'images/product/' . $image->product_id . '/' . $image->filename,
'images/product/' . $this->model->id . '/' . $name
'images/product/'.$image->product_id.'/'.$image->filename,
'images/product/'.$this->model->id.'/'.$name
);
ProductImage::create([