This commit is contained in:
E98Developer 2026-02-28 06:53:05 +01:00
commit 68b7c35bef
662 changed files with 258370 additions and 0 deletions

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[compose.yaml]
indent_size = 4

65
.env.example Normal file
View File

@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

11
.gitattributes vendored Normal file
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.fleet
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
Homestead.json
Homestead.yaml
Thumbs.db

59
README.md Normal file
View File

@ -0,0 +1,59 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Redberry](https://redberry.international/laravel-development)**
- **[Active Logic](https://activelogic.com)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View File

@ -0,0 +1,100 @@
<?php
namespace App\Console\Commands;
use App\Enums\DbStatusFieldEnum;
use App\Enums\ProductTypeEnum;
use App\Models\ProductGroup;
use Illuminate\Console\Command;
use Rap2hpoutre\FastExcel\FastExcel;
class EmegrendelesImportProductGroup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:importProductGroup {--file= : default database/import/productGroup.xlsx}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Product group importer';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
private function parseNodes($parentNode, $collection)
{
$parentNodeName = $parentNode->name;
$rootNode = false;
if (! isset($parentNode->parent_id) || is_null($parentNode->parent_id)) {
// o maga a root Node
$rootNode = true;
}
foreach ($collection as $row) {
if (isset($row[$parentNodeName])
&& strlen($row[$parentNodeName]) > 0
&& $row[$parentNodeName] !== 'n/a'
) {
$node = [
'name' => $row[$parentNodeName],
'status' => DbStatusFieldEnum::active,
];
if ($rootNode) {
if (ProductTypeEnum::hasValue($node['name'])) {
$node['type'] = ProductTypeEnum::getKey($node['name']);
} else {
$node['type'] = ProductTypeEnum::X();
}
} else {
$node['type'] = $parentNode->type;
}
$treeNode = $parentNode->children()->create($node);
$this->parseNodes($treeNode, $collection);
}
}
}
/**
* Execute the console command.
*/
public function handle(): int
{
// $name = $this->argument('name');
$collection = (new FastExcel)->sheet(1)->import(
database_path().'/import/productGroup.xlsx'
);
$rootName = array_keys($collection->first())[0];
$tree = [
'name' => $rootName,
'status' => DbStatusFieldEnum::active,
];
\Schema::disableForeignKeyConstraints();
ProductGroup::truncate();
$rootNode = ProductGroup::create($tree);
$this->parseNodes($rootNode, $collection);
\Schema::enableForeignKeyConstraints();
$this->info('Import End');
return 0;
}
}

View File

@ -0,0 +1,191 @@
<?php
namespace App\Console\Commands;
use App\Models\Order;
use App\Models\OrderNumber;
use App\Models\ProductGroup;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\UnsupportedTypeException;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Carbon\Carbon;
use Illuminate\Console\Command;
class EmegrendelesOrderNumberChange extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:orderNumberChange {workerNumber=1}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Change and convert order numbers ';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
private function getMaxSupplierOrderNumber(): int
{
// SELECT max(supplierOrderNumber) FROM `order_archives` WHERE deliveryDate>'2025-01-01';
return \DB::table('order_archives')
->where('deliveryDate', '>', '2025-01-01')
->max('supplierOrderNumber');
}
private function setDefaultOrderNumberForSuppliers(): void
{
$this->info('Start setDefaultOrderNumberForSuppliers');
$supplierIds = \DB::table('order_archives')
->selectRaw('DISTINCT(supplier_id)')
->orderBy('supplier_id')
->get();
foreach ($supplierIds as $supplierId) {
$o = OrderNumber::create([
'id' => $this->startOrderNumber,
'year' => 25,
'supplier_id' => $supplierId->supplier_id,
'order_id' => 1000 + $supplierId->supplier_id,
]);
}
$this->info('End setDefaultOrderNumberForSuppliers');
}
private function changeTable()
{
$this->info('Start changeTable');
$this->info('change id field, and add supplier_order_number field');
\Schema::table('order_numbers', function (\Illuminate\Database\Schema\Blueprint $table) {
$table->integer('id')->change()->unsigned();
$table->dropIndex('PRIMARY');
$table->integer('supplier_order_number')->unsigned()->after('id');
// $table->string('new_column');
// $table->dropColumn('old_column');
// $table->integer('existing_column')->nullable();
});
$this->info('set supplier_order_number = id');
\DB::table('order_numbers')->update(['supplier_order_number' => \DB::raw('id')]);
$startId = 10000;
$this->info('recreate id field value');
foreach (\DB::table('order_numbers')->get() as $orderNumber) {
\DB::table('order_numbers')
->where('id', $orderNumber->id)
->where('order_id', $orderNumber->order_id)
->update(['id' => $startId]);
$startId++;
}
\Schema::table('order_numbers', function (\Illuminate\Database\Schema\Blueprint $table) {
/*
ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, add PRIMARY KEY (`id`);
*/
// $table->integer('id')->change()->autoIncrement()->primary();
$this->info(' set id field auto increment and primary key');
\DB::statement('ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (`id`)');
$this->info(' set unique key on supplier_order_number, year, supplier_id');
$table->unique(['supplier_order_number', 'year', 'supplier_id'], 'unique_supplier_order_number_year_supplier_id');
});
}
private function createSupplierOrderNumber(int $orderId): ?array
{
$ret = [];
if ($Order = Order::find($orderId)) {
// dd($Order->toArray());
if ($o = OrderNumber::where('order_id', $orderId)->get()->first()) {
} else {
$orderYear = Carbon::createFromDate($Order->deliveryDate)->format('y');
$maxSupplierOrderNumber = OrderNumber::where('supplier_id', $Order->supplier_id)
->where('year', $orderYear)
->max('supplier_order_number');
$nextSupplierOrderNumber = $maxSupplierOrderNumber ? ($maxSupplierOrderNumber + 1) : 1;
$this->info($maxSupplierOrderNumber.' '.$nextSupplierOrderNumber);
$maxRetry = 5;
while ($maxRetry > 0) {
try {
$o = OrderNumber::create([
'supplier_order_number' => $nextSupplierOrderNumber,
'year' => $orderYear,
'supplier_id' => $Order->supplier_id,
]);
$o->order_id = $orderId;
$o->save();
break;
} catch (\Exception $e) {
$this->error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - '.$e->getMessage());
$maxRetry--;
$nextSupplierOrderNumber++;
usleep(rand(400, 600));
}
}
if (! $o) {
$this->error('Error creating OrderNumber for supplier:'.$Order->supplier_id.' - maxRetry');
throw new \Exception('Error creating OrderNumber for supplier:'.$Order->supplier_id);
return null;
}
}
$ret = $o->toArray();
} else {
$ret = null;
}
return $ret;
}
/**
* Execute the console command.
*
*
* @throws IOException
* @throws UnsupportedTypeException
* @throws ReaderNotOpenedException
*/
public function handle(): int
{
var_dump(config('app.env', 'env'.now()));
var_dump(config('app.stage', 'fuck'.now()));
$this->changeTable();
/*
$supplierOrderNumber=$this->createSupplierOrderNumber(16605);
dd($supplierOrderNumber);
$this->info("created supplier order number $supplierOrderNumber");
*/
// $this->generateRandomSupplierNumber();
return 0;
/*
ALTER TABLE `order_numbers` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;
ALTER TABLE `order_numbers` DROP PRIMARY KEY;
ALTER TABLE `order_numbers` ADD `supplier_order_number` INT UNSIGNED NOT NULL AFTER `id`;
//$name = $this->argument('name');
\Schema::disableForeignKeyConstraints();
ProductGroup::truncate();
\Schema::enableForeignKeyConstraints();
$this->info('Import End');
return 0;
*/
}
}

View File

@ -0,0 +1,135 @@
<?php
namespace App\Console\Commands;
use App\Models\OrderNumber;
use App\Models\ProductGroup;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\UnsupportedTypeException;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Illuminate\Console\Command;
class EmegrendelesOrderNumberTest extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:orderNumberTest {workerNumber=1}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Recovery and test order numbers from emegrendeles';
protected $startOrderNumber = 4999;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
private function getMaxSupplierOrderNumber(): int
{
// SELECT max(supplierOrderNumber) FROM `order_archives` WHERE deliveryDate>'2025-01-01';
return \DB::table('order_archives')
->where('deliveryDate', '>', '2025-01-01')
->max('supplierOrderNumber');
}
private function setDefaultOrderNumberForSuppliers(): void
{
$this->info('Start setDefaultOrderNumberForSuppliers');
$supplierIds = \DB::table('order_archives')
->selectRaw('DISTINCT(supplier_id)')
->orderBy('supplier_id')
->get();
foreach ($supplierIds as $supplierId) {
$o = OrderNumber::create([
'id' => $this->startOrderNumber,
'year' => 25,
'supplier_id' => $supplierId->supplier_id,
'order_id' => 1000 + $supplierId->supplier_id,
]);
}
$this->info('End setDefaultOrderNumberForSuppliers');
}
private function generateRandomSupplierNumber($count = 10000)
{
$this->info('Start generateRandomSupplierNumber');
$supplierIds = \DB::table('order_archives')
->selectRaw('DISTINCT(supplier_id)')
->orderBy('supplier_id')
->get();
$supplierIds = $supplierIds->pluck('supplier_id')->toArray();
$startOrderID = $this->getMaxSupplierOrderNumber();
$startOrderID += $this->argument('workerNumber') * $count;
$this->info('Start generateRandomSupplierNumber from orderID:'.$startOrderID);
for ($i = 0; $i < $count; $i++) {
$randomSupplierId = $supplierIds[array_rand($supplierIds)];
try {
$o = OrderNumber::create([
'year' => 25,
'supplier_id' => $randomSupplierId,
'order_id' => $startOrderID + $i,
]);
$this->info('Created OrderNumber: '.$o->id.' for supplier:'.$o->supplier_id);
} catch (\Exception $e) {
$this->error('Error creating Order for supplier:'.$randomSupplierId.' - '.$e->getMessage());
}
usleep(rand(150, 600));
}
$this->info('End generateRandomSupplierNumber');
}
/**
* Execute the console command.
*
*
* @throws IOException
* @throws UnsupportedTypeException
* @throws ReaderNotOpenedException
*/
public function handle(): int
{
var_dump(config('app.env', 'env'.now()));
var_dump(config('app.stage', 'fuck'.now()));
$DBMaxSupplierOrderNumber = $this->getMaxSupplierOrderNumber();
if ($this->startOrderNumber < $DBMaxSupplierOrderNumber) {
$this->error('Max startOrderNumber wrong. Set:'.
$this->startOrderNumber.
' inDB:'.$DBMaxSupplierOrderNumber
);
return false;
}
\DB::table('order_numbers')->truncate();
$this->setDefaultOrderNumberForSuppliers();
// $this->generateRandomSupplierNumber();
return 0;
/*
//$name = $this->argument('name');
\Schema::disableForeignKeyConstraints();
ProductGroup::truncate();
\Schema::enableForeignKeyConstraints();
$this->info('Import End');
return 0;
*/
}
}

View File

@ -0,0 +1,325 @@
<?php
namespace App\Console\Commands;
use App\Enums\DbStatusFieldEnum;
use App\Models\Contact;
use App\Models\ProfitCenter;
use App\Models\Role;
use App\Models\User;
use Illuminate\Console\Command;
class EmegrendelesimportProfitCenterWithUsers extends Command
{
private string $defaultFile = 'profitCenterWithUser.php';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:importProfitCenterWithUsers {--file= : default database/import/*defaultFile*}
{--doc : print documentation }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'ProfitCenter import with user';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
$this->signature = str_replace('*defaultFile*', $this->defaultFile, $this->signature);
parent::__construct();
}
public function printDoc()
{
$this->info("
1: source malvac.e98.hu localhost - fs.emegrendeles.hu - felhasznalo
2: sql Select:
SELECT
f.kod id,
f.nev userName,
f.jelszo userPassword,
k_email userEmail,
f.statusz,
fa.nev name,
fa.irsz postCode,
fa.varos city,
fa.cim street,
fa.megjegy note,
k_email email,
k_tel phone,
k_mob mobil,
k_nev contactName,
k_email contactEmail,
k_tel contactPhone,
k_mob contactMobil
FROM `felhasznalo` as f
left join felhasznalo_adat fa on fa.kod=f.kod
WHERE f.`statusz`='F'
order by name
3: export json
");
return 0;
}
/**
* From https://stackoverflow.com/a/19136663/319266
*/
public function stripComments(string $str = '')
{
$str = preg_replace('!/\*.*?\*/!s', '', $str);
$str = preg_replace('/\n\s*\n/', "\n", $str);
return $str;
}
private function stripPrefixedItemFromArray($data, $prefix)
{
if (is_array($prefix)) {
foreach ($prefix as $pre) {
$data = $this->stripPrefixedItemFromArray($data, $pre);
}
} else {
foreach ($data as $k => $v) {
if (strpos($k, $prefix) !== false) {
unset($data[$k]);
}
}
}
return $data;
}
private function getPrefixKeyedDataFromArray($data, $prefix)
{
$retArray = [];
foreach ($data as $k => $v) {
if (strpos($k, $prefix) !== false) {
$key = str_replace($prefix, '', $k);
$key = lcfirst($key);
$retArray[$key] = $v;
}
}
return $retArray;
}
private function getUserDataFromArray($data)
{
$userData = $this->getPrefixKeyedDataFromArray($data, 'user');
$userData['password'] = \Hash::make($userData['password']);
return $userData;
}
private function getContactDataFromArray($data)
{
return $this->getPrefixKeyedDataFromArray($data, 'contact');
}
private function getAcceptedProfitCenterData($data)
{
$acceptedKey = [
'name',
'hooreycaId',
'nameId',
'email',
'postCode',
'city',
'street',
'phone',
'mobil',
'note',
];
$retData = [];
foreach ($data as $k => $v) {
if (in_array($k, $acceptedKey)) {
$retData[$k] = $v;
}
}
return $retData;
}
private function fillNeedProfitCenterData($data,
$num = null,
?bool $convertNull = true)
{
if (! $num) {
$num = random_int(1000, 9999);
}
$data = $this->getAcceptedProfitCenterData($data);
if (! isset($data['hooreycaId'])) {
$data['hooreycaId'] = 'H'.$num;
}
if ($convertNull) {
foreach ($data as $k => $v) {
if ($v === '') {
$data[$k] = null;
}
}
}
$data['status'] = DbStatusFieldEnum::active;
return $data;
}
private function getAcceptedContactData($data)
{
$acceptedKey = [
'name',
'email',
'phone',
'note',
];
if (isset($data['mobil']) && ! is_null($data['mobil']) && $data['mobil'] !== '') {
$data['phone'] = $data['mobil'];
}
$retData = [];
foreach ($data as $k => $v) {
if (in_array($k, $acceptedKey)) {
$retData[$k] = $v;
}
}
return $retData;
}
private function fillNeedContactData($data,
$num = null,
?bool $convertNull = true)
{
$data = $this->getAcceptedContactData($data);
if ($convertNull) {
foreach ($data as $k => $v) {
if ($v === '') {
$data[$k] = null;
}
}
}
$data['status'] = DbStatusFieldEnum::active;
return $data;
}
private function createUser($userData)
{
if ($user = User::where('email', $userData['email'])->first()) {
$emailPieces = explode('@', $userData['email']);
$userData['email'] = $emailPieces[0].time().'@'.$emailPieces[1];
$this->error('Presents user:'.$userData['name'].' rename email:'.$userData['email']);
/* print var_export($userData,true);
print var_export($user->toArray(),true);
die();*/
} else {
}
$user = User::Create($userData);
$this->info('User created:'.$user->name);
return $user;
}
private ?Role $RoleProfitCenter = null;
private function initProfitCenterRole()
{
$this->RoleProfitCenter = Role::where('name', 'profit-center')->first();
}
public function importFile($file, $format = 'JSON')
{
$this->initProfitCenterRole();
$this->info('inport fileName:'.$file.' format'.$format);
$file = base_path().DIRECTORY_SEPARATOR.'database'.DIRECTORY_SEPARATOR.'import'.DIRECTORY_SEPARATOR.$file;
$this->info('file:'.$file);
switch ($format) {
case 'JSON':
try {
// json_decode("{", false, 512, JSON_THROW_ON_ERROR);
$jsonStr = $this->stripComments(file_get_contents($file));
$jsonStr = ltrim($jsonStr);
$itemsArray = json_decode($jsonStr, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
echo $exception->getMessage(); // displays "Syntax error"
exit();
}
break;
case 'PHP':
require_once $file;
$itemsArray = $f;
break;
}
auth()->loginUsingId(1);
foreach ($itemsArray as $k => $item) {
/*
array (
'id' => 182,
'userName' => 'atrium',
'userPass' => 'atriumetterem',
'statusz' => 'F',
'name' => 'Átrium',
'postCode' => 1138,
'city' => 'Budapest',
'street' => 'Váci út 45.',
'note' => '',
'contactName' => 'Szőnyi Iván',
'contactEmail' => 'atrium@eurest.hu',
'contactPhone' => '',
'contactMobil' => '06-30/207-0148',
)
*/
$userData = $this->getUserDataFromArray($item);
$contactData = $this->getContactDataFromArray($item);
/*
print var_export($item,true);
*/
$profitCenterData = $this->stripPrefixedItemFromArray($item, ['user', 'contact']);
$profitCenterData = $this->fillNeedProfitCenterData($profitCenterData, $k + 1);
$ProfitCenter = ProfitCenter::create($profitCenterData);
$contactData = $this->fillNeedContactData($contactData);
$Contact = Contact::create($contactData);
$this->info('Contact created:'.$Contact->name);
$User = $this->createUser($userData);
$User->syncRolesWithoutDetaching([$this->RoleProfitCenter]);
$ProfitCenter->users()->syncWithoutDetaching($User);
$ProfitCenter->syncContactRelations([$Contact->id]);
$this->info('ProfitCenter created:'.$ProfitCenter->name);
}
// $this->info(var_export($Json,true));
}
/**
* Execute the console command.
*/
public function handle(): int
{
// $name = $this->argument('name');
if ($this->option('doc')) {
return $this->printDoc();
}
$file = $this->defaultFile;
if ($this->option('file')) {
$file = $this->option('file');
}
$this->importFile($file, 'PHP');
$this->info('Import End');
return 0;
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class appGetDbConfigCommand extends Command
{
protected $signature = 'app:get-dbconfig';
protected $description = 'Command description';
public function handle(): void
{
$User = new \App\Models\User;
$DriverName = $User->getConnection()->getDriverName();
$config = config('database.connections.'.$DriverName, 'Can not get database connection config');
$this->info(var_export($config, true));
}
}

View File

@ -0,0 +1,142 @@
<?php
namespace App\Console\Commands;
use App\Models\OrderArchive;
use App\Models\OrderArchivesItem;
use Carbon\Carbon;
use Illuminate\Support\Env;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Mail;
class hooreycaIdNotifier extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:hooreycaIdNotifier {--doc : print documentation }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send scheduled hooreyca id missing in order notification to Delirest';
private Carbon $nowTime;
private Carbon $fromTime;
protected bool $sendEmail=true;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
$this->nowTime=Carbon::now();
$this->fromTime=Carbon::yesterday();
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$tmp=explode('\\', __CLASS__);
$className=end($tmp);
$this->info($className." started");
$this->sendEmail= config('app.send_hooreyca_id_notification',false);
//$this->info("Need debug!!!");
$this->info("Send email:".var_export($this->sendEmail,true));
$this->checkMissingHooreycaId();
$this->info($className." end");
return 0;
}
public function info($string, $verbosity = null)
{
if($verbosity){
Log::channel('hooreycaIdNotifier')->info($string, $verbosity);
parent::info($string.' data: '.var_export($verbosity,true));
}else{
Log::channel('hooreycaIdNotifier')->info($string);
parent::info($string);
}
}
private function checkMissingHooreycaId()
{
//$this->fromTime=Carbon::parse('2023-09-18');
$this->info($this->fromTime->toDateString());
$Orders=OrderArchive::select(['id','supplier_name','profit_center_name'])->where('sentTime','>',$this->fromTime->toDateString())->get();
if(count($Orders)<1){
$this->info('No active Order Notification this moment');
return;
}else{
$this->info('Active Order Notification this moment:'.count($Orders).'');
}
//dd($Orders->get()->where('id',12182)->toArray());
$orderItems=OrderArchivesItem::
select(['name','hooreycaId','order_archive_id','id'])
->whereIn('order_archive_id',$Orders->pluck('id'))
->where(function ($query) {
$query->where('hooreycaId','=','')
->orWhereNull('hooreycaId');
})
->orderBy('name')
//->distinct()
->limit(10)
//->toSql();
->get() ;
//dd($orderItems);
if(count($orderItems)<1){
$this->info('No missing Hooreyca ID this moment');
return;
}else{
$this->info('Missing Hooreyca ID this moment:'.count($orderItems));
}
//debug
//return;
//dd($orderItems->toArray());
$viewData=['fromTime'=>$this->fromTime->format('Y.m.d.'),'items'=>[]];
foreach ($orderItems->toArray() as $item){
//dd($Orders->where('id',$item['order_archive_id'])->toArray()[0]);
//dd($item, $Orders->where('id',$item['order_archive_id']));
$OrderData=$Orders->where('id',$item['order_archive_id'])->first()->toArray();
$item=array_merge($item,$OrderData);
$viewData['items'][]=$item;
//parent::info('item',['asdasd']);
$this->info('item',$item);
//Log::channel('hooreycaIdNotifier')->info('item', $item);
//var_dump($item);
}
if($this->sendEmail){
$MailResult=Mail::send('email.hooreycaIdNotifier',$viewData,function($m){
//$subject='Delirest - '.$orderData['profit_center']['name'].' - '.$orderData['humanId'];
$subject='Hooreyca id missing';
$m->subject($subject);
$m->to( explode(',',config('app.mail_to_hooreyca_id_notification','city99@e98.hu')));
$m->bcc('city99@e98.hu');
});
$this->info('Email sent to:'.var_export(explode(',',config('app.mail_to_hooreyca_id_notification','city99@e98.hu'))));
$this->info('Email result'.
var_export($MailResult,true));
}
}
}

View File

@ -0,0 +1,357 @@
<?php
namespace App\Console\Commands;
use App\Enums\OrderFlag;
use App\Http\Controllers\OrderController;
use App\Models\OrderArchive;
use App\Models\SupplierNotifier as SupplierNotifierModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class supplierNotifier extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emegrendeles:supplierNotifier {--doc : print documentation }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send scheduled unprocessed order notification to supplier';
/**
* Create a new command instance.
*
* @return void
*/
protected bool $sendEmail = false;
protected int $minHour = 0;
protected array $notifierHour = [3, 8, 24];
protected array $workHour = [
1 => [4, 18],
2 => [4, 18],
3 => [4, 18],
4 => [4, 18],
5 => [4, 16],
6 => [23, -1],
0 => [23, -1],
];
protected array $nextDay = [
1 => 2,
2 => 3,
3 => 4,
4 => 5,
5 => 1,
6 => 1,
0 => 1,
];
private Carbon $nowTime;
public function __construct()
{
parent::__construct();
$this->minHour = $this->notifierHour[0];
$this->nowTime = Carbon::now();
$this->sendEmail = env('SEND_SUPPLIER_NOTIFICATION', false);
}
public function info($string, $verbosity = null)
{
if ($verbosity) {
Log::channel('supplierNotifier')->info($string, $verbosity);
} else {
Log::channel('supplierNotifier')->info($string);
}
parent::info($string, $verbosity);
}
/**
* Execute the console command.
*/
public function handle(): int
{
$this->info('Supplier Notifier Started');
// Log::channel('supplierNotifier')->info('Supplier Notifier Started',['requestData'=>var_export($request->server(),true)]);
// $name = $this->ask('What is your name?');
// $this->info('hello '.$name);
// $this->error('error','sdsd');
// $this->warn('warn','pppp');
// $this->exampleProgressBar();
// $this->testTimes();
// $this->testSupplierNotifierModel();
/* $s=new SupplierNotifierModel();
$s->makeNotificationsForOrderArchive(12179);*/
$this->info(get_current_user());
$this->checkUnprocessedOrderNotification();
$this->info('Supplier Notifier end');
return 0;
}
private function testSupplierNotifierModel($timeStr = null)
{
$timeStr = '2023-09-08 15:12:12'; // péntek in work
$timeStr = '2023-09-08 6:12:12'; // péntek +3+8
$timeStr = '2023-09-08 17:12:12'; // péntek out of work
$timeStr = '2023-09-08 11:12:12'; // péntek +3
$timeStr = '2023-09-04 07:12:12'; // hetfő +3+8
$timeStr = '2023-09-04 03:12:12'; // hetfő before work
$timeStr = '2023-09-04 18:12:12'; // hetfő out of work
$timeStr = '2023-09-04 07:12:12'; // hetfő +3+8
$timeStr = '2023-09-18 07:13:56';
$SupplierNotifier = new SupplierNotifierModel;
// $SupplierNotifier->makeTime($timeStr);
$SupplierNotifier->makeNotificationsForOrderArchive(12180);
}
public function exampleProgressBar($max = null)
{
if (! $max) {
$max = 100;
}
$bar = $this->output->createProgressBar($max);
$bar->start();
for ($i = 0; $i < $max; $i++) {
usleep(300);
$bar->advance();
}
$bar->finish();
}
private function sendNotification(int $orderArchiveId)
{
// $orderData=app(OrderController::class)->getOrderData($orderArchiveId);
$orderData = app(OrderController::class)->getOrderData(null, getOrderFromOrderArchive($orderArchiveId));
$orderData['feedBackIdLinkParam'] = base64_encode($orderData['feedBackId']);
$orderData['sentTime'] = Carbon::now()->toDateTimeString();
$orderData['noPrintButton'] = true;
$HTMLInvoice = view('modules.order.invoice')->with($orderData
)->render();
$HTMLOrder = view('email.order')->with(['orderHTMLInvoice' => $HTMLInvoice,
'orderData' => $orderData,
]
)->render();
$subject = 'EMLÉKEZTETŐ A Szállítói webrendelőn érkezett megrendelés visszaigazolására ';
$fileType = $orderData['supplier']['emailAttachmentType'];
$attachments = app(OrderController::class)->getEmailAttachment($orderData, $fileType);
$to = [];
if ($orderData['customNotificationEmail'] && $orderData['customNotificationEmail'] != 'NULL') {
$to[] = $orderData['customNotificationEmail'];
}
if (env('APP_STAGE', 'DEV') == 'PROD') {
$to[] = $orderData['supplier']['orderEmail'];
if ($orderData['supplier']['orderEmail2']) {
$to[] = $orderData['supplier']['orderEmail2'];
}
} else {
$to[] = env('MAIL_TO_ORDER_ADDRESS');
}
$bcc = [];
if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
$bcc[] = ('city@e98.hu');
}
$this->info('Notification sent: '.$orderArchiveId.' address:'.implode(',', array_merge($to, $bcc)));
if ($this->sendEmail) {
\Mail::send('email.supplierNotifier', [
'originalEmailHTML' => $HTMLOrder,
], function ($m) use ($fileType, $attachments, $to, $bcc) {
// $subject='Delirest - '.$orderData['profit_center']['name'].' - '.$orderData['humanId'];
$subject = 'EMLÉKEZTETŐ A Szállítói webrendelőn érkezett megrendelés visszaigazolására';
/* if($orderData['orderFlag']==OrderFlag::modifier){
$subject.=' MÓDOSÍTÁS';
}*/
$m->subject($subject);
foreach ($to as $address) {
$m->to($address);
}
foreach ($bcc as $address) {
$m->bcc($address);
}
// $m->attach($attach,['as'=>$fileNameWithExt]);
if ($fileType !== 'none') {
if (is_array($attachments) && count($attachments) > 0) {
foreach ($attachments as $attachData) {
$m->attachData($attachData['attach'], $attachData['fileNameWithExt']);
}
}
}
});
}
}
public function checkUnprocessedOrderNotification()
{
$Orders = OrderArchive::select('id')->where('sentTime', '>', Carbon::now()->subWeek()->toDateTimeString())->whereNull('confirmed')->get();
// OrderArchive::groupBy()
// dd($Orders->toArray());
$NeedNotification = SupplierNotifierModel::whereIn('order_archive_id', $Orders->pluck('id'))
->whereNull('sent')
// ->where('id','<',1)
->where('need_send', '<', DB::raw("'".Carbon::now()->toDateTimeString()."'"))
->orderBy('need_send');
// dd($NeedNotification->toSql(),$NeedNotification->getBindings());
$orderFinished = [];
if ($NeedNotification->get()->count() < 1) {
$this->info('No active Supplier Order Notification this moment');
return;
}
foreach ($NeedNotification->get() as $notification) {
// var_dump($notification->order_archive_id);
// dd($notification->order_archive_id);
if (! in_array($notification->order_archive_id, $orderFinished)) {
$this->sendNotification($notification->order_archive_id);
$orderFinished[] = $notification->order_archive_id;
// var_dump('add'.$notification->order_archive_id);
// var_dump($notification->toArray());
}
}
/*
* kodnál az összes olyat ami régebbi mint mostani dátum hogy ne küldjön újat.
*/
$Notifies = SupplierNotifierModel::whereIn('order_archive_id', $orderFinished)->whereNull('sent')->where('need_send', '<', Carbon::now());
if ($Notifies->get()->count() > 0) {
$Nid = $Notifies->pluck('id')->toArray();
$Notifies->update(['sent' => Carbon::now()]);
$this->info('SupplierNotifier update:'.implode(',', $Nid));
}
}
public function testTimes()
{
/*
* Pl: hétfőn 7 órakkor leadott megrendelés emlékeztető hetfő 10,15 óra.
*/
/* $searchDay = 'Monday';
$searchDate = new Carbon(); //or whatever Carbon instance you're using
$lastDay = Carbon::createFromTimeStamp(strtotime("last $searchDay", $searchDate->timestamp));
$lastDay->setTime(7,rand(0,58));
$checkTime=$lastDay->toDateTimeString();
//$this->nowTime=$lastDay->setTime(7+rand(0,13),rand(0,58));
$this->nowTime=$lastDay->setTime(10,rand(0,58));
$this->nowTime=$lastDay->setTime(15,rand(0,58));
$this->info('nowTime>'.$this->nowTime->toDateTimeString());
$this->diffTime($checkTime);*/
$checkTime = Carbon::parse('2023-09-04');
$checkTime->setTime(7, rand(0, 58));
$nowTime = Carbon::parse('2023-09-04');
$nowTime->setTime(10, 59);
$nowTime->setTime(15, 59);
$this->nowTime = $nowTime;
// $this->info('nowTime>'.$this->nowTime->toDateTimeString());
// $this->diffTime($checkTime);
/*
* hétfőn 21 órakkor leadott megrendelés emlékeztető kedd 7,12 óra.
*/
$checkTime = Carbon::parse('2023-09-04');
$checkTime->setTime(21, rand(0, 58));
$nowTime = Carbon::parse('2023-09-05');
/*
$nowTime->setTime(5,59);
$nowTime->setTime(7,59);
$nowTime->setTime(10,59);
$nowTime->setTime(12,59);
*/
$nowTime->setTime(12, 59);
$this->nowTime = $nowTime;
// $this->info('nowTime>'.$this->nowTime->toDateTimeString());
// $this->diffTime($checkTime);
/*
* Kedden 18 órakkor leadott megrendelés emlékeztető Szerda 7,12 óra.
*/
$checkTime = Carbon::parse('2023-09-05');
$checkTime->setTime(18, rand(0, 58));
$nowTime = Carbon::parse('2023-09-06');
/*
$nowTime->setTime(5,59);
$nowTime->setTime(7,59);
$nowTime->setTime(10,59);
$nowTime->setTime(12,59);
*/
$nowTime->setTime(12, 59);
$this->nowTime = $nowTime;
// $this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
// $this->diffTime($checkTime);
/*
* Péntek 13 órakkor leadott megrendelés emlékeztető hétfő 7,12 óra.
*/
$checkTime = Carbon::parse('2023-09-08');
$checkTime->setTime(13, rand(0, 58));
$nowTime = Carbon::parse('2023-09-11');
/*
$nowTime->setTime(5,59);
$nowTime->setTime(7,59);
$nowTime->setTime(10,59);
$nowTime->setTime(12,59);
*/
$nowTime->setTime(16, 50);
$this->nowTime = $nowTime;
/*
$this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
$this->makeTime($checkTime);
*/
/*
* Péntek 13 órakkor leadott megrendelés emlékeztető hétfő 7,12 óra.
*/
$checkTime = Carbon::parse('2023-09-08');
$checkTime->setTime(19, rand(0, 58));
$nowTime = Carbon::parse('2023-09-11');
/*
$nowTime->setTime(5,59);
$nowTime->setTime(7,59);
$nowTime->setTime(10,59);
$nowTime->setTime(12,59);
*/
$nowTime->setTime(16, 50);
$this->nowTime = $nowTime;
$this->makeTime($checkTime);
/*
$this->info('nowTime>'.$this->nowTime->toDateTimeString().' '.$this->nowTime->format('l'));
$this->diffTime($checkTime);
*/
}
}

27
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Database;
use Illuminate\Database\Schema\Blueprint as BaseBlueprint;
class Blueprint extends BaseBlueprint
{
public function userIdFields()
{
$this->unsignedInteger('created_by')->nullable();
$this->unsignedInteger('updated_by')->nullable();
$this->unsignedInteger('deleted_by')->nullable();
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static kg()
* @method static static l()
* @method static static db()
*/
class BasicUnitEnum extends Enum
{
const kg = 'kg';
const l = 'l';
const db = 'db';
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static orderMail()
* @method static static contactMember()
* @method static static customerService()
*/
final class ContactTypeEnum extends Enum
{
const orderMail = 'Megrendelés e-mailcím';
const contactMember = 'Kapcsolattartó';
const customerService = 'Vevőszolgálat';
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static draft()
* @method static static active()
* @method static static archive()
* @method static static deleted()
*/
final class DbStatusFieldEnum extends Enum
{
const draft = 'draft';
const active = 'active';
const archive = 'archive';
const deleted = 'deleted';
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static pdf()
* @method static static excel()
* @method static static none()
*/
final class EmailAttachmentTypeEnum extends Enum
{
const pdf = 'pdf';
const excel = 'excel';
const nincs = 'nincs';
}

19
app/Enums/OrderFlag.php Normal file
View File

@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static modifier()
* @method static static modified()
* @method static static storno()
*/
final class OrderFlag extends Enum
{
const modifier = 'modifier';
const modified = 'modified';
const storno = 'storno';
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static supplierSelect()
* @method static static parameter()
* @method static static productSelect()
* @method static static invoice()
* @method static static send()
* @method static static sent()
* @method static static confirmed()
*/
final class OrderStatusEnum extends Enum
{
const supplierSelect = 'supplierSelect';
const parameter = 'parameter';
const productSelect = 'productSelect';
const invoice = 'invoice';
const send = 'send';
const sent = 'sent';
const confirmed = 'confirmed';
const archived = 'archived';
/*
const = '';
*/
}

16
app/Enums/OrderType.php Normal file
View File

@ -0,0 +1,16 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static daily()
* @method static static weekly()
*/
final class OrderType extends Enum
{
const daily = 'daily';
const weekly = 'weekly';
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use BenSampo\Enum\Enum;
/**
* @method static static F()
* @method static static N()
* @method static static X()
*/
final class ProductTypeEnum extends Enum
{
const F = 'Food';
const N = 'NonFood';
const X = 'Other';
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Enums;
/**
* @method static static g()
*/
class ProductUnitEnum extends BasicUnitEnum
{
const g = 'g';
const ml = 'ml';
const tálca = 'tálca';
const csom = 'csom';
const dob = 'dob';
const kart = 'kart';
const rúd = 'rúd';
const pár = 'pár';
const zsák = 'zsák';
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace app\Exceptions;
use Flugg\Responder\Exceptions\Http\HttpException;
/**
* An exception thrown whan a relation is not found.
*
* @author Alexander Tømmerås <flugged@gmail.com>
* @license The MIT License
*/
class MethodNotAllowedHttpAPIException extends HttpException
{
/**
* An HTTP status code.
*
* @var int
*/
protected $status = 405;
/**
* An error code.
*
* @var string|null
*/
protected $errorCode = 'MethodNotAllowedHttpException';
}

View File

@ -0,0 +1,264 @@
<?php
namespace App\Exports;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ExportOrderInvoiceExcel implements FromView, ShouldAutoSize, WithColumnFormatting, WithCustomValueBinder, WithMapping, WithStyles
{
public function __construct($data)
{
$this->data = $data;
}
public function collection(): Collection
{
//
}
public function view(): View
{
return view('modules.order.excelExport')->with($this->data);
return view('test.invoice')->with($this->data);
}
private function searchByValue($sheet, $needValue, $partial = true): array
{
foreach ($sheet->getRowIterator() as $row) {
$ret = [
'col' => null,
'row' => null,
];
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($partial) {
if (strpos($cell->getValue(), $needValue) !== false) {
$ret['col'] = $cell->getColumn();
$ret['row'] = $cell->getRow();
$retArray[] = $ret;
}
} else {
if ($cell->getValue() == $needValue) {
$ret['col'] = $cell->getColumn();
$ret['row'] = $cell->getRow();
$retArray[] = $ret;
}
}
}
}
// dd($retArray);
return $retArray;
}
private function formatHead(Worksheet $sheet)
{
$lastCell = $sheet->getHighestColumn();
$sheet->getRowDimension(1)->setRowHeight(170);
$dataRange = 'A1:'.$lastCell.'1';
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
],
'font' => [
'bold' => true,
],
]);
}
private function formatTitleRow(Worksheet $sheet)
{
$headValueInRow = $this->searchByValue($sheet, 'Cikkszám', true)[0]['row'];
$lastCell = $sheet->getHighestColumn();
$dataRange = 'A'.$headValueInRow.':'.$lastCell.$headValueInRow;
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'font' => [
'bold' => true,
],
]);
}
private function formatDayRows(Worksheet $sheet)
{
$pointerText = 'Szállítási dátum:';
$dateValueInRow = $this->searchByValue($sheet, $pointerText, true);
$lastCell = $sheet->getHighestColumn();
// fejlécet skipelni kell
foreach ($dateValueInRow as $item) {
$row = $item['row'];
if ($row > 1) {
$dataRange = 'A'.($row).':'.$lastCell.($row);
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
],
'font' => [
'size' => 14,
],
]);
}
}
}
private function formatSumRows(Worksheet $sheet)
{
$pointerText = 'Végösszeg';
$sumValueInRow = $this->searchByValue($sheet, $pointerText, true);
$lastCell = $sheet->getHighestColumn();
// fejlécet skipelni kell
foreach ($sumValueInRow as $item) {
$row = $item['row'];
if ($row > 1) {
$dataRange = 'A'.$row.':'.$lastCell.$row;
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
],
'font' => [
'bold' => true,
],
]);
}
}
}
private function setItemRowFormat(Worksheet $sheet, $dataRange)
{
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
]);
}
private function formatItemsRows(Worksheet $sheet)
{
$pointerText = 'Végösszeg';
$sumValueInRow = $this->searchByValue($sheet, $pointerText, true);
$lastCell = $sheet->getHighestColumn();
if ($this->data['orderType'] == 'weekly') {
$pointerText = 'Szállítási dátum:';
$dateValueInRow = $this->searchByValue($sheet, $pointerText, true);
for ($i = 0; $i < count($sumValueInRow); $i++) {
$dataRange = 'A'.($dateValueInRow[$i]['row'] + 1).':'.$lastCell.($sumValueInRow[$i]['row'] - 1);
$this->setItemRowFormat($sheet, $dataRange);
}
} else {
$headValueInRow = $this->searchByValue($sheet, 'Cikkszám', true)[0]['row'];
$dataRange = 'A'.($headValueInRow + 1).':'.$lastCell.($sumValueInRow[0]['row'] - 1);
$this->setItemRowFormat($sheet, $dataRange);
}
}
public function styles(Worksheet $sheet)
{
$this->formatHead($sheet);
$this->formatTitleRow($sheet);
$this->formatDayRows($sheet);
$this->formatItemsRows($sheet);
$this->formatSumRows($sheet);
return;
return [
/*$sumValueInRow=>[
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'font' => [
'bold' => true,
],
],*/
];
/* return [
// Style the first row as bold text.
1 => ['font' => ['bold' => true]],
// Styling a specific cell by coordinate.
'B2' => ['font' => ['italic' => true]],
// Styling an entire column.
'C' => ['font' => ['size' => 16]],
];*/
}
public function map($row): array
{
// TODO: Implement map() method.
dd('asd');
}
public function columnFormats(): array
{
// TODO: Implement columnFormats() method.
return [];
}
public function bindValue(Cell $cell, $value)
{
// TODO: Implement bindValue() method.
// dd([$cell,$value]);
// dd($cell->getColumn());
// dd($cell->getDataType());
// $cell->setDataType(DataType::TYPE_STRING);
$noConvertToNumeric = ['A'];
$cell->setValueExplicit($value, DataType::TYPE_STRING);
if (is_numeric($value)) {
if (! in_array($cell->getColumn(), $noConvertToNumeric)) {
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
}
}
return true;
return $cell->getColumn();
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace App\Exports;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ExportSuppliersProfitCentersExcel implements FromView, ShouldAutoSize
{
public function __construct($data)
{
$this->data = $data;
}
public function view(): View
{
return view('admin.export.SupplierProfitCenterExcel')->with($this->data);
}
private function setItemRowFormat(Worksheet $sheet, $dataRange)
{
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
]);
}
private function formatItemsRows(Worksheet $sheet)
{
$pointerText = 'Végösszeg';
$sumValueInRow = $this->searchByValue($sheet, $pointerText, true);
$lastCell = $sheet->getHighestColumn();
if ($this->data['orderType'] == 'weekly') {
$pointerText = 'Szállítási dátum:';
$dateValueInRow = $this->searchByValue($sheet, $pointerText, true);
for ($i = 0; $i < count($sumValueInRow); $i++) {
$dataRange = 'A'.($dateValueInRow[$i]['row'] + 1).':'.$lastCell.($sumValueInRow[$i]['row'] - 1);
$this->setItemRowFormat($sheet, $dataRange);
}
} else {
$headValueInRow = $this->searchByValue($sheet, 'Cikkszám', true)[0]['row'];
$dataRange = 'A'.($headValueInRow + 1).':'.$lastCell.($sumValueInRow[0]['row'] - 1);
$this->setItemRowFormat($sheet, $dataRange);
}
}
public function styles(Worksheet $sheet) {}
public function map($row): array
{
// TODO: Implement map() method.
}
public function columnFormats(): array
{
// TODO: Implement columnFormats() method.
return [];
}
public function bindValue(Cell $cell, $value)
{
return true;
}
}

175
app/Exports/ExportTest.php Normal file
View File

@ -0,0 +1,175 @@
<?php
namespace App\Exports;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ExportTest implements FromView, ShouldAutoSize, WithColumnFormatting, WithCustomValueBinder, WithMapping, WithStyles
{
public function __construct($data)
{
$this->data = $data;
}
public function collection(): Collection
{
//
}
public function view(): View
{
// TODO: Implement view() method.
return view('test.excelExport')->with($this->data);
return view('test.invoice')->with($this->data);
}
private function searchByValue($sheet, $needValue, $partial = true): array
{
$ret = [
'col' => null,
'row' => null,
];
foreach ($sheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($partial) {
if (strpos($cell->getValue(), $needValue) !== false) {
$ret['col'] = $cell->getColumn();
$ret['row'] = $cell->getRow();
}
} else {
if ($cell->getValue() == $needValue) {
$ret['col'] = $cell->getColumn();
$ret['row'] = $cell->getRow();
}
}
}
}
return $ret;
}
public function styles(Worksheet $sheet)
{
$sumValueInRow = $this->searchByValue($sheet, 'Végösszeg', true)['row'];
$headValueInRow = $this->searchByValue($sheet, 'Cikkszám', true)['row'];
$lastCell = $sheet->getHighestColumn();
$lastRow = $sheet->getHighestRow();
// orderProfitcenter data style in return
// rowsHead style in return
// data range border Style
$dataRange = 'A'.($headValueInRow + 1).':'.$lastCell.$sumValueInRow;
$sheet->getStyle($dataRange)->applyFromArray([
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
]);
// footer style in return
return [
'1' => [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
],
'font' => [
'bold' => true,
],
],
$headValueInRow => [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'font' => [
'bold' => true,
],
],
$sumValueInRow => [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
],
'inside' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'font' => [
'bold' => true,
],
],
];
/* return [
// Style the first row as bold text.
1 => ['font' => ['bold' => true]],
// Styling a specific cell by coordinate.
'B2' => ['font' => ['italic' => true]],
// Styling an entire column.
'C' => ['font' => ['size' => 16]],
];*/
}
public function map($row): array
{
// TODO: Implement map() method.
dd('asd');
}
public function columnFormats(): array
{
// TODO: Implement columnFormats() method.
return [];
}
public function bindValue(Cell $cell, $value)
{
// TODO: Implement bindValue() method.
// dd([$cell,$value]);
// dd($cell->getColumn());
// dd($cell->getDataType());
// $cell->setDataType(DataType::TYPE_STRING);
$noConvertToNumeric = ['A'];
$cell->setValueExplicit($value, DataType::TYPE_STRING);
if (is_numeric($value)) {
if (! in_array($cell->getColumn(), $noConvertToNumeric)) {
$cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
}
}
return true;
return $cell->getColumn();
}
}

38
app/Facades/Schema.php Normal file
View File

@ -0,0 +1,38 @@
<?php
namespace App\Facades;
use App\Database\Blueprint;
use Illuminate\Database\Schema\Builder;
use Illuminate\Support\Facades\Schema as BaseSchema;
class Schema extends BaseSchema
{
/**
* Get a schema builder instance for a connection.
*/
public static function connection(?string $name): Builder
{
/** @var Builder $builder */
$builder = static::$app['db']->connection($name)->getSchemaBuilder();
$builder->blueprintResolver(static function ($table, $callback) {
return new Blueprint($table, $callback);
});
return $builder;
}
/**
* Get a schema builder instance for the default connection.
*/
protected static function getFacadeAccessor(): Builder
{
/** @var Builder $builder */
$builder = static::$app['db']->connection()->getSchemaBuilder();
$builder->blueprintResolver(static function ($table, $callback) {
return new Blueprint($table, $callback);
});
return $builder;
}
}

View File

@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Services\AddressService;
use App\Traits\JsonApiCustomFunctionTraits;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Validator;
class AddressController extends Controller
{
use JsonApiCustomFunctionTraits;
protected AddressService $service;
public function __construct(AddressService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response('create');
}
/**
* Store a newly created resource in storage.
*
*
* @throws ValidationException
*/
public function store(Request $request): Response|JsonResponse
{
$validated = Validator::make($request->all(), [
'street' => 'required',
'name' => 'string|nullable|max:250',
'postCode' => 'string|nullable|max:250',
'city' => 'string|nullable|max:250',
'note' => 'string|nullable|max:65000',
]);
if ($validated->fails()) {
return response()->json($this->convertMessageBagToJSONAPIError($validated->getMessageBag()));
}
$newItem = new Address;
$newItem->fill($validated->validated());
$newItem->status = DbStatusFieldEnum::active;
$newItem->save();
return response()->json($newItem->toArray());
}
/**
* Display the specified resource.
*/
public function show(int $ContactId): Response|JsonResponse
{
return response()->json(Address::findOrFail($ContactId));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $ItemId): Response|JsonResponse
{
$validated = Validator::make($request->all(), [
'street' => 'required',
'name' => 'string|nullable|max:250',
'postCode' => 'string|nullable|max:250',
'city' => 'string|nullable|max:250',
'note' => 'string|nullable|max:65000',
]);
if ($validated->fails()) {
return response()->json($this->convertMessageBagToJSONAPIError($validated->getMessageBag()));
}
$newItem = Address::findOrFail($ItemId);
$newItem->fill($validated->validated());
$newItem->save();
return response()->json($newItem->toArray());
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $ContactId): Response|JsonResponse
{
$item = Address::findOrFail($ContactId);
$item->delete();
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,243 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\ContactTypeEnum;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Rules\PhoneRule;
use App\Services\ContactService;
use App\Traits\JsonApiCustomFunctionTraits;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use LaravelJsonApi\Core\Document\Error;
use LaravelJsonApi\Core\Document\ErrorList;
use LaravelJsonApi\Core\Document\ErrorSource;
use LaravelJsonApi\Core\Document\JsonApi;
use Log;
use Validator;
class ContactController extends Controller
{
use JsonApiCustomFunctionTraits;
protected ContactService $service;
public function __construct(ContactService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): Response|JsonResponse|ErrorList|JsonApi
{
Log::channel('chromePHP')->critical('BrowserConsole', ['basename' => basename(__FILE__), 'line' => __LINE__]);
/*
return csrf_token();
*/
/*
$error=Error::make();
$error->setStatus('201');
$error->setId(12);
$error->setSource( ['pointer'=>'pointer','parameter'=>'parameter2']);
return $error;
return JsonApi::make();
*/
$error = Error::fromArray([
'status' => 201,
'id' => 99,
// 'soucre'=>$errorSource
'source' => ['pointer' => 'pointer', 'parameter' => 'parameter4'],
]);
$error2 = Error::fromArray([
// 'soucre'=>$errorSource
'source' => ['pointer' => 'pointer', 'parameter' => 'parameter2'],
]);
// dd(Error::make()->setSource($errorSource));
// return $error;
$errorList = ErrorList::fromArray([
$error, $error2,
]);
return $errorList;
$error = Error::make()->setStatus(202);
/*
['code'=>202,
'detail'=>'ez a hiba leirasa',
'status'=>202,
'title'=>'van baj'
]
$error=Error::fromArray(['code'=>999,
'detail'=>'ez a hiba leirasa',
'status'=>202,
'title'=>'van baj2',
'code'=>'400',
'soucre'=>'xax'
//'soucre'=>['pointer'=>'pointer','parameter'=>'parameter']
]);
*/
$errorSource = ErrorSource::fromArray(
['pointer' => 'pointer', 'parameter' => 'parameter']
);
$error = Error::make();
$error->setStatus('201');
$error->setId(12);
$error->setSource(['pointer' => 'pointer', 'parameter' => 'parameter2']);
$error = Error::fromArray([
'status' => 201,
'id' => 99,
// 'soucre'=>$errorSource
'source' => ['pointer' => 'pointer', 'parameter' => 'parameter4'],
]);
$error2 = Error::fromArray([
'status' => 202,
'id' => 92,
// 'soucre'=>$errorSource
'source' => ['pointer' => 'pointer', 'parameter' => 'parameter2'],
]);
// dd(Error::make()->setSource($errorSource));
// return $error;
$errorList = ErrorList::fromArray([
$error, $error2,
]);
$errorList = JsonApi::make('1');
$errorList->data = ['id' => 12];
$errorList->setMeta(['total' => 200]);
return $errorList;
// return JsonApi::make();
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response('create');
}
/**
* Store a newly created resource in storage.
*
*
* @throws ValidationException
*/
public function store(Request $request): Response|JsonResponse|ErrorList
{
$validated = Validator::make($request->all(), [
'name' => 'required',
'email' => 'email|nullable',
// 'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
'phone' => ['nullable', new PhoneRule],
'note' => 'string|nullable|max:65000',
// 'type'=>'string|nullable|enum:'.ContactTypeEnum::class
'type.*' => ['nullable', Rule::in(ContactTypeEnum::getKeys())],
]);
if ($validated->fails()) {
return $this->convertMessageBagToJSONAPIError($validated->getMessageBag());
}
$fillData = $validated->validated();
if (isset($fillData['type']) && is_array($fillData['type'])) {
$fillData['type'] = implode(',', $fillData['type']);
} else {
$fillData['type'] = null;
}
$contact = new Contact;
$contact->fill($fillData);
$contact->status = DbStatusFieldEnum::active;
$contact->save();
return response()->json($contact->toArray());
}
/**
* Display the specified resource.
*/
public function show(int $ContactId): Response|JsonResponse
{
return response()->json(Contact::findOrFail($ContactId));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $ContactId): Response|JsonResponse|ErrorList
{
/*dd(var_export(ContactTypeEnum::getKeys(),true),[
'name'=>'required',
'email'=>'email',
//'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
'phone'=>['nullable',new PhoneRule()],
'note'=>'string|nullable|max:65000',
'type'=>'nullable|enum:'
]);*/
$validated = Validator::make($request->all(), [
'name' => 'required',
'email' => 'email|nullable',
// 'phone'=>'regex:"^[\/+][0-9]{1,2}[(][0-9]{1,2}[)][0-9]{3}[ ][0-9]{3,4}$"|nullable',
'phone' => ['nullable', new PhoneRule],
'note' => 'string|nullable|max:65000',
'type.*' => ['nullable', Rule::in(ContactTypeEnum::getKeys())],
]);
if ($validated->fails()) {
return $this->convertMessageBagToJSONAPIError($validated->getMessageBag());
}
// dd($validated->validated());
$fillData = $validated->validated();
if (isset($fillData['type']) && is_array($fillData['type'])) {
$fillData['type'] = implode(',', $fillData['type']);
} else {
$fillData['type'] = null;
}
$contact = Contact::findOrFail($ContactId);
$contact->fill($fillData);
$contact->save();
return response()->json($contact->toArray());
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $ContactId): Response|JsonResponse
{
$contact = Contact::findOrFail($ContactId);
$contact->delete();
return response()->json(['success' => true]);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Exports\ExportSuppliersProfitCentersExcel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Maatwebsite\Excel\Facades\Excel;
class ExportController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
return view('admin.export.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show(int $id)
{
if (\request()->get('fileName')) {
$fileNameWithPath = \Storage::disk()->path('Export'.DIRECTORY_SEPARATOR.\request()->get('fileName'));
return response()->file($fileNameWithPath, ['Content-Disposition' => 'attachment;filename='.\request()->get('fileName')]);
}
$Suppliers = \App\Models\Supplier::with(['profitCenter' => function ($query) {
$query->orderBy('name');
}])->orderBy('name')->get();
$fileName = 'SuppliersProfitCenters_'.date('Ymd_His').'.xlsx';
Excel::store(new ExportSuppliersProfitCentersExcel(['Suppliers' => $Suppliers]), 'Export/'.$fileName);
return view('admin.export.SupplierProfitCenterExcelSuccess', ['fileName' => $fileName]);
return response()->json(['success' => true]);
return Excel::download(new ExportSuppliersProfitCentersExcel(['Suppliers' => $Suppliers]), 'SuppliersProfitCenters'.date('Ymd_His').'.xlsx');
return view('admin.export.SupplierProfitCenterExcel')->with(['Suppliers' => $Suppliers]);
}
/**
* Show the form for editing the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function edit(int $id)
{
//
}
/**
* Update the specified resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function update(Request $request, int $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\Response
*/
public function destroy(int $id)
{
//
}
}

View File

@ -0,0 +1,355 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Models\Product;
use App\Models\Supplier;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\View\View;
class FileBatchUploadController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
return view('admin.fileBatchController.index')->with(
[
'suppliers' => $suppliers,
'formUUID' => \Str::uuid(),
]
);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
$functionName = 'client'.ucfirst($request->input('requestType'));
if (method_exists($this, $functionName)) {
return call_user_func([$this, $functionName], $request);
}
return response()->json([
'jsonrpc' => '2.0',
'request_param' => $request->all(),
'result' => null,
'id' => 'id',
], 200);
}
private array $responseJSON = [
'jsonrpc' => '2.0',
'result' => null,
'status' => 200,
];
private array $responseError = [];
private int $responseStatus = 200;
private function responseAddError(string $errorStr)
{
$this->responseError[] = $errorStr;
}
private function responseSetResultStatus(int $status)
{
$this->responseJSON['status'] = $status;
}
private function responseSetStatus(int $status)
{
$this->responseStatus = $status;
}
private function responseAddResult($data)
{
if (! $this->responseJSON['result']) {
$this->responseJSON['result'] = [];
}
$this->responseJSON['result'] = array_merge($this->responseJSON['result'], $data);
}
private function responseAddNewData($pointer, $data)
{
$this->responseJSON[$pointer] = $data;
}
private function responseMake($result = null, $errors = null, $status = null)
{
if ($errors) {
$this->responseError = array_merge($this->responseError, $errors);
}
if (count($this->responseError) > 0) {
$this->responseJSON['errors'] = $this->responseError;
$this->responseSetStatus(500);
}
if ($status) {
$this->responseSetStatus($status);
}
if ($result) {
if (! $this->responseJSON['result']) {
$this->responseJSON['result'] = $result;
} else {
$this->responseJSON['result'] = array_merge($this->responseJSON['result'], $result);
}
}
return response()->json($this->responseJSON, $this->responseStatus);
}
private function removeAttachment(Collection $attachments)
{
/** @var Attachment $attachment */
foreach ($attachments as $attachment) {
$attachment->removeFile();
$attachment->delete();
// dd($attachment->toArray());
}
}
private array $acceptedAttachmentType = ['picture', 'specification'];
private function clientFilesAttach(Request $request)
{
// sleep(30);
$this->responseAddNewData('function', lcfirst(str_replace('client', '', __FUNCTION__)));
if (! $supplier = Supplier::find($request->get('supplier'))) {
return $this->responseMake(null, ['Ismeretlen Beszállító']);
}
if (! $request->get('attachmentType') || ! in_array($request->get('attachmentType'), $this->acceptedAttachmentType)) {
return $this->responseMake(null, ['Ismeretlen csatolmány típus']);
}
$attachTypePointer = $request->get('attachmentType');
// $attachTypePointer='specification';
$attachTypeRelationPointer = $request->get('attachmentType').'s';
// sleep(2);
$fileNamesArray = json_decode($request->get('fileNames'));
foreach ($fileNamesArray as $i => $v) {
// print " $i $v".PHP_EOL;
$product = Product::with($attachTypePointer)->where('supplier_id', '=', $supplier->id)->where('supplierProductNumber', '=', pathinfo($v)['filename'])->get();
if (count($product) < 1) {
$this->responseAddResult([$i => ['name' => $v, 'status' => 'error', 'pid' => null, 'desc' => 'Nincs ilyen termék']]);
continue;
}
if (count($product) > 1) {
$this->responseAddResult([$i => ['name' => $v, 'status' => 'error', 'pid' => null, 'desc' => 'Több termék rendelkezik ezzel a cikkszámmal']]);
continue;
}
$product = $product->first();
$attachCount = count($product->{$attachTypePointer}()->get()->toArray());
if ($attachCount > 0) {
$this->removeAttachment($product->{$attachTypePointer}()->get());
}
/* $this->responseAddResult([$i=>['attachCount'=>$attachCount, 'name'=>$v,'status'=>'ok','pid'=>$product->id,'desc'=>$product->name]]);
continue;
dd($product->{$attachTypePointer}()->get()->toArray());*/
$path = \Storage::disk('uploader')->getDriver()->getAdapter()->getPathPrefix();
$dir = $this->getTargetDirectory();
$file = pathinfo($v)['basename'];
$attachment = new Attachment;
$attachment->attachType = $request->get('attachmentType');
$FileObject = new UploadedFile($path.$dir.$file, $file);
$attachment->addFile($FileObject);
$attachment->attachable()->associate($product);
$attachment->save();
/**@todo:need remove file
*
*/
$this->responseAddResult([$i => ['name' => $v, 'status' => 'ok', 'pid' => $product->id, 'desc' => $product->name]]);
}
return $this->responseMake();
}
private function clientFilesAdded(Request $request)
{
$this->responseAddNewData('function', lcfirst(str_replace('client', '', __FUNCTION__)));
if (! $supplier = Supplier::find($request->get('supplier'))) {
return $this->responseMake(null, ['Ismeretlen Beszállító']);
}
if (! $request->get('attachmentType') || ! in_array($request->get('attachmentType'), $this->acceptedAttachmentType)) {
return $this->responseMake(null, ['Ismeretlen csatolmány típus']);
}
$fileNamesArray = json_decode($request->get('fileNames'));
foreach ($fileNamesArray as $i => $v) {
// print " $i $v".PHP_EOL;
$product = Product::where('supplier_id', '=', $supplier->id)->where('supplierProductNumber', '=', pathinfo($v)['filename'])->get();
if (count($product) < 1) {
$this->responseAddResult([$i => ['name' => $v, 'status' => 'error', 'pid' => null, 'desc' => 'Nincs ilyen termék']]);
continue;
}
if (count($product) > 1) {
$this->responseAddResult([$i => ['name' => $v, 'status' => 'error', 'pid' => null, 'desc' => 'Több termék rendelkezik ezzel a cikkszámmal']]);
continue;
}
$product = $product->first();
$this->responseAddResult([$i => ['name' => $v, 'status' => 'ok', 'pid' => $product->id, 'desc' => $product->name]]);
}
return $this->responseMake();
}
private function getTargetDirectory()
{
return \request()->get('formUUID').DIRECTORY_SEPARATOR;
// return csrf_token().DIRECTORY_SEPARATOR;
}
private function chunkUpload(Request $request)
{
$request->get('chunks');
$request->get('chunk');
$partStr = '.part';
$fileNameWithPath = $this->getTargetDirectory();
$fileNameWithPath .= $request->get('name').$partStr;
\Storage::disk('uploader')->append($fileNameWithPath, $request->file('file')->get());
// \Storage::disk('uploader')->append($fileNameWithPath,Carbon::now());
if ($request->get('chunk') == $request->get('chunks') - 1) {
\Storage::disk('uploader')->move($fileNameWithPath, str_replace($partStr, '', $fileNameWithPath));
}
return response()->json([
'jsonrpc' => '2.0',
'result' => null,
'id' => 'id',
], 200);
}
public function upload(Request $request)
{
$this->responseAddNewData('function', 'upload');
if ($request->get('chunks') > 1) {
return $this->chunkUpload($request);
}
$fileNameWithPath = $this->getTargetDirectory().$request->get('name');
if (\Storage::disk('uploader')->put($fileNameWithPath, $request->file('file')->get())) {
$this->responseAddResult([$request->get('fileId') => ['name' => $request->get('name'), 'status' => 'uploaded', 'uploaded' => Carbon::now()->toDateTimeString()]]);
return $this->responseMake();
}
$this->responseAddError('Feltöltési hiba!');
return $this->responseMake();
}
private function x()
{
// 5 minutes execution time
@set_time_limit(5 * 60);
// Uncomment this one to fake upload time
usleep(500000);
// die(ini_get("upload_tmp_dir"));
// Settings
// $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
$targetDir = './uploads';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 12 * 3600; // Temp file age in seconds
// Create target dir
if (! file_exists($targetDir)) {
@mkdir($targetDir);
}
// Get a file name
if (isset($_REQUEST['name'])) {
$fileName = $_REQUEST['name'];
} elseif (! empty($_FILES)) {
$fileName = $_FILES['file']['name'];
} else {
$fileName = uniqid('file_');
}
$filePath = $targetDir.DIRECTORY_SEPARATOR.$fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST['chunk']) ? intval($_REQUEST['chunk']) : 0;
$chunks = isset($_REQUEST['chunks']) ? intval($_REQUEST['chunks']) : 0;
// Remove old temp files
if ($cleanupTargetDir) {
if (! is_dir($targetDir) || ! $dir = opendir($targetDir)) {
exit('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir.DIRECTORY_SEPARATOR.$file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}
// Open temp file
if (! $out = @fopen("{$filePath}.part", $chunks ? 'ab' : 'wb')) {
exit('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if (! empty($_FILES)) {
if ($_FILES['file']['error'] || ! is_uploaded_file($_FILES['file']['tmp_name'])) {
exit('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}
// Read binary input stream and append it to temp file
if (! $in = @fopen($_FILES['file']['tmp_name'], 'rb')) {
exit('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (! $in = @fopen('php://input', 'rb')) {
exit('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
// Check if file has been uploaded
if (! $chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
// Return Success JSON-RPC response
exit('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
}
}

View File

@ -0,0 +1,450 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use App\Models\PriceList;
use App\Models\Supplier;
use App\Services\PriceListService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Rap2hpoutre\FastExcel\FastExcel;
class PriceListController extends Controller
{
protected PriceListService $service;
/*
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKRELHooreyca.xlsx';
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceList.xlsx';
protected $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListOriginal.xlsx';
protected $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListFieldTypeError.xlsx';
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSort.xlsx';
protected string $testFile='V:\!EurestNew\Katitol\Jáner 2021.12.13-tólv2.xlsx';
protected string $testFile='V:\!EurestNew\Katitol\Egertej egységes árlista - 2021.12.01-től.xlsx';
protected string $testFile='V:\!EurestNew\Katitol\Rozmár Egységes árlista 2021.11.15v2.xlsx';
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSort.xlsx';
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKREL.xlsx';
protected string $testFile='V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKRELHooreyca.xlsx';
*/
protected string $testFile = 'V:\!EurestNew\doc\forrasAnyagok\examplePriceListSortKREL.xlsx';
protected bool $testFileMod = false;
protected int $dataStartLine = 3;
public function __construct(PriceListService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View|Response|JsonResponse
{
// test
if (\request()->input('t') == 1) {
$priceListId = 222;
$repository = new \App\Repositories\PriceListRepository;
$ret = ['data' => []];
$repository->setRelation('attachment');
$priceList = $repository->getQueryWithRelations()->find($priceListId);
/*
* árlistábol kell a suppplier ID
* supplierbol kellenek a csatolt egységek
* $S->pluck????
*/
$supplier = Supplier::with('profitCenter')->find($priceList->supplier_id);
// print "<pre>";
// profit_center
// Supplier::with('profitCenter')->pluck('profitCenter.id')->toArray()
$destEmail = $supplier->profitCenter->pluck('email', 'name')->filter(function ($value) {
return ! is_null($value);
});
if ($destEmail->isEmpty()) {
return response()->noContent();
}
// ->filter(function ($value){return !is_null($value);})
$emailData['priceList']['note'] = $priceList->note;
$emailData['priceList']['filename'] = $priceList->attachment->filename;
$emailData['priceList']['fileName'] = $priceList->attachment->original_filename;
$emailData['priceList']['url'] = $priceList->attachment->PublicUrl;
$MailData['HTML'] = view('email.priceListChangeNotify')->with($emailData)->render();
echo '<pre>';
$destEmail->each(function ($emailAddress) use ($emailData) {
var_export($emailAddress);
\Mail::send('email.priceListChangeNotify', $emailData, function ($m) use ($emailAddress) {
$m->subject('Árlista változás ');
$m->to($emailAddress);
/*
if(env('APP_STAGE')=='PROD'){
$m->to($emailAddress);
}else{
if(env('APP_STAGE')=='TEST'){
$m->to('beszerzes@delirest.hu');
}
if(env('APP_STAGE')=='DEV'){
$m->to('city@e98.hu');
}
}
*/
if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
$m->bcc('city@e98.hu');
}
// $m->attach($attach,['as'=>$fileNameWithExt]);
// $m->attachData($attach,$fileNameWithExt);
});
});
/*
print "<pre>";
var_export($destEmail);
var_export($item->toArray());
var_export($emailData);
return view('email.priceListChangeNotify')->with($emailData);
*/
dd('end');
dd([$destEmail->filter(function ($value) {
return ! is_null($value);
}), $priceListId, $item, $S]);
$importStartLine = $this->dataStartLine;
$importLength = 9999;
// $importStartLine = rand(100,400);
$importLength = 10;
$collection = $this->getRowCollection();
/*$startDate = $collection[0][1];
$supplierName = $collection[1][1];
*/
$supplierId = 9;
$availableDate = '2022-01-26';
$res = $this->service->importPriceList($supplierId, $availableDate, $collection->slice($importStartLine, $importLength)->toArray());
// $res = $this->service->importPriceListCheck($supplierId, $collection->slice($importStartLine,$importLength)->toArray());
echo '<pre>';
dd($res);
// @todo: file attachment storage
dd($res, $res['rows'][1]['originalData'], $this->service->getError());
$success = false;
if ($res) {
if ($res['importSuccess'] == true) {
$success = true;
}
}
return \response()->json([
'success' => $success,
'error' => $this->service->getError(),
]);
$collection = $this->getRowCollection();
// $startDate=$collection[0][1];
// $supplierName=$collection[1][1];
$supplierId = 7;
$availableDate = '2022-01-01';
if (! $return = $this->service->importPriceListCheck($supplierId, $collection->slice($this->dataStartLine)->toArray())) {
// if(!$return=$this->service->importPriceListCheck(99999,[])){
$return = $this->service->getError();
return \response()->json([
'success' => false,
// 'file'=>$file->getLinkTarget(),
// 'item'=>$collection[0],
'error' => $return,
], 500);
}
dd($return);
return \response()->json(array_merge($return, ['success' => true]));
}
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
// var_dump($this->testFileMod);
return view('admin.priceList.index')->with(
['suppliers' => $suppliers,
'testFileMod' => ($this->testFileMod) ? 'true' : 'false',
]
);
}
/**
* Show the form for creating a new resource.
*/
public function create(): View
{
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
return view('admin.priceList.create')->with(
['suppliers' => $suppliers,
'testFileMod' => $this->testFileMod,
]
);
}
private function getSourceFileName()
{
if ($this->testFileMod) {
/*
* A teszt fajlal dolgozunk
*
*/
$fileName = basename($this->testFile);
} else {
/*
* A feltott fajlal dolgozunk
$file=$file->getLinkTarget(); //nem mukodik splfileinfo elszall file olvasasi hibaval
$file = $request->file('priceListFile');
*/
$fileName = $_FILES['priceListFile']['name'];
}
return $fileName;
}
private function getSourceFile()
{
if ($this->testFileMod) {
/*
* A teszt fajlal dolgozunk
*
*/
$file = $this->testFile;
} else {
/*
* A feltott fajlal dolgozunk
$file=$file->getLinkTarget(); //nem mukodik splfileinfo elszall file olvasasi hibaval
$file = $request->file('priceListFile');
*/
$file = $_FILES['priceListFile']['tmp_name'];
}
return $file;
}
private function getRowCollection(): Collection
{
return (new FastExcel)->sheet(1)->withoutHeaders()->import(
$this->getSourceFile()
);
}
private function importPriceListCheck(Request $request)
{
app('debugbar')->disable();
$collection = $this->getRowCollection();
// $startDate=$collection[0][1];
// $supplierName=$collection[1][1];
$supplierId = $request->input('supplier');
$availableDate = $request->input('availableDate');
if (! $return = $this->service->importPriceListCheck($supplierId, $collection->slice($this->dataStartLine)->toArray())) {
// if(!$return=$this->service->importPriceListCheck(99999,[])){
$return = $this->service->getError();
return \response()->json([
'success' => false,
// 'file'=>$file->getLinkTarget(),
// 'item'=>$collection[0],
'error' => $return,
], 500);
}
return \response()->json(array_merge($return, ['success' => true]));
}
private function notificationNewPriceList($priceListId)
{
// debugbar($priceListId);
$repository = new \App\Repositories\PriceListRepository;
$repository->setRelation('attachment');
$priceList = $repository->getQueryWithRelations()->find($priceListId);
/*
* árlistábol kell a suppplier ID
* supplierbol kellenek a csatolt egységek
*/
$supplier = Supplier::with('profitCenter')->find($priceList->supplier_id);
$destEmail = $supplier->profitCenter->pluck('email', 'name')->filter(function ($value) {
return ! is_null($value);
});
if ($destEmail->isEmpty()) {
return;
}
$emailData['priceList']['note'] = $priceList->note;
$emailData['priceList']['filename'] = $priceList->attachment->filename;
$emailData['priceList']['fileName'] = $priceList->attachment->original_filename;
$emailData['priceList']['url'] = $priceList->attachment->PublicUrl;
// $MailData['HTML']=view('email.priceListChangeNotify')->with($emailData)->render();
$destEmail->each(function ($emailAddress) use ($emailData) {
\Mail::send('email.priceListChangeNotify', $emailData, function ($m) use ($emailAddress) {
$m->subject('Árlista változás ');
if (env('APP_STAGE') == 'PROD') {
$m->to($emailAddress);
} else {
if (env('APP_STAGE') == 'TEST') {
$m->to('beszerzes@delirest.hu');
}
if (env('APP_STAGE') == 'DEV') {
$m->to('city@e98.hu');
}
}
if (env('MAIL_TO_ORDER_ADDRESS') != 'city@e98.hu') {
$m->bcc('city@e98.hu');
}
});
});
return 'Notified Ok:'.$priceListId;
}
private function importPriceList(Request $request): JsonResponse
{
$importStartLine = $this->dataStartLine;
$importLength = 9999;
// $importStartLine = rand(100,400);
// $importLength=20;
$collection = $this->getRowCollection();
/*$startDate = $collection[0][1];
$supplierName = $collection[1][1];
*/
$supplierId = $request->input('supplier');
$availableDate = $request->input('availableDate');
$otherField = [];
$otherField['note'] = $request->input('note');
$res = $this->service->importPriceList($supplierId, $availableDate, $collection->slice($importStartLine, $importLength)->toArray(), $otherField);
$success = false;
if ($res) {
if ($res['importSuccess'] == true) {
$success = true;
$attachmentFile = new Attachment;
$attachmentFile->addStreamedFile(file_get_contents($this->getSourceFile()), $this->getSourceFileName());
// fajl csatolasa
$attachmentFile->attachable()->associate(PriceList::find($res['id']));
$attachmentFile->save();
/*
* Álista értesítő profitcenter számára
* http://pm.e98.hu/agiles/117-9/current?issue=EV3-69
*
*/
$res['NotifyRes'] = $this->notificationNewPriceList($res['id']);
}
}
return \response()->json([
'success' => $success,
'error' => $this->service->getError(),
'res' => $res,
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
if ($request->input('finalization') == '1') {
return $this->importPriceList($request);
} else {
return $this->importPriceListCheck($request);
}
}
/**
* Display the specified resource.
*/
public function show(int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $Id): Response|JsonResponse
{
$repository = new \App\Repositories\PriceListRepository;
if ($repository->delete($Id)) {
$ret = ['success' => true];
} else {
$ret = ['success' => false];
}
return \response()->json($ret);
}
public function getDataTableContent(): JsonResponse
{
$repository = new \App\Repositories\PriceListRepository;
$ret = ['data' => []];
$items = $repository->getQueryWithRelations()->get()->toArray();
foreach ($items as $item) {
if (! isset($item['supplier']['name'])) {
} else {
$data['id'] = $item['id'];
$data['supplierName'] = $item['supplier']['name'];
$data['available'] = formatterDate($item['available']);
$data['created_at'] = formatterDateTime($item['created_at']);
$data['note'] = $item['note'];
$ret['data'][] = $data;
}
}
return \response()->json($ret);
var_dump($ret);
dd($ret);
dd($repository->all()->toArray());
return \response()->file('exapmle2.json');
}
}

View File

@ -0,0 +1,142 @@
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Repositories\ProductRepository;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;
class PriceListProfitCenterController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
$profitCenters = ProfitCenter::orderBy('name')->get(['id', 'name'])->toArray();
// var_dump($this->testFileMod);
return view('admin.priceListProfitCenter.index')->with(
['suppliers' => $suppliers,
'profitCenters' => $profitCenters,
// 'testFileMod'=>($this->testFileMod)?'true':'false'
]
);
}
public function getDataTableContent(): JsonResponse
{
$groupId = null;
$searchStr = null;
if (\request()->get('profitCenterId')) {
$profitCenterId = \request()->get('profitCenterId');
} else {
return \response()->json(['data' => []]);
}
if (\request()->get('supplierId')) {
$supplierId = \request()->get('supplierId');
} else {
return \response()->json(['data' => []]);
}
if (\request()->get('deliveryDate')) {
$deliveryDate = \request()->get('deliveryDate');
} else {
$deliveryDate = Carbon::now()->format('Y-m-d');
}
$special = [];
$special['withFavorites'] = true;
if (\request()->get('searchStr')) {
$searchStr = \request()->get('searchStr');
if (substr($searchStr, 0, 2) == '**') {
$special['type'] = str_replace('*', '', $searchStr);
$special['profitCenterId'] = $profitCenterId;
$searchStr = null;
}
} else {
if (\request()->get('groupId')) {
$groupId = \request()->get('groupId');
}
}
if (\request()->get('krel')) {
if (request()->get('krel') === 'true') {
$special['krel'] = 1;
}
}
debug(\request()->all());
$productRepo = new ProductRepository;
$productRepo->setRelation(
'ProductGroup', 'Supplier', 'Producer', 'PriceList', 'LastPrice');
// $products=$productRepo->getByGroupId($groupId,true);
$products = $productRepo->getSupplierProductFromPriceList($supplierId, $profitCenterId, $deliveryDate, $groupId, $searchStr, $special);
// debug($products[1]);
$ret = ['data' => []];
// dd($products[0]);
foreach ($products as $product) {
// dd(count($product['price_list']));
// if(count($product['price_list'])>0){
if ($product['price_list_price']) {
$data = [];
$data['id'] = $product['id'];
$data['name'] = $product['name'];
$data['packing'] = $product['packing'];
$data['unitValue'] = $product['unitValue'];
$data['productUnit'] = $product['productUnit'];
$data['sellerUnit'] = $product['sellerUnit'];
$data['unitMultiplier'] = $product['unitMultiplier'];
$data['amountUnit'] = $product['amountUnit'];
$data['note'] = ($product['note'] ? $product['note'] : '');
// $product['product_group']['name'];
// $data['price']=$product['last_price'][0]['pivot']['price'];
$data['price'] = $product['price_list_price']['price'];
$data['hooreycaId'] = $product['hooreycaId'];
$data['office'] = '';
$data['extn'] = '';
$data['favorites'] = $product['favorites'];
if ($product['krel'] == 1) {
$product['krel'] = '*';
} else {
$product['krel'] = '';
}
$data['krel'] = $product['krel'];
$ret['data'][] = $data;
} else {
}
}
return \response()->json($ret);
return \response()->file('exapmle2.json');
}
public function getProductGroupHTML(): View
{
$productRepo = new ProductRepository;
$productsGroupIds = $productRepo->getSupplierProductGroupsIdFromPriceList(
\request()->get('supplierId'), \request()->get('deliveryDate'));
$productGroupArray = [];
if ($productsGroupIds && count($productsGroupIds) > 0) {
$ProductGroups = new ProductGroup;
$productGroupArray = $ProductGroups->nodesWithParentToTree($productsGroupIds);
}
return view('modules.order.productSelectSidebarProductGroupPartial')->with(['productGroup' => $productGroupArray]);
dd($productGroupArray);
}
}

View File

@ -0,0 +1,377 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\BasicUnitEnum;
use App\Enums\ProductUnitEnum;
use App\Http\Controllers\Controller;
use App\Models\Producer;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Services\ProductService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class ProductController extends Controller
{
protected ProductService $service;
private bool $testMode = false;
public function __construct(ProductService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View
{
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
$profitCenters = ProfitCenter::orderBy('name')->get(['id', 'name'])->toArray();
$productGroups = ProductGroup::orderBy('name')->get(['id', 'name'])->toArray();
$producer = Producer::orderBy('name')->get(['id', 'name'])->toArray();
DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
$hooreycaNames = Product::orderBy('buyerProductName')->where('buyerProductName', '!=', '')->groupBy('buyerProductName')->get(['id', 'buyerProductName as name'])->toArray();
DB::statement("SET sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));");
// dd($hooreycaNames);
// dd(json_encode($service->getAvailableFilters()));
return view('admin.product.index')->with(
[
'suppliers' => $suppliers,
'profitCenters' => $profitCenters,
'productGroups' => $productGroups,
'producer' => $producer,
'hooreycaNames' => $hooreycaNames,
'testMode' => $this->testMode,
'init' => (bool) \request()->get('init', true),
// 'formUUID'=>\Str::uuid(),
// 'availableFilters'=>json_encode(['Product'=>['suppliers','date','dateFrom','dateTo','productGroups','products','hooreycaNames','producers']]),
'availableFilters'=>json_encode(['Product'=>['suppliers','productGroups','products','hooreycaNames','producers','specialOffer']]),
]
);
$retData = [];
// $retData['testMode']=($this->testMode)?'true':'false';
$retData['testMode'] = $this->testMode;
$retData['init'] = (bool) \request()->get('init', true);
return view('admin.product.index')->with($retData);
/*
$ProductGroup=new \App\Models\ProductGroup();
$productGroupArray=$ProductGroup->allWithParents(2);
return view('admin.product.edit')->with(
['productGroup'=>$productGroupArray,
'productUnit'=>ProductUnitEnum::getValues(),
'producer'=>[
['id'=>11,'name'=>'Voyagex'],
['id'=>12,'name'=>'Győri előre'],
['id'=>13,'name'=>'Elmar'],
['id'=>14,'name'=>'Gramellini'],
]
]);
*/
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
$ret = ['status' => 'ok', 'message' => 'Product save successfully!'];
return \response()->json($ret);
// return \response(json_encode(['status'=>'ok','message'=>'Product save successfully!']),200);
}
/**
* Display the specified resource.
*/
public function show(int $ProductId): Response|JsonResponse
{
return response('ez show');
}
/**
* Show the form for editing the specified resource.
*
* @param int $ProductId
*/
public function prof_flag($str)
{
global $prof_timing, $prof_names;
$prof_timing[] = microtime(true);
$prof_names[] = $str;
}
// Call this when you're done and want to see the results
public function prof_print()
{
global $prof_timing, $prof_names;
$size = count($prof_timing);
if ($size == 0) {
return;
}
for ($i = 0; $i < $size - 1; $i++) {
echo "<b>{$prof_names[$i]}</b><br>";
echo sprintf('&nbsp;&nbsp;&nbsp;%f<br>', $prof_timing[$i + 1] - $prof_timing[$i]);
}
echo "<b>{$prof_names[$size - 1]}</b><br>";
}
public function edit(int $ProductId): View
{
// $this->prof_flag('Start');
$ProductGroup = new \App\Models\ProductGroup;
// @todo:too slow, change other methode
$productGroupArray = $ProductGroup->allWithParents(3);
$Product = Product::with(['Supplier', 'Producer', 'ProductGroup', 'picture', 'specification'])->find($ProductId);
$Product->setAttributePrice();
// $this->prof_flag(__LINE__);
$Producer = [];
foreach (Producer::orderBy('name')->get() as $producer) {
$Producer[] = ['id' => $producer->id, 'name' => $producer->name];
}
// $this->prof_flag(__LINE__);
if (! \request()->ajax()) {
// $this->prof_print();
dd($productGroupArray, $Product, $Product->toArray());
}
//
return view('admin.product.edit')->with(
['Product' => $Product,
'productGroup' => $productGroupArray,
'productUnit' => BasicUnitEnum::getValues(),
'sellerUnit' => ProductUnitEnum::getValues(),
// 'productUnit'=>ProductUnitEnum::getValues(),
'producer' => $Producer,
]);
}
/**
* Update the specified resource in storage.
*
*/
public function update(Request $request, int $ProductId): Response|JsonResponse
{
// $Product=Product::with(['Supplier','Producer','ProductGroup','picture','specification'])->find($ProductId);
// dd($request->all(),$ProductId);
$validated = $request->validate([
'name' => 'required|string|max:255',
'supplierId' => 'required|integer|exists:suppliers,id',
'producer' => 'required|exists:producers,id',
'packaging' => 'required|numeric|min:0',
'unitValue' => 'required|numeric|min:0',
'productUnit' => 'required|string|in:'.implode(',', BasicUnitEnum::getValues()),
'sellerUnit' => 'required|string|in:'.implode(',', ProductUnitEnum::getValues()),
'unitMultiplier' => 'required|numeric|min:0',
'amountUnit' => 'required|string|in:'.implode(',', ProductUnitEnum::getValues()),
'vat' => 'required|numeric|min:0',
'supplierProductNumber' => 'nullable|string|max:255',
'buyerProductName'=>'required|string|max:255',
'productGroup' => 'required|exists:product_groups,id',
'hooreycaId' => 'nullable|string|max:255',
'HooreycaUnit' => 'nullable|string|max:255',
'HooreycaMultiplier' => 'nullable|numeric|min:0',
'note' => 'nullable|string',
'canSee' => 'boolean',
'krel' => 'boolean',
'specialOffer' => 'boolean',
'price' => 'required|numeric|min:0',
]);
// $request->merge(['canSee'=>$request->has('canSee')]);
// $request->merge(['krel'=>$request->has('krel')]);
// $request->merge(['specialOffer'=>$request->has('specialOffer')]);
$validated['producer_id'] = $validated['producer'][0];
unset($validated['producer']);
$validated['product_group_id'] = $validated['productGroup'][0];
unset($validated['productGroup']);
$validated['note'] = str_replace("\r\n", "\n", $validated['note']);
// dd($validated,$request->all());
$ret = [];
if (! $this->service->update($ProductId, $validated)) {
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['errors'] = $this->service->getError();
}
return \response()->json($ret)->setStatusCode(422);
}
if (! $this->service->updatePrice($ProductId, $validated['price'])) {
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['errors'] = $this->service->getError();
}
return \response()->json($ret)->setStatusCode(422);
}
/**@todo: save picture, specification, price
* save picture
* save specification
*/
$ret = ['status' => 'ok', 'message' => 'Product save successfully!'];
$ret['success'] = true;
return \response()->json($ret);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $ProductId): Response|JsonResponse
{
//
return response()->noContent();
}
public function getDataTableContent(Request $request): JsonResponse
{
$searchParameter = json_decode($request->input('ajaxData'), true);
$Product = Product::with(['Supplier', 'Producer', 'ProductGroup']);
if ($request->input('search.value')) {
$Product->where('name', 'like', '%'.$request->input('search.value').'%');
}
if (isset($searchParameter['products[]'])) {
if (! is_array($searchParameter['products[]'])) {
$searchParameter['products[]'] = [$searchParameter['products[]']];
}
$Product->whereIn('name', $searchParameter['products[]']);
}
if (isset($searchParameter['hooreycaNames[]'])) {
if (! is_array($searchParameter['hooreycaNames[]'])) {
$searchParameter['hooreycaNames[]'] = [$searchParameter['hooreycaNames[]']];
}
$Product->whereIn('buyerProductName', $searchParameter['hooreycaNames[]']);
}
if (isset($searchParameter['producers[]'])) {
if (! is_array($searchParameter['producers[]'])) {
$searchParameter['producers[]'] = [$searchParameter['producers[]']];
}
$Product->whereIn('producer_id', $searchParameter['producers[]']);
}
if (isset($searchParameter['suppliers[]'])) {
if (! is_array($searchParameter['suppliers[]'])) {
$searchParameter['suppliers[]'] = [$searchParameter['suppliers[]']];
}
$Product->whereIn('supplier_id', $searchParameter['suppliers[]']);
}
if (isset($searchParameter['productGroups[]'])) {
if (! is_array($searchParameter['productGroups[]'])) {
$searchParameter['productGroups[]'] = [$searchParameter['productGroups[]']];
}
foreach ($searchParameter['productGroups[]'] as $productGroupId) {
$productGroup = ProductGroup::find($productGroupId);
// $children=$productGroup->getChildNodesArray($productGroup);
$nodeDepth = ProductGroup::where('id', $productGroupId)->withDepth()->first()->depth;
if ($nodeDepth == 2) {
$childrenId = $productGroup->descendants()->withDepth()->having('depth', '=', $nodeDepth + 1)->get()->pluck('id');
// $searchParameter['productGroups[]']=array_merge($searchParameter['productGroups[]'],$childrenId->toArray());
}
// dd($productGroupId,$nodeDepth,$children);
}
$Product->whereIn('product_group_id', $searchParameter['productGroups[]']);
}
// Akciós szűrő (specialOffer): '1' = Igen, '0' = Nem, '' vagy hiányzik = Mindegy
if(isset($searchParameter['specialOffer']) && $searchParameter['specialOffer'] !== ''){
$val = $searchParameter['specialOffer'] == '1' ? 1 : 0;
$Product->where('specialOffer', $val);
}
if (! $request->ajax()) {
// dd($searchParameter,$Product->toSql(), $request->input());
}
// dd($request->input('order.0.dir'));
if ($request->input('order.0')) {
// dd($request->input('order.0'));
$pointer = $request->input('order.0.column');
$orderName = $request->input('columns')[$pointer]['data'];
$orderDirection = $request->input('order.0.dir');
$Product->orderBy($orderName, $orderDirection);
}
// if($request->get('search.value'))
$count = $Product->count('id');
$Product->limit($request->get('length'));
$Product->offset($request->get('start'));
$ProductDD = $Product->toSql();
// dd($request->all(),$ProductDD);
// $ProductDD=$Product->get()->first()->LastPrice;
$ret = [
'draw' => $request->get('draw'),
'recordsTotal' => Product::count(),
'recordsFiltered' => $count,
'data' => [],
];
if (! $request->ajax()) {
// dd($Product->get()->toArray() );
}
foreach ($Product->get() as $item) {
$data['id'] = $item->id;
$data['name'] = $item->name;
$data['hooreycaId'] = $item->hooreycaId;
$data['productGroup'] = $item->ProductGroup->name;
if (isset($item->Supplier->name)) {
$data['supplierName'] = $item->Supplier->name;
} else {
$data['supplierName'] = '-';
}
if (is_numeric($item->Price())) {
$data['price'] = $item->Price();
} else {
$data['price'] = '-';
}
$data['created_at'] = formatterDateTime($item->created_at);
$ret['data'][] = $data;
}
$ProductDD = $ret['data'];
if (! $request->ajax()) {
dd($searchParameter, getSql($Product), $request->input(), $ret['data']);
}
return \response()->json($ret);
dd($request->all(), $ProductDD);
}
}

View File

@ -0,0 +1,236 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\ProductGroup;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Validation\Rule;
use Kalnoy\Nestedset\Collection;
use LaravelJsonApi\Core\Document\Error;
class ProductGroupController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
/*
$error=Error::make()->setStatus(202);
['code'=>202,
'detail'=>'ez a hiba leirasa',
'status'=>202,
'title'=>'van baj'
]
return $error;
*/
return view('admin.productGroup.index');
}
public function treeNodeAdd(Request $request): JsonResponse
{
return response()->json(['id' => 'tmp_'.time()]);
}
private function nodeRename($nodeId, $name) {}
private function nodeAdd(array $data, ?int $parentId = null)
{
$parent = ProductGroup::findOrFail($parentId);
if (! isset($data['type']) || $data['type'] == null) {
$data['type'] = $this->getParentType($parentId);
}
$node = $parent->children()->create($data);
return $node;
}
private function getParentType(int $parentId, $defaultType = null)
{
$returnType = $defaultType;
$nodes = ProductGroup::ancestorsAndSelf($parentId);
$nodes = $nodes->toArray();
rsort($nodes);
foreach ($nodes as $node) {
if ($node['type'] !== null) {
return $node['type'];
}
}
return $returnType;
}
public function treeNodeRename(Request $request, $id)
{
$rules = [];
// \Log::channel('chromePHP')->info(basename(__FILE__).':'.__LINE__,$request->all());
if (substr($id, 0, 4) == 'tmp_') {
$rules['name'] = Rule::unique('product_groups', 'name');
$ProductGroup = new ProductGroup;
$ProductGroup->canSee = true;
$ProductGroup->status = DbStatusFieldEnum::active;
} else {
$ProductGroup = ProductGroup::findOrFail($id);
$rules['name'] = Rule::unique('product_groups', 'name')->ignore($ProductGroup->name, 'name');
}
$validated = \Validator::make($request->all(), $rules);
\Log::channel('chromePHP')->info(basename(__FILE__).':'.__LINE__);
if ($validated->fails()) {
$error = Error::make();
$error->setStatus(500);
$error->setDetail('Már létezik "'.$request->input('name').'"');
$error->setTitle('Nem lehet átnevezni');
return $error;
}
$ProductGroup->name = $request->input('name');
if (! $ProductGroup->id) {
\Log::channel('chromePHP')->debug('ujat kell letrehozni');
$ProductGroup = $this->nodeAdd($ProductGroup->toArray(), $request->get('parents')[0]);
} else {
$ProductGroup->save();
}
return response()->json(['id' => $ProductGroup->id]);
}
public function treeNodeMove(Request $request, $id): JsonResponse
{
$ProductGroup = ProductGroup::findOrFail($id);
$ProductGroupParent = ProductGroup::findOrFail($request->get('parent'));
// moveNode($position)
$ProductGroup->appendToNode($ProductGroupParent)->save();
return response()->json(['id' => $ProductGroup->id]);
}
public function treeNodeDelete(Request $request, $id): JsonResponse
{
$ProductGroup = ProductGroup::findOrFail($id);
$ProductGroup->delete();
return response()->json(['id' => $ProductGroup->id]);
}
public function treeNodeGetContent($id): Response|JsonResponse
{
$item = ProductGroup::find($id);
return response($item->name);
}
protected function getTreeRootChildren()
{
$root = ProductGroup::find(1);
$nodes = ProductGroup::where('id', 1)->withDepth()->get();
return $nodes;
}
protected function convertToTreeArray(Collection $nodes)
{
$treeArray = [];
foreach ($nodes as $node) {
$tmpNodeArray = [
'text' => $node->name,
'id' => $node->id,
];
if ($node->depth < 3) {
$tmpNodeArray['icon'] = 'jstree-folder';
$tmpNodeArray['type'] = 'folder';
if (ProductGroup::descendantsOf($node)->count() > 0) {
$tmpNodeArray['children'] = true;
}
} else {
$tmpNodeArray['icon'] = 'jstree-file';
$tmpNodeArray['type'] = 'file';
}
if (isset($node->depth)) {
$tmpNodeArray['depth'] = $node->depth;
}
$treeArray[] = $tmpNodeArray;
}
return $treeArray;
}
public function treeNodeGet(Request $request): Response|JsonResponse|array
{
if (is_numeric($request->input('id'))) {
$nodeDepth = ProductGroup::where('id', $request->input('id'))->withDepth()->first()->depth;
$nodes = ProductGroup::find($request->input('id'))->descendants()->withDepth()->having('depth', '=', $nodeDepth + 1)->get();
return $this->convertToTreeArray($nodes);
} else {
return $this->convertToTreeArray($this->getTreeRootChildren());
}
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show(ProductGroup $productGroup)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function edit(ProductGroup $productGroup)
{
//
}
/**
* Update the specified resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function update(Request $request, ProductGroup $productGroup)
{
//
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\Response
*/
public function destroy(ProductGroup $productGroup)
{
//
}
}

View File

@ -0,0 +1,267 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\Supplier;
use App\Repositories\ProfitCenterRepository;
use App\Services\ProfitCenterService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class ProfitCenterController extends Controller
{
protected ProfitCenterService $service;
private bool $testMode = false;
public function __construct(ProfitCenterService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View|JsonResponse
{
if (\request()->input('t') == 1) {
$options = [
'validate_all' => true,
'return_type' => 'both',
];
[$validate, $allValidations] = auth()->user()->ability(
['root', 'owner'],
['create-post', 'edit-user'],
$options
);
dd($allValidations);
dd(auth()->user()->hasRole('admin'));
return response()->json(['debug' => 'test']);
}
$retData = [];
// $retData['testMode']=($this->testMode)?'true':'false';
$retData['testMode'] = $this->testMode;
$retData['init'] = (bool) \request()->get('init', true);
return view('admin.profitCenter.index')->with($retData);
}
/**
* Show the form for creating a new resource.
*/
public function create(): View
{
$retData = [];
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['supplier'] = Supplier::orderBy('name', 'asc')->get()->toArray();
return view('admin.profitCenter.create')->with($retData);
return view('admin.profitCenter.create')->with([
'testMode' => ($this->testMode) ? 'true' : 'false',
]);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
$data = $this->getSupplierDataFromRequest($request);
$id = $this->service->add($data);
$ret['success'] = true;
$ret['data'] = $data;
$ret['id'] = $id;
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['error'] = $this->service->getError();
}
return \response()->json($ret);
}
/**
* Display the specified resource.
*/
public function show(int $ProfitCenterId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $ProfitCenterId): View|JsonResponse|bool
{
$this->service->setRelation('address', 'contact', 'users', 'supplier');
// if(!$itemData=$this->service->getWithRelations($ProfitCenterId)){
if (! $itemData = $this->service->getWithAllRelations($ProfitCenterId)) {
return false;
}
$retData = [];
$retData['itemData'] = $itemData;
if (isset($retData['itemData']['users'][0])) {
$profitCenterUserData = $retData['itemData']['users'][0];
$retData['itemData']['userId'] = $profitCenterUserData['id'];
$retData['itemData']['userName'] = $profitCenterUserData['name'];
} else {
$profitCenterUserData = ['id' => '', 'name' => ''];
}
unset($retData['itemData']['users']);
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['init'] = false;
$retData['supplier'] = Supplier::orderBy('name', 'asc')->get()->toArray();
debug($retData);
if (\request()->input('t') == 1) {
echo '<pre>';
var_dump($itemData);
return response()->json($itemData);
}
return view('admin.profitCenter.create')->with($retData);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $ProfitCenterId): Response|JsonResponse
{
$data = $this->getSupplierDataFromRequest($request);
debug($data);
$this->service->update($ProfitCenterId, $data);
$ret['success'] = true;
$ret['data'] = $data;
$ret['id'] = $ProfitCenterId;
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['error'] = $this->service->getError();
}
return \response()->json($ret);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $id): Response|JsonResponse
{
$repository = new ProfitCenterService(new ProfitCenterRepository);
if ($repository->delete($id)) {
$ret = ['success' => true];
} else {
$ret = ['success' => false];
}
return \response()->json($ret);
}
public function getDataTableContent(): JsonResponse
{
$repository = new ProfitCenterRepository;
$ret = ['data' => []];
$items = $repository->getQueryWithRelations()->orderBy('name')->get()->toArray();
foreach ($items as $item) {
$data['id'] = $item['id'];
$data['name'] = $item['name'];
$data['hooreycaId'] = $item['hooreycaId'];
$data['nameId'] = $item['nameId'];
$data['created_at'] = formatterDateTime($item['created_at']);
$ret['data'][] = $data;
}
return \response()->json($ret);
}
private function getSupplierDataFromRequest(Request $request)
{
// dd($request->route('supplier'));
/** @var array $data */
$data = [];
$acceptedData = [
'name',
'hooreycaId',
'nameId',
'email',
'postCode',
'city',
'street',
'phone',
'mobil',
'userName',
'userPassword',
'userRePassword',
'note',
'canSee',
'addressEqual',
'multiAddress',
'user',
];
foreach ($acceptedData as $num => $key) {
$data[$key] = $request->get($key);
}
$data['status'] = DbStatusFieldEnum::active;
if ($contactId = $request->get('contactId')) {
$data['contactId'] = $contactId;
} else {
$data['contactId'] = [];
}
if ($addressId = $request->get('addressId')) {
$data['addressId'] = $addressId;
} else {
$data['addressId'] = [];
}
$hasDefaultValueNotNull = [
'addressEqual',
'multiAddress',
'canSee',
];
foreach ($hasDefaultValueNotNull as $key) {
if (array_key_exists($key, $data) && is_null($data[$key])) {
unset($data[$key]);
}
}
$data['supplierId'] = [];
if ($supplierNames = $request->get('supplier')) {
$data['supplierId'] = \App\Models\Supplier::whereIn('name', (array) $supplierNames)->get()->pluck('id')->toArray();
}
if ($request->file('logoFile')) {
$disk = 'image';
$diskPath = \Storage::disk($disk)->getAdapter()->getPathPrefix();
$pathPrefix = str_replace(public_path(), '', $diskPath);
$pathPrefix = ltrim($pathPrefix, DIRECTORY_SEPARATOR);
$pathPrefix = str_replace('\\', '/', $pathPrefix);
// ha van mar akkor torolni kell!!!
if ($request->route('profitCenter')) {
$profitCenter = \App\Models\ProfitCenter::with('attachment')->find($request->route('profitcenter'));
if ($profitCenter->logoFile) {
$file = 'images/supplierLogo/B9f65IlF62fEoNfLPmSFen8D8A2E0HUCHJcqHYDw.jpg';
// var_dump(str_replace($pathPrefix,'',$file));
\Storage::disk($disk)->delete(str_replace($pathPrefix, '', $profitCenter->logoFile));
}
}
$path = $request->file('logoFile')->store('/profitCenter', $disk);
$data['logoFile'] = $pathPrefix.$path;
}
return $data;
}
}

View File

@ -0,0 +1,187 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Producer;
use App\Models\Product;
use App\Models\ProductGroup;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Services\StatisticsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class StatisticsController extends Controller
{
private StatisticsService $Service;
public function __construct(StatisticsService $Service)
{
// parent::__construct();
$this->Service = $Service;
}
/**
* Display a listing of the resource.
*/
public function index(): View
{
$suppliers = Supplier::orderBy('name')->get(['id', 'name'])->toArray();
$profitCenters = ProfitCenter::orderBy('name')->get(['id', 'name'])->toArray();
$productGroups = ProductGroup::orderBy('name')->get(['id', 'name'])->toArray();
$producer = Producer::orderBy('name')->get(['id', 'name'])->toArray();
DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
$hooreycaNames = Product::orderBy('buyerProductName')->where('buyerProductName', '!=', '')->groupBy('buyerProductName')->get(['id', 'buyerProductName as name'])->toArray();
DB::statement("SET sql_mode=(SELECT CONCAT(@@sql_mode, ',ONLY_FULL_GROUP_BY'));");
// dd($hooreycaNames);
// dd(json_encode($service->getAvailableFilters()));
return view('admin.statistics.index')->with(
[
'suppliers' => $suppliers,
'profitCenters' => $profitCenters,
'productGroups' => $productGroups,
'producer' => $producer,
'hooreycaNames' => $hooreycaNames,
'formUUID' => \Str::uuid(),
'availableFilters' => json_encode($this->Service->getAvailableFilters()),
]
);
}
/**
* Display the specified resource.
*/
public function show(string $viewType): Response|JsonResponse
{
return response($viewType);
}
/**
* Display the specified resource.
*
* @param string $viewType
*/
public function getStat(Request $request): Response|JsonResponse
{
$type = ucfirst($request->input('type'));
$functionName = 'getStatistics'.ucfirst($request->input('type'));
$acceptedFieldsArrays = $this->Service->getAvailableFilters($type);
foreach ($acceptedFieldsArrays as $acceptedField) {
if ($request->get($acceptedField)) {
if (is_array($request->get($acceptedField))) {
$this->Service->addStatisticsParameter($acceptedField, $request->get($acceptedField));
} else {
$this->Service->setStatisticsParameters($acceptedField, $request->get($acceptedField));
}
}
}
if (! method_exists($this->Service, $functionName)) {
return \response()->json([], 500);
}
$ret = $this->Service->$functionName();
return \response()->json(['function' => $functionName, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
/*
*
$functionName = 'getStat' . ucfirst($request->input('type'));
if (method_exists($this, $functionName)) {
return call_user_func_array(array($this, $functionName),[$request]);
}
return \response()->json([], 400);
dd($request);
return $viewType;
*/
}
private function getStatOrderFrequency(Request $request): JsonResponse
{
$acceptedFieldsArrays = $this->Service->getAvailableFilters('OrderFrequency');
foreach ($acceptedFieldsArrays as $acceptedField) {
if ($request->get($acceptedField)) {
if (is_array($request->get($acceptedField))) {
$this->Service->addStatisticsParameter($acceptedField, $request->get($acceptedField));
} else {
$this->Service->setStatisticsParameters($acceptedField, $request->get($acceptedField));
}
}
}
/*
$acceptedFieldsArrays=['suppliers','profitCenters','suppliers','productGroups','products'];
foreach ($acceptedFieldsArrays as $acceptedField) {
if(is_array($request->get($acceptedField))){
$this->Service->addStatisticsParameter($acceptedField,$request->get($acceptedField));
}
}
$acceptedFields=['dateFrom','dateTo'];
foreach ($acceptedFields as $acceptedField) {
if($request->get($acceptedField)){
$this->Service->setStatisticsParameters($acceptedField,$request->get($acceptedField));
}
}
*/
$ret = $this->Service->getStatOrderFrequencyStatistics();
return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
}
private function getStatProductAmount(Request $request): JsonResponse
{
$ret = [];
return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
}
private function getStatPriceChange(Request $request): JsonResponse
{
$ret = [];
return \response()->json(['function' => __FUNCTION__, 'parameters' => $this->Service->getStatisticsParameters(), 'ret' => $ret, 'success' => true], 200);
}
public function getProductSearch(Request $request): JsonResponse
{
$page = $request->get('page');
$resultCount = 25;
$offset = ($page - 1) * $resultCount;
$items = Product::with('supplier:id,name')->where('name', 'LIKE', '%'.$request->get('term').'%')->orWhere('supplierProductNumber', 'LIKE', '%'.$request->get('term').'%');
$count = $items->count();
// $items=$items->orderBy('name')->skip($offset)->take($resultCount)->get(['supplier_id','id',DB::raw('name as text')]);
$items = $items->orderBy('name')->skip($offset)->take($resultCount)->get(['supplier_id', 'id', 'name'])->toArray();
// dd($items);
foreach ($items as $k => $item) {
$items[$k]['text'] = $item['name'];
if ($item['supplier']) {
$items[$k]['text'] .= ' ['.$item['id'].'/'.$item['supplier']['name'].']';
}
$items[$k]['id'] = $item['name'];
}
$endCount = $offset + $resultCount;
$morePages = $endCount < $count;
$results = [
'results' => $items,
'pagination' => [
'more' => $morePages,
],
];
return response()->json($results);
dd($count, $offset, $endCount, $morePages, $items->toArray());
dd($request->all());
}
}

View File

@ -0,0 +1,375 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\DbStatusFieldEnum;
use App\Http\Controllers\Controller;
use App\Models\ProfitCenter;
use App\Models\Service;
use App\Models\Supplier;
use App\Services\SupplierService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class SupplierController extends Controller
{
protected SupplierService $service;
private bool $testMode = false;
public function __construct(SupplierService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View|JsonResponse
{
// test
if (\request()->input('t') == 1) {
return response()->json(['debug' => 'test']);
}
$retData = [];
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['init'] = (bool) \request()->get('init', true);
return view('admin.supplier.index')->with($retData);
}
/**
* Show the form for creating a new resource.
*/
public function create(): View
{
$ProductGroup = new \App\Models\ProductGroup;
$productGroupArray = $ProductGroup->allWithParents(2);
$retData = [];
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['productGroup'] = $ProductGroup->allWithParents(2);
$retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();
$retData['service'] = Service::select('name')->orderBy('name')->get()->toArray();
return view('admin.supplier.create')->with($retData);
return view('admin.supplier.create')->with([
'productGroup' => $productGroupArray,
'testMode' => ($this->testMode) ? 'true' : 'false',
]);
}
private function getSupplierDataFromRequest(Request $request)
{
// dd($request->route('supplier'));
/** @var array $data */
$data = [];
$acceptedData = [
1 => 'name',
2 => 'hooreycaId',
3 => 'nameId',
4 => 'orderEmail',
5 => 'orderEmail2',
6 => 'address',
7 => 'mailingAddress',
8 => 'phone',
9 => 'fax',
10 => 'customerServicePhone',
11 => 'note',
12 => 'emailAttachmentType',
13 => 'canSee',
14 => 'canSeeInOrder',
// 15 => 'hooreycaDataActive',
15 => 'openHours',
16 => 'ordersDeadline',
17 => 'minOrderValue',
];
foreach ($acceptedData as $num => $key) {
$data[$key] = $request->get($key);
}
$data['status'] = DbStatusFieldEnum::active;
if ($contactId = $request->get('contactId')) {
$data['contactId'] = $contactId;
} else {
$data['contactId'] = [];
}
$data['productGroupId'] = [];
if ($productGroupNames = $request->get('productGroup')) {
// @todo: atszervezni a servicebe, vagy a repositoryba
// dd($productGroupNames);
$data['productGroupId'] = \App\Models\ProductGroup::whereIn('name', (array) $productGroupNames)->get()->pluck('id')->toArray();
}
$data['serviceId'] = [];
if ($ServiceNames = $request->get('supplierService')) {
// @todo: atszervezni a servicebe, vagy a repositoryba
$Services = \App\Models\Service::select(['name', 'id'])->whereIn('name', (array) $ServiceNames)->get()->keyBy('name')->toArray();
foreach ($ServiceNames as $serviceName) {
if (! isset($Services[$serviceName])) {
$newService = \App\Models\Service::create(['name' => $serviceName]);
$data['serviceId'][] = $newService->id;
} else {
$data['serviceId'][] = $Services[$serviceName]['id'];
}
}
}
$data['profitCenterId'] = [];
if ($profitCenterNames = $request->get('profitCenter')) {
$data['profitCenterId'] = \App\Models\ProfitCenter::whereIn('name', (array) $profitCenterNames)->get()->pluck('id')->toArray();
}
if ($request->file('logoFile')) {
$disk = 'image';
$diskPath = \Storage::disk($disk)->getAdapter()->getPathPrefix();
$pathPrefix = str_replace(public_path(), '', $diskPath);
$pathPrefix = ltrim($pathPrefix, DIRECTORY_SEPARATOR);
$pathPrefix = str_replace('\\', '/', $pathPrefix);
// ha van mar akkor torolni kell!!!
if ($request->route('supplier')) {
$supplier = Supplier::with('attachment')->find($request->route('supplier'));
if ($supplier->logoFile) {
$file = 'images/supplierLogo/B9f65IlF62fEoNfLPmSFen8D8A2E0HUCHJcqHYDw.jpg';
// var_dump(str_replace($pathPrefix,'',$file));
\Storage::disk($disk)->delete(str_replace($pathPrefix, '', $supplier->logoFile));
}
}
$path = $request->file('logoFile')->store('/supplierLogo', $disk);
$data['logoFile'] = $pathPrefix.$path;
}
return $data;
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
$data = $this->getSupplierDataFromRequest($request);
// $data['canSeeInOrder']=1;
$id = $this->service->add($data);
$ret = [];
$ret['success'] = true;
$ret['id'] = $id;
$ret['data'] = $data;
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['error'] = $this->service->getError();
}
return \response()->json($ret);
}
/**
* Display the specified resource.
*/
public function show(int $SupplierId): Response|JsonResponse
{
return response('Yes show');
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $SupplierId): View|JsonResponse|bool
{
if (! $supplierData = $this->service->getWithAllRelations($SupplierId)) {
return false;
}
$retData = [];
$retData['supplierData'] = $supplierData;
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['init'] = false;
$ProductGroup = new \App\Models\ProductGroup;
$productGroupArray = $ProductGroup->allWithParents(2);
$retData['productGroup'] = $productGroupArray;
$retData['service'] = Service::select('name')->orderBy('name')->get()->toArray();
$retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();
if (\request()->input('t') == 1) {
echo '<pre>';
var_dump($supplierData);
var_dump($retData);
return response()->json($supplierData);
}
return view('admin.supplier.create')->with($retData);
}
/**
* Update the specified resource in storage.
*
* @param int $SupplierId
*/
public function update(Request $request, int $supplierId): JsonResponse
{
/*
$ret['success']=false;
return \response()->json($ret);
*/
// $this->fileManagement($request,$SupplierId);
// debug($request->get('profitCenter'));
$data = $this->getSupplierDataFromRequest($request);
$this->service->update($supplierId, $data);
$ret['success'] = true;
$ret['data'] = $data;
$ret['id'] = $supplierId;
if ($this->service->hasError()) {
$ret['success'] = false;
$ret['error'] = $this->service->getError();
}
return \response()->json($ret);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $SupplierId): Response|JsonResponse
{
if ($this->service->delete($SupplierId)) {
$ret = ['success' => true];
} else {
$ret = ['success' => false];
}
return \response()->json($ret);
}
public function getDataTableContent(): JsonResponse
{
$repository = new \App\Repositories\SupplierRepository;
$ret = ['data' => []];
$items = $repository->getQueryWithRelations()->orderBy('name')->get()->toArray();
foreach ($items as $item) {
$data['id'] = $item['id'];
$data['name'] = $item['name'];
$data['hooreycaId'] = $item['hooreycaId'];
$data['nameId'] = $item['nameId'];
$data['created_at'] = formatterDateTime($item['created_at']);
$ret['data'][] = $data;
}
return \response()->json($ret);
var_dump($ret);
dd($ret);
dd($repository->all()->toArray());
return \response()->file('exapmle2.json');
}
private function fileManagement($request, $supplierId)
{
if ($file = $request->file('logoFile')) {
// ha van mar akkor torolni kell!!!
$supplier = Supplier::with('attachment')->find($supplierId);
if (count($supplier->attachment) > 0) {
foreach ($supplier->attachment as $attached) {
\App\Models\Attachment::find($attached->id)->delete();
}
}
$attachment = new \App\Models\Attachment;
$attachment->addFile($file);
$attachment->attachable()->associate($supplier);
$attachment->save();
}
}
private function getResponseStatusFromData($retData)
{
$status = 500;
if (isset($retData['success']) && $retData['success'] === true) {
$status = 200;
}
if (isset($retData['statusCode']) && is_numeric($retData['statusCode'])) {
$status = $retData['statusCode'];
}
return $status;
}
public function attachFile(int $supplierId): JsonResponse
{
$file = \request()->file('attacheFile');
$ret = ['data' => [], 'success' => false];
if ($file) {
$ret['data']['file'] = var_export(\request()->file('attacheFile'), true);
if ($supplier = Supplier::find($supplierId)) {
$attachment = new \App\Models\Attachment;
$attachment->addFile($file);
$attachment->attachable()->associate($supplier);
$attachment->save();
$ret['data']['attachment'] = $attachment->toArray();
$ret['success'] = true;
}
}
if ($ret['success'] === true) {
$supplierData = $this->service->getWithAllRelations($supplierId);
$emailData = [
'supplierName' => $supplierData['name'],
'documentName' => $file->getClientOriginalName(),
];
if (is_array($supplierData['profit_center'])) {
$toEmailAddress = [];
foreach ($supplierData['profit_center'] as $profitCenter) {
if ($profitCenter['email'] && $profitCenter['email'] != 'NULL') {
$toEmailAddress[] = $profitCenter['email'];
}
}
}
Log::info('supplierNewFile prepared'.var_export($toEmailAddress,true));
Log::info('supplierNewFile prepared'.var_export($emailData,true));
\Mail::send('email.supplierNewFile', [
'emailData' => $emailData,
], function ($m) use ($toEmailAddress) {
$subject = 'Értesítés dokumentum változásról';
$m->subject($subject);
if (config('app.stage', 'DEV') == 'PROD') {
$m->to($toEmailAddress);
} else {
$m->to($toEmailAddress);
$m->to(config('mail.MailToOrderAddress'));
}
if (config('mail.MailToOrderAddress') != 'city99@e98.hu') {
$m->bcc('city99@e98.hu');
}
});
}
return \response()->json($ret, $this->getResponseStatusFromData($ret));
}
public function detachFile(int $supplierId): JsonResponse
{
$ret = ['data' => [], 'success' => false];
if ($supplier = Supplier::with('attachment')->find($supplierId)) {
if ($attachment = $supplier->attachment->where('id', \request()->get('attachemntId'))->first()) {
if ($attachment->delete()) {
$ret['data']['attachment'] = $attachment->toArray();
$ret['success'] = true;
}
}
}
return \response()->json($ret, $this->getResponseStatusFromData($ret));
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\systemParameters;
use Illuminate\Http\Request;
use Illuminate\View\View;
class SystemParametersController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
return view('admin.systemParameters.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show(systemParameters $systemParameters)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function edit(systemParameters $systemParameters)
{
//
}
/**
* Update the specified resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function update(Request $request, systemParameters $systemParameters)
{
//
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\Response
*/
public function destroy(systemParameters $systemParameters)
{
//
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers;
use App\Services\ContactService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class ContactController extends Controller
{
protected $service;
public function __construct(ContactService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return response()->noContent();
}
/**
* Display the specified resource.
*/
public function show(int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $ContactId): Response|JsonResponse
{
return response()->noContent();
}
}

View File

@ -0,0 +1,5 @@
<?php
namespace App\Http\Controllers;
abstract class Controller {}

View File

@ -0,0 +1,95 @@
<?php
namespace App\Http\Controllers;
use App\Enums\DbStatusFieldEnum;
use App\Models\systemParameters;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Validator;
class DashboardController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(): View
{
$customContent = systemParameters::where('name', 'dashboardCustomContent')->firstOrCreate([
'name' => 'dashboardCustomContent',
'name_display' => 'Dashboard Custom Content',
'data_type' => 'text',
'status' => DbStatusFieldEnum::active(),
]
)->select(['name', 'id', 'stored_data']);
// dd($customContent->toArray());
// $customContentData=$customContent->select(['name','id','stored_data'])->get()->toArray();
$customContentData = $customContent->first()->toArray();
return view('dashboard')->with(['customContentData' => $customContentData]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show(int $id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function edit(int $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $id): JsonResponse
{
$validated = Validator::make($request->all(), [
'stored_data' => 'string|nullable|max:65000',
]);
$newItem = systemParameters::findOrFail($id);
$newItem->fill($validated->validated());
$newItem->save();
return response()->json($newItem->toArray());
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\Response
*/
public function destroy(int $id)
{
//
}
}

View File

@ -0,0 +1,51 @@
<?php namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/**
* Handle an authentication attempt.
*
* @return \Illuminate\Http\Response
*/
public function authenticate(Request $request)
{
$credentials = $request->validate([
'name' => ['required'],
'password' => ['required'],
]);
/* var_dump($credentials);
var_dump(Auth::attempt(
['name'=>$credentials['name'],
'password'=>$credentials['password']]
));
return ;*/
if (Auth::attempt(
['name' => $credentials['name'],
'password' => $credentials['password'], ]
)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->withErrors([
'email' => 'Sikertelen Bejelentkezés',
]);
}
public function logout(Request $request): RedirectResponse
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@ -0,0 +1,227 @@
<?php
namespace App\Http\Controllers;
use App\Enums\DbStatusFieldEnum;
use App\Enums\OrderFlag;
use App\Enums\OrderStatusEnum;
use App\Enums\OrderType;
use App\Models\Order;
use App\Models\OrderArchive;
use App\Models\ProfitCenter;
use App\Models\Supplier;
use App\Services\OrderService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class OrderArchiveController extends Controller
{
protected OrderService $service;
protected bool $testMode = false;
public function __construct(OrderService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View
{
// test mode
if (\request()->input('t') == 1) {
dd(auth()->user()->roles->toArray(), auth()->user()->allPermissions(), auth()->user()->whereDoesntHaveRole()->get()
);
dd(auth()->user()->roles->toArray());
dd(auth()->user()->allPermissions());
dd(auth()->user()->whereDoesntHaveRole()->get());
}
$dataView = ['testMode' => $this->testMode];
if (auth()->user()->hasRole(['root', 'admin', 'developer'])) {
$dataView['profitCenters'] = ProfitCenter::whereIn('status', [DbStatusFieldEnum::active, DbStatusFieldEnum::archive])->select('name', 'id')->orderBy('name')->get()->toArray();
$dataView['suppliers'] = Supplier::whereIn('status', [DbStatusFieldEnum::active, DbStatusFieldEnum::archive])->select('name', 'id')->orderBy('name')->get()->toArray();
}
return view('modules.orderArchive.index')->with($dataView);
}
/**
* Show the form for creating a new resource.
*/
public function create(Request $request): Response|JsonResponse
{
return \response()->json([], 400);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return \response()->json([], 400);
}
/**
* Display the specified resource.
*/
public function show(int $id): View|Response|JsonResponse
{
$showData = [];
$showData = OrderArchive::with('items', 'supplier', 'profitCenter')->find($id)->toArray();
debug($showData);
return view('modules.orderArchive.show')->with($showData);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $OrderId): Response|JsonResponse|RedirectResponse
{
// letre kell hozni egy újat ordert
$OrderArchive = OrderArchive::find($OrderId);
$Order = new Order;
$Order->orderStatus = OrderStatusEnum::productSelect;
$copyFieldPointer = [
'profit_center_id',
'supplier_id',
'contactName',
'note',
'orderType',
'parent_id',
'deliveryDate',
'deliveryAddressId',
'deliveryAddressName',
'deliveryAddress',
'customNotificationEmail',
'productSelected',
'productComment',
'sumPrice',
];
foreach ($copyFieldPointer as $pointer) {
$Order->$pointer = $OrderArchive->$pointer;
}
$Order->orderFlag = OrderFlag::modifier;
$Order->rel_id = $OrderArchive->id;
$OrderOriginal = Order::where('humanId', $OrderArchive->humanId)->first();
if ($OrderOriginal) {
$Order->parent_id = $OrderOriginal->parent_id;
$Order->note = $OrderOriginal->note.' '.$OrderOriginal->humanId.' számú megrendelés módosítása.';
}
$Order->save();
return \response()->redirectTo(route('order.edit', $Order->id));
dd($Order->toArray(), $OrderArchive->toArray(), $OrderOriginal->toArray());
}
public function update(Request $request, int $orderId): JsonResponse
{
return \response()->json([], 400);
}
public function destroy(int $OrderId): Response|JsonResponse
{
return response()->noContent();
}
private function orderCanEditable($orderData)
{
if (! auth()->user()->hasRole('profit-center')) {
return false;
}
$profitCenterId = auth()->user()->profitCenters->first()->id;
if ($orderData['profit_center_id'] !== $profitCenterId) {
return false;
}
if ($orderData['orderType'] !== OrderType::daily) {
return false;
}
// print"<pre>";
// var_dump($orderData);
if (in_array($orderData['orderFlag'], [OrderFlag::storno, OrderFlag::modified])) {
return false;
}
if ($orderData['deliveryDate'] <= Carbon::tomorrow()->format('Y-m-d')) {
return false;
}
return true;
}
public function getDataTableContent(): JsonResponse
{
$groupId = null;
$searchStr = null;
$OrderArchive = OrderArchive::with('attachment')->select('id', 'profit_center_id', 'supplier_name', 'deliveryAddressName', 'deliveryAddress', 'deliveryDate', 'humanId', 'confirmed', 'contactName', 'sentTime', 'orderType', 'parent_id', 'orderFlag', 'rel_id');
if (auth()->user()->hasRole('profit-center')) {
$profitCenterId = auth()->user()->profitCenters->first()->id;
$OrderArchive = $OrderArchive->where('profit_center_id', $profitCenterId);
} elseif (auth()->user()->hasRole(['root', 'admin', 'developer'])) {
debug('high permission');
$OrderArchive->with('profitCenter');
if (\request()->get('advanceSearchParameter')) {
$advanceSearchParameter = \request()->get('advanceSearchParameter');
if (isset($advanceSearchParameter['profitCenterId']) && is_int($advanceSearchParameter['profitCenterId'] * 1)) {
$OrderArchive->where('profit_center_id', $advanceSearchParameter['profitCenterId']);
}
if (isset($advanceSearchParameter['supplierId']) && is_int($advanceSearchParameter['supplierId'] * 1)) {
$OrderArchive->where('supplier_id', $advanceSearchParameter['supplierId']);
}
}
} else {
return \response()->json(['data' => []]);
}
if (\request()->get('advanceSearchParameter')) {
debug(\request()->get('advanceSearchParameter'));
$advanceSearchParameter = \request()->get('advanceSearchParameter');
if (isset($advanceSearchParameter['deliveryDateFrom']) && strlen($advanceSearchParameter['deliveryDateFrom']) == 10) {
$OrderArchive->where('deliveryDate', '>=', $advanceSearchParameter['deliveryDateFrom']);
}
if (isset($advanceSearchParameter['deliveryDateTo']) && strlen($advanceSearchParameter['deliveryDateTo']) == 10) {
$OrderArchive->where('deliveryDate', '<=', $advanceSearchParameter['deliveryDateTo']);
}
}
$OrderArchive->orderBy('sentTime', 'desc');
$OrderArchive->limit(3000);
// $OrderArchive->limit(100);
$OrderArchive->where('orderType', '!=', 'weekly');
$retData = $OrderArchive->get()->toArray();
// $retData=$OrderArchive->limit(10)->get()->toArray();
$retData = array_map(function ($item) {
$item['fileUrl'] = false;
$item['fileName'] = false;
if ($item['attachment']) {
$item['fileUrl'] = $item['attachment']['PublicUrl'].$item['attachment']['filename'];
$item['fileName'] = $item['attachment']['original_filename'];
}
if (! $item['deliveryAddressName'] || strlen($item['deliveryAddressName']) < 2) {
$item['deliveryAddressName'] = $item['deliveryAddress'];
}
$item['canEditable'] = $this->orderCanEditable($item);
// dd($item);
return $item;
}, $retData);
debug(count($retData));
debug($retData);
return \response()->json(['data' => $retData]);
/**clean up code*/
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers;
use App\Services\PackService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PackController extends Controller
{
protected $service;
public function __construct(PackService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return response()->noContent();
}
/**
* Display the specified resource.
*/
public function show(int $PackId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $PackId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $PackId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $PackId): Response|JsonResponse
{
return response()->noContent();
}
}

View File

@ -0,0 +1,156 @@
<?php
namespace App\Http\Controllers;
use App\Enums\DbStatusFieldEnum;
use App\Models\PriceList;
use App\Models\ProfitCenter;
use App\Services\PriceListService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class PriceListController extends Controller
{
protected $service;
public function __construct(PriceListService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View|Response|JsonResponse
{
if (\request()->input('t') == 1) {
// ... (keep the dd calls if you want, but for now let's just make it valid)
}
return view('modules.priceList.index');
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return response()->noContent();
}
/**
* Display the specified resource.
*/
public function show(int $priceListId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $PriceListId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $PriceListId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $PriceListId): Response|JsonResponse
{
return response()->noContent();
}
public function getDataTableContent(): JsonResponse
{
$ret = ['data' => []];
$accessSupplierId = ProfitCenter::with('suppliers')->find(auth()->user()->profitCenters->first()->id)->suppliers->pluck('id')->toArray();
$lastPriceList = [];
foreach ($accessSupplierId as $supplierId) {
if ($PriceList = PriceList::where('supplier_id', $supplierId)
->where('status', DbStatusFieldEnum::active)
->where('available', '<=', Carbon::now()->toDateTimeString())
->orderBy('available', 'desc')
->first()) {
$lastPriceList[] = $PriceList->toArray()['id'];
}
}
$s = PriceList::with('supplier', 'attachment')
->where('status', DbStatusFieldEnum::active)
->whereIn('supplier_id', $accessSupplierId)
->where(function ($query) use ($lastPriceList) {
$query->where('available', '>=', Carbon::now()->toDateTimeString());
$query->orWhereIn('id', $lastPriceList);
})
->orderBy('available', 'desc');
$items = $s->get()->toArray();
foreach ($items as $item) {
$data['id'] = $item['id'];
$data['supplierName'] = $item['supplier']['name'];
$data['available'] = formatterDate($item['available']);
$data['created_at'] = formatterDateTime($item['created_at']);
$data['note'] = $item['note'];
$data['fileUrl'] = false;
$data['fileName'] = false;
if ($item['attachment']) {
$data['fileUrl'] = $item['attachment']['PublicUrl'].$item['attachment']['filename'];
$data['fileName'] = $item['attachment']['original_filename'];
}
$ret['data'][] = $data;
}
return \response()->json($ret);
$ret = ['data' => []];
if (! $userSuppliers = ProfitCenter::find(auth()->user()->profitCenters()->first()->id)->
suppliers()->pluck('suppliers.id')) {
return \response()->json($ret);
}
$userSupplierIds = $userSuppliers->toArray();
$repository = new \App\Repositories\PriceListRepository;
$repository->setRelation(['supplier', 'attachment']);
$items = $repository->getQueryWithRelations()->get()->toArray();
foreach ($items as $item) {
if (in_array($item['supplier_id'], $userSupplierIds)) {
$data['id'] = $item['id'];
$data['supplierName'] = $item['supplier']['name'];
$data['available'] = formatterDate($item['available']);
$data['created_at'] = formatterDateTime($item['created_at']);
$data['fileUrl'] = false;
$data['fileName'] = false;
if ($item['attachment']) {
$data['fileUrl'] = $item['attachment']['PublicUrl'].$item['attachment']['filename'];
$data['fileName'] = $item['attachment']['original_filename'];
}
$ret['data'][] = $data;
}
}
return \response()->json($ret);
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace App\Http\Controllers;
use App\Services\ProducerService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class ProducerController extends Controller
{
protected $service;
public function __construct(ProducerService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return response()->noContent();
}
/**
* Display the specified resource.
*/
public function show(int $ProducerId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $ProducerId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $ProducerId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $ProducerId): Response|JsonResponse
{
return response()->noContent();
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers;
use App\Models\ProfitCenter;
class ProductController extends Controller
{
//
public function toggleFavorites($productId)
{
// $productId=878;
$profitCenterId = auth()->user()->profitCenters()->first()->id;
debug([$productId, $profitCenterId]);
$ProfitCenter = ProfitCenter::find($profitCenterId);
$favorites = $ProfitCenter->favorites()->where('product_id', '=', $productId)->get()->pluck('id')->toArray();
if (! in_array($productId, $favorites)) {
$currentStatus = false;
debug('berakjuk');
$ProfitCenter->favorites()->attach($productId);
$currentStatus = true;
} else {
debug('kivesszuk');
$currentStatus = true;
$ProfitCenter->favorites()->detach($productId);
$currentStatus = false;
}
return \response()->json([
'success' => true,
'status' => $currentStatus,
]);
}
}

View File

@ -0,0 +1,179 @@
<?php
namespace App\Http\Controllers;
use App\Models\PriceList;
use App\Models\ProfitCenter;
use App\Repositories\SupplierRepository;
use App\Services\SupplierService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class SupplierController extends Controller
{
protected SupplierService $service;
public function __construct(SupplierService $service)
{
$this->service = $service;
}
/**
* Display a listing of the resource.
*/
public function index(): View
{
return view('modules.supplier.index');
}
/**
* Show the form for creating a new resource.
*/
public function create(): Response|JsonResponse
{
return response()->noContent();
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request): Response|JsonResponse
{
return response()->noContent();
}
/**
* Display the specified resource.
*/
public function show(int $SupplierId): View|Response|JsonResponse
{
if (\request()->get('t')) {
$supplierData = $this->service->getWithAllRelations($SupplierId);
dd($supplierData);
$priceLists = PriceList::where('supplier_id', $SupplierId)->with('attachment');
$PriceList = $priceLists->where('available', '<=', Carbon::now()->format('Y-m-d'));
if ($priceLists->orderBy('available', 'desc')->first()) {
$PriceList = $priceLists->orderBy('available', 'desc')->first();
}
dd($PriceList->toArray());
}
if (! $supplierData = $this->service->getWithAllRelations($SupplierId)) {
return response()->noContent();
}
$viewData = [];
$needData = ['name', 'openHours', 'ordersDeadline', 'minOrderValue', 'contact', 'note'];
foreach ($needData as $pointer) {
$viewData[$pointer] = $supplierData[$pointer];
}
$viewData['product_group'] = [];
foreach ($supplierData['product_group'] as $productGroup) {
$viewData['product_group'][] = [
'name' => $productGroup['name'],
'type' => $productGroup['type'],
];
}
$viewData['service'] = [];
$supplierData['service'] = collect($supplierData['service'])->sortBy('name')->toArray();
foreach ($supplierData['service'] as $service) {
$viewData['service'][] = [
'name' => $service['name'],
'id' => $service['id'],
];
}
$retData = [];
$retData['supplierData'] = $viewData;
$retData['attachment'] = $supplierData['attachment'];
unset($viewData,$needData,$supplierData);
$retData['files'] = [];
/*
* PriceList file
*/
$priceLists = PriceList::where('supplier_id', $SupplierId)->with('attachment');
$PriceList = $priceLists->where('available', '<=', Carbon::now()->format('Y-m-d'));
if ($priceLists->orderBy('available', 'desc')->first()) {
$PriceList = $priceLists->orderBy('available', 'desc')->first();
$retData['files']['priceList'] = $PriceList->toArray();
unset($priceLists,$PriceList);
}
return view('modules.supplier.show')->with($retData);
dd($retData, $supplierData);
$retData['supplierData'] = $supplierData;
$retData['testMode'] = ($this->testMode) ? 'true' : 'false';
$retData['init'] = false;
$ProductGroup = new \App\Models\ProductGroup;
$productGroupArray = $ProductGroup->allWithParents(2);
$retData['productGroup'] = $productGroupArray;
$retData['profitCenter'] = ProfitCenter::orderBy('name', 'asc')->get()->toArray();
return view('modules.supplier.show')->with($retData);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
/**
* Remove the specified resource from storage.
*/
public function destroy(int $SupplierId): Response|JsonResponse
{
return response()->noContent();
}
public function getDataTableContent(): JsonResponse
{
$accessSupplier = ProfitCenter::with('suppliers')->find(auth()->user()->profitCenters->first()->id)->suppliers->pluck('id')->toArray();
// $suppliers=Supplier::all()->toArray();
$repo = new SupplierRepository;
$suppliers = $repo->allWithRelations();
$suppliers = array_filter($suppliers, function ($item) use ($accessSupplier) {
if (in_array($item['id'], $accessSupplier)) {
return true;
}
return false;
});
// dd($suppliers);
// $repository=new SupplierRepository();
$ret = ['data' => []];
// $items=$repository->getQueryWithRelations()->orderBy('name')->get()->toArray();
foreach ($suppliers as $item) {
// dd(collect($item['product_group'])->pluck('name')->all());
// dd(collect($item['product_group'])->implode('name',','));
$data['id'] = $item['id'];
$data['name'] = $item['name'];
$data['hooreycaId'] = $item['hooreycaId'];
$data['nameId'] = $item['nameId'];
$data['product_group'] = collect($item['product_group'])->implode('name', ', ');
$data['service'] = collect($item['service'])->implode('name', ', ');
$data['created_at'] = formatterDateTime($item['created_at']);
$data['canSeeInOrder'] = $item['canSeeInOrder'];
$ret['data'][] = $data;
}
return \response()->json($ret);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers;
use App\Enums\OrderStatusEnum;
use App\Enums\OrderType;
use App\Models\OrderArchive;
use Carbon\Carbon;
class SupplierFeedbackController extends Controller
{
public function orderFeedback($orderFeedbackId)
{
if ($Order = OrderArchive::where('feedBackId', base64_decode($orderFeedbackId))->get()->first()) {
$viewData = $Order->toArray();
if (! is_null($Order->confirmed)) {
$viewData['confirmedBefore'] = true;
return view('modules.order.supplierFeedback')->with($viewData);
}
if ($Order->orderType == OrderType::weekly) {
foreach ($Order->children as $dayOrder) {
$dayOrder->confirmed = Carbon::now();
// $dayOrder->orderStatus=OrderStatusEnum::confirmed;
$dayOrder->save();
}
}
$Order->confirmed = Carbon::now();
// $Order->orderStatus=OrderStatusEnum::confirmed;
$Order->save();
$viewData = $Order->toArray();
return view('modules.order.supplierFeedback')->with($viewData);
}
return response(null, 500);
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers;
use App\Enums\DbStatusFieldEnum;
use App\Enums\ProductTypeEnum;
use App\Models\ProductGroup;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\View\View;
class TestController extends Controller
{
private function parseNodes($parentNode, $collection)
{
$parentNodeName = $parentNode->name;
$rootNode = false;
if (! isset($parentNode->parent_id) || is_null($parentNode->parent_id)) {
// o maga a root Node
$rootNode = true;
}
foreach ($collection as $row) {
if (isset($row[$parentNodeName])
&& strlen($row[$parentNodeName]) > 0
&& $row[$parentNodeName] !== 'n/a'
) {
$node = [
'name' => $row[$parentNodeName],
'status' => DbStatusFieldEnum::active,
];
if ($rootNode) {
if (ProductTypeEnum::hasValue($node['name'])) {
$node['type'] = ProductTypeEnum::getKey($node['name']);
} else {
$node['type'] = ProductTypeEnum::X();
}
} else {
$node['type'] = $parentNode->type;
}
$treeNode = $parentNode->children()->create($node);
$this->parseNodes($treeNode, $collection);
}
}
}
public function test1(): Response|JsonResponse
{
// ...
return response('helloka');
}
public function test2(): Response|JsonResponse
{
$o = new ProductGroup;
return response()->json($o->allToTreeArray()['children']);
}
public function test(): View|Response|JsonResponse
{
// ...
return view('test.test');
}
}

View File

@ -0,0 +1,307 @@
<?php
namespace App\Http\Controllers\api\v1;
use App\Http\Controllers\Controller;
use App\Models\OrderArchive;
use Carbon\Carbon;
use Flugg\Responder\Http\MakesResponses;
use Flugg\Responder\Responder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class OrderController extends Controller
{
use MakesResponses;
public function convertItemCollectionToHooreycaAPIItems($ItemCollection)
{
unset($ItemCollection->order_archive_id);
$ItemCollection->HooreycaVolumen = null;
$ItemCollection->HooreycaUnitPrice = null;
if ($ItemCollection->HooreycaMultiplier !== null) {
$ItemCollection->HooreycaVolumen = $ItemCollection->quantity * $ItemCollection->HooreycaMultiplier;
$ItemCollection->HooreycaUnitPrice = ($ItemCollection->quantity * $ItemCollection->price) / $ItemCollection->HooreycaVolumen;
}
/* if(!in_array($ItemCollection->id,[91045,91046,91047,91042,91043,91044])){
var_dump($ItemCollection->id);
var_dump(($ItemCollection->quantity*$ItemCollection->price)/($ItemCollection->quantity*$ItemCollection->HooreycaMultiplier));
die('hello');
}*/
// $ItemCollection->HooreycaSumPrice=($ItemCollection->quantity*$ItemCollection->HooreycaMultiplier);
// 'HooreycaSumPrice'=>
return $ItemCollection;
/*
Rendelő felületről adatok biztosítása
- Cikk kódja
- Mennyiségi egység (árlista L oszlop)
- Mértékegység (árlista H oszlop)
- Kiszerelés (árlista F oszlop)
- Súly/Űrtartalom (árlista G oszlop)
- Egységszorzó (árlista K oszlop)
- Rendelt mennyiség
- Megrendelt cikk nettó értéke
*/
return $ItemCollection->map(function ($item) {
return [
'id' => $item->id,
'hooreycaId' => $item->hooreycaId, // - Cikk kódja
'HooreycaUnit' => $item->HooreycaUnit,
'HooreycaMultiplier' => $item->HooreycaMultiplier,
'productName' => $item->name.'aaaaaaaaaaaa',
'hooreycaId' => $item->hooreycaId,
'productUnit' => $item->productUnit,
'sellerUnit' => $item->sellerUnit,
'unitMultiplier' => $item->unitMultiplier, // - Egységszorzó (árlista K oszlop)
'amountUnit' => $item->amountUnit,
'quantity' => $item->quantity, // - Rendelt mennyiség
'price' => $item->price, // - Megrendelt cikk nettó értéke
'HooreycaVolumen' => $item->quantity * $item->HooreycaMultiplier,
'HooreycaSumPrice' => ($item->quantity * $item->price) / ($item->quantity * $item->HooreycaMultiplier),
];
});
}
public function convertOrderToHooreycaAPI($order, $key)
{
/*
Rendelő felületről adatok biztosítása
- szállító kódja supplier.hooreycaId
- Szállítási dátum deliveryDate
- Üzlet kódja profit_center.hooreycaId
*/
$order->APICallBackId = (string) \Str::orderedUuid();
$order->save();
$order->supplierHooreycaId = $order->supplier->hooreycaId;
$order->supplierName = $order->supplier->name;
$order->profitCenterHooreycaId = $order->profitCenter->hooreycaId;
$order->profitCenterName = $order->profitCenter->name;
$order->items = $order->itemsAPISpecial->transform([$this, 'convertItemCollectionToHooreycaAPIItems']);
unset($order->supplier,$order->profitCenter,$order->itemsAPISpecial);
return $order;
}
/**
Display a listing of the unprocessed orders.
@group Order management
@authenticated
@urlParam page int required The page number. Example: 4
@responseField status integer request HTTP status
@responseField status integer request HTTP status
@responseField success boolean process successes
@responseField apiVersion integer current API version
@responseField processedTime DateTime process Timestamp
@responseField data object collection of Orders.
@responseField data.APICallBackId string Neet to set order update status in setProcessed interface.
@responseFile 200 scenario="Has unprocessed orders" example/APIUnProcessingResponse.json
@responseFile 401 scenario="Request unauthenticated" example/APIUnauthenticated.json
*/
public function unProcessed(Request $request, Responder $responder)
{
Log::channel('api')->info('API request', ['requestData' => var_export($request->server(), true)]);
$updateDate = Carbon::now();
$OrderCollection = OrderArchive::with(['supplier' => function ($query) {
$query->select('id', 'name', 'hooreycaId');
}, 'profitCenter' => function ($query) {
$query->select('id', 'name', 'hooreycaId');
}, 'itemsAPISpecial' => function ($query) {
// $query->select('id','order_archive_id');
$query->select(
'order_archive_id',
'id',
'hooreycaId', // - Cikk kódja
'name',
'hooreycaId',
'HooreycaUnit',
'HooreycaMultiplier',
'productUnit',
'sellerUnit',
'unitMultiplier', // - Egységszorzó (árlista K oszlop)
'amountUnit',
'quantity', // - Rendelt mennyiség
'price'
);
},
])->select(
'id',
'supplier_id',
'profit_center_id',
'humanId',
'deliveryDate',
'confirmed', )
// ->whereNulll('APIConfirmed')
->whereNotNull('confirmed')
->whereNull('APIConfirmed')
->orderBy('id', 'desc')->paginate(3);
$ret[] = get_debug_type($OrderCollection);
$OrderCollection->transform([$this, 'convertOrderToHooreycaAPI']);
$updateId = $OrderCollection->pluck('id');
$header = parseAPIVersionFromNamespace(__NAMESPACE__);
$header['processedTime'] = $updateDate->format('Y.m.d. H:i:s.u');
$response = responder()->success($OrderCollection)->respond(null, $header);
$ret = [];
$ret[] = $OrderCollection->pluck('id');
$ret[] = OrderArchive::whereIn('id', $OrderCollection->pluck('id'));
OrderArchive::whereIn('id', $updateId)->update(['APILastGetting' => $updateDate]);
$ret[] = OrderArchive::whereIn('id', $updateId)->update(['APILastGetting' => $updateDate]);
Log::channel('api')->info('Update APILastGetting ', ['Id' => $updateId->toArray(), 'Date' => $updateDate]);
$ret[] = $response->getContent();
$ret[] = var_export($request->server(), true);
Log::channel('api')->info('API response', ['responseBody' => json_decode($response->getContent(), JSON_PRETTY_PRINT)]);
return $response;
/*erorr teszthez DB error
* return responder()->success(OrderArchive::with('items')->orderBy('kod','desc')->paginate(2))->respond();
*/
}
/*
* @bodyParam [] Example:["987f3001-6364-4d7c-8b0c-daf29dbd38ec","987ee197-5293-48de-a488-3c9a05229bb6"]
localhost key 2|hqN0ifD9OP0vIAQZRPubcZ7x5W8qw49XKeFk9WJs
d2d key "1|tCtfKT9hAjGt213iuluWiHEvlyAK2KqtZmblQx8Y"
{"APICallBackId":["987f3001-6364-4d7c-8b0c-daf29dbd38ec","987f3001-6364-4d7c-8b0c-daf29dbd38eX"]}
*/
/**
Set processed orders.
@group Order management
@authenticated
@bodyParam APICallBackId string[] required List of APICallBackId need to set. Example: 987f3001-6364-4d7c-8b0c-daf29dbd38ec
@responseField status integer request HTTP status
@responseField status integer request HTTP status
@responseField success boolean process successes
@responseField apiVersion integer current API version
@responseField processedTime DateTime process Timestamp
@responseField data object collection of updated Order status.
@responseField data.APICallBackId string Order update status ("updated" is ok).
@responseFile 200 scenario="Has unprocessed orders" example/APISetProcessingResponse.json
@responseFile 500 scenario="Request invalid Request Body data" example/APISetProcessingResponseErrorInvalidData.json
@responseFile 401 scenario="Request unauthenticated" example/APIUnauthenticated.json
*/
public function setProcessed(Request $request)
{
$updateDate = Carbon::now();
$successData = [];
$header = parseAPIVersionFromNamespace(__NAMESPACE__);
$header['processedTime'] = $updateDate->format('Y.m.d. H:i:s.u');
Log::channel('api')->info('API request', ['requestData' => var_export($request->server(), true)]);
Log::channel('api')->info('API request', ['requestData' => var_export($request->getContent(), true)]);
$orderUUIds = json_decode($request->getContent());
// var_export($orderUUIds);
// if(!property_exists($orderUUIds,'APICallBackId') || !is_array($orderUUIds->APICallBackId)){
if (! property_exists($orderUUIds, 'APICallBackId')) {
return responder()->error('invalid data', $request->getContent())->respond(null, $header);
}
// var_export(property_exists($orderUUIds,'APICallBackId'));
// die();
// return responder()->error('invalid data',gettype($orderUUIds));
// $orderUUIds=json_decode($request->getContent());
Log::channel('api')->info(var_export($orderUUIds, true));
foreach ($orderUUIds->APICallBackId as $APICallBackId) {
if (is_array($APICallBackId)) {
return responder()->error('invalid data'.__LINE__, $request->getContent())->respond(null, $header);
}
if ($Order = OrderArchive::where('APICallBackId', $APICallBackId)->whereNull('APIConfirmed')->first()) {
$Order->APIConfirmed = $updateDate;
$Order->save();
$successData[$APICallBackId] = 'updated';
} else {
$successData[$APICallBackId] = 'invalid Id';
}
}
$response = responder()->success($successData)->respond(null, $header);
Log::channel('api')->info('API response', ['responseBody' => json_decode($response->getContent(), JSON_PRETTY_PRINT)]);
return $response;
}
/**
Display a server Status.
@group General Interfaces
@unauthenticated
@responseField status integer request HTTP status
@responseField success boolean process successes
@responseField apiVersion integer current API version
@responseField processedTime DateTime process Timestamp
*
@responseField data.APIStatus string API status state (up and down).
@responseFile 200 scenario="Server status" example/APIServerStatusResponse.json
*/
public function status()
{
$header = parseAPIVersionFromNamespace(__NAMESPACE__);
$header['processedTime'] = Carbon::now()->format('Y.m.d. H:i:s.u');
return responder()->success(['APIStatus' => 'up'])->respond(null, $header);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return 'hello';
}
/**
* Store a newly created resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show(int $id)
{
//
}
/**
* Update the specified resource in storage.
*
* @return \Illuminate\Http\Response
*/
public function update(Request $request, int $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @return \Illuminate\Http\Response
*/
public function destroy(int $id)
{
//
}
}

67
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,67 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithCustomChunkSize;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class PriceListColumnsCheck implements ToArray, WithBatchInserts, WithCustomChunkSize, WithMultipleSheets
{
public function array(array $array)
{
// TODO: Implement array() method.
return $array;
}
public function sheets(): array
{
return [
0,
// 1 => new SecondSheetImport(),
];
}
public function chunkSize(): int
{
return 1;
}
public function batchSize(): int
{
return 1;
}
}

31
app/JsonApi/V1/Server.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace App\JsonApi\V1;
use LaravelJsonApi\Core\Server\Server as BaseServer;
class Server extends BaseServer
{
/**
* The base URI namespace for this server.
*/
protected string $baseUri = '/api/v1';
/**
* Bootstrap the server when it is handling an HTTP request.
*/
public function serving(): void
{
// no-op
}
/**
* Get the server's list of schemas.
*/
protected function allSchemas(): array
{
return [
// @TODO
];
}
}

22
app/Models/Address.php Normal file
View File

@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Address extends BaseAuditable
{
protected $appends = ['fullAddress'];
public function attachable(): MorphTo
{
return $this->morphTo();
}
public function getFullAddressAttribute(): string
{
return "{$this->postCode} {$this->city} {$this->street}";
return $this->postCode.' '.$this->city.' '.$this->street;
}
}

140
app/Models/Attachment.php Normal file
View File

@ -0,0 +1,140 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\UploadedFile;
/**
* @property false|mixed|string path
* @property false|mixed|string mimetype
* @property false|int|mixed size
* @property false|mixed|string original_filename
* @property mixed|string filename
* @property int id
* @property string attachType
*/
class Attachment extends BaseAuditable
{
protected $appends = ['PublicUrl'];
public function attachable(): MorphTo
{
return $this->morphTo();
}
public function addStreamedFile($stream = null, $fileName = null)
{
$temp = tmpfile();
fwrite($temp, $stream);
$acceptedMime = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'application/pdf' => 'pdf',
];
$this->mimetype = mime_content_type($temp);
$this->size = filesize(stream_get_meta_data($temp)['uri']);
fclose($temp);
if (! array_key_exists($this->mimetype, $acceptedMime)) {
return false;
}
if ($fileName) {
$this->original_filename = $fileName;
}
$fileExt = $acceptedMime[$this->mimetype];
$this->filename = (string) \Str::orderedUuid().'.'.$fileExt;
$this->save();
$dir = sprintf('%010d', intval(floor($this->id / 1000)));
$this->path = DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR;
$fileNameWithPath = DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$this->filename;
\Storage::disk('attachments')->put($fileNameWithPath, $stream);
$this->save();
return $this->id;
/*
$attachment = new Attachment;
$attachment->addFile($file);
$attachment->attachable()->associate($customer);
$attachment->save();
*/
}
private function makeFilenameWithPath($fileExt = 'tmp'): string
{
return $this->getSavePath().DIRECTORY_SEPARATOR.$this->makeFileName($fileExt);
}
private function makeFileName($fileExt = 'tmp'): string
{
return (string) \Str::orderedUuid().'.'.$fileExt;
}
private function getSavePath(): string
{
return sprintf('%010d', intval(floor($this->id / 1000)));
}
public function addFile(UploadedFile $file): ?Attachment
{
if (isset($file) && $file && is_file($file)) {
$this->mimetype = $file->getMimeType();
$this->size = $file->getSize();
$this->filename = $this->makeFileName($file->extension());
$this->original_filename = $file->getClientOriginalName();
if (! $this->id) {
$this->save();
}
$this->path = $this->getSavePath();
\Storage::disk('attachments')->putFileAs($this->getSavePath(), $file, $this->filename);
$this->save();
return $this;
return $this;
$oldName = $file->getClientOriginalName();
$this->original_filename = $oldName;
$path = \Storage::disk('dev')->put('/', $file, ['name' => $oldName]);
$this->path = $path;
// \Storage::disk('dev')->download($path);
$this->filename = $file->getClientOriginalName();
}
return null;
}
public function removeFile()
{
try {
\Storage::disk('attachments')->delete($this->path.DIRECTORY_SEPARATOR.$this->filename); // false-al ter vissza sikeres torles eseten is
// var_dump('sikeres torles');
} catch (\Exception $e) {
return false;
}
return true;
}
public function delete()
{
if ($this->removeFile()) {
return parent::delete(); // TODO: Change the autogenerated stub
}
return false;
}
public function getPublicUrlAttribute(): string
{
return $this->getPublicUrl();
}
public function getPublicUrl()
{
return \Storage::disk('attachments')->url(str_replace('\\', '/', $this->path));
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Models;
use App\Traits\GetRelationshipsTraits;
use App\Traits\ModelUserIdAppenderTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BaseAuditable extends Model
{
use GetRelationshipsTraits,
HasFactory,
ModelUserIdAppenderTrait;
protected $guarded = [];
}

13
app/Models/Contact.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Contact extends BaseAuditable
{
public function contactable(): MorphTo
{
return $this->morphTo();
}
}

42
app/Models/Order.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace App\Models;
use App\Enums\OrderStatusEnum;
use App\Enums\OrderType;
use App\Traits\SelfReferenceTraits;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* @method static find(int $orderId)
* @method static where($column, $operator = null, $value = null, $boolean = 'and')
* @method children()
*
* @property HasMany children
* @property OrderStatusEnum orderStatus
* @property int|null parent_id
* @property OrderType orderType
*/
class Order extends BaseAuditable
{
use SelfReferenceTraits;
protected $guarded = ['id', 'created_at', ' updated_at'];
public function supplier(): BelongsTo
{
return $this->belongsTo(Supplier::class);
}
public function profitCenter(): BelongsTo
{
return $this->belongsTo(ProfitCenter::class);
}
public function orderNumber(): HasOne
{
return $this->hasOne(OrderNumber::class);
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace App\Models;
use App\Enums\OrderStatusEnum;
use App\Enums\OrderType;
use App\Traits\SelfReferenceTraits;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
/**
* @method static find(int $orderId)
* @method static where($column, $operator = null, $value = null, $boolean = 'and')
* @method children()
*
* @property Collection<OrderArchivesItem> items
* @property Attachment attachment
* @property Supplier supplier
* @property ProfitCenter profitCenter
* @property HasMany children
* @property OrderStatusEnum orderStatus
* @property int|null parent_id
* @property OrderType orderType
*/
class OrderArchive extends BaseAuditable
{
use SelfReferenceTraits;
/**
* The items that belong to the OrderArchive.
*/
public function items(): HasMany
{
return $this->hasMany(OrderArchivesItem::class);
}
public function attachment(): MorphOne
{
return $this->morphOne(Attachment::class, 'attachable');
}
public function supplier(): BelongsTo
{
return $this->belongsTo(Supplier::class);
}
public function profitCenter(): BelongsTo
{
return $this->belongsTo(ProfitCenter::class);
}
public function supplierNotifier(): HasMany
{
return $this->hasMany(SupplierNotifier::class);
}
public function itemsAPISpecial(): HasMany
{
return $this->hasMany(OrderArchivesItem::class);
// ->with(['ProductGroup']);
}
public function specialApiData()
{
/*
* 'supplier','profitCenter','itemsx'
* Rendelő felületről adatok biztosítása
- szállító kódja supplier.hooreycaId
- Szállítási dátum deliveryDate
- Üzlet kódja profit_center.hooreycaId
- Cikk kódja
- Mennyiségi egység (árlista L oszlop)
- Mértékegység (árlista H oszlop)
- Kiszerelés (árlista F oszlop)
- Súly/Űrtartalom (árlista G oszlop)
- Egységszorzó (árlista K oszlop)
- Rendelt mennyiség
- Megrendelt cikk nettó értéke
*/
$ret = $this->query();
// $ret=$ret->select('supplier_id');
// $ret=$ret->with(['supplier'=>function($query){$query->select('hooreycaId');}]);
$ret = $ret->with(['supplier' => function ($query) {
$query->select('id', 'hooreycaId');
}, 'profitCenter', 'itemsAPISpecial']);
// dd($ret->first());
return $ret;
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OrderArchivesItem extends BaseAuditable
{
/**
* The items that belong to the OrderArchive.
*/
public function orderArchive(): BelongsTo
{
return $this->belongsTo(OrderArchive::class);
}
public function ProductGroup(): BelongsTo
{
return $this->belongsTo(ProductGroup::class);
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OrderNumber extends Model
{
use HasFactory;
protected $guarded = [];
}

11
app/Models/Pack.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pack extends Model
{
use HasFactory;
}

10
app/Models/Permission.php Normal file
View File

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Laratrust\Models\Permission as LaratrustPermission;
class Permission extends LaratrustPermission
{
public $guarded = [];
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Models\Pivot;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PricePivot extends Pivot
{
public function price(): BelongsTo
{
return $this->belongsTo();
}
}

66
app/Models/PriceList.php Normal file
View File

@ -0,0 +1,66 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
/**
* @property Supplier supplier
*/
// class PriceList extends Model implements AuditableContract
class PriceList extends BaseAuditable
{
public function attachment(): MorphOne
{
return $this->morphOne(Attachment::class, 'attachable');
}
// protected $hidden=['created_at'];
public function supplier(): BelongsTo
{
return $this->belongsTo(Supplier::class);
}
private array $productRelations = ['Producer', 'picture', 'specification'];
public function getProductRelations(): array
{
return $this->productRelations;
}
public function setProductRelations(array $productRelations): void
{
$this->productRelations = $productRelations;
}
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class, 'price_list_prices', 'price_list_id', 'product_id')
// ->where('price_list_id','=',$priceListId)
// ->where('product_group_id','=',12)
->whereRaw('price_list_prices.price_list_id = ?', [$this->id])
->withTimestamps()
->withPivot(['price'])
// ->with('Producer')
->with($this->productRelations)
// ->using(PricePivot::class)
->as('priceListPrice');
// ->wherePivot('price','<','500')
}
public function productsWithRelations(): BelongsToMany
{
return $this->belongsToMany(Product::class, 'price_list_prices', 'price_list_id', 'product_id')
->withTimestamps()
->withPivot(['price'])
->with(['Producer', 'ProductGroup'])
// ->using(PricePivot::class)
->as('priceListPrice');
// ->wherePivot('price','<','500')
}
}

5
app/Models/Producer.php Normal file
View File

@ -0,0 +1,5 @@
<?php
namespace App\Models;
class Producer extends BaseAuditable {}

107
app/Models/Product.php Normal file
View File

@ -0,0 +1,107 @@
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends BaseAuditable
{
use SoftDeletes;
protected $guarded = ['id'];
// protected $fillable=['name'];
public function ProductGroup(): BelongsTo
{
return $this->belongsTo(ProductGroup::class);
}
public function Supplier(): BelongsTo
{
return $this->belongsTo(Supplier::class);
}
public function Producer(): BelongsTo
{
return $this->belongsTo(Producer::class);
}
public function Price(?string $deliveryDate = null)
{
$price = $this->belongsToMany(PriceList::class, 'price_list_prices', 'product_id', 'price_list_id')->select('id')
// ->withTimestamps()
->withPivot(['price']);
if (! $deliveryDate) {
$deliveryDate = Carbon::today()->format('Y-m-d');
}
$price->where('available', '<=', $deliveryDate);
$price->orderBy('available', 'desc')->orderBy('id', 'asc');
$price->first();
if ($price = $price->get()->toArray()) {
$price = $price[0]['pivot']['price'];
}
return $price;
}
public function setAttributePrice(?string $deliveryDate = null)
{
$this->setAttribute('price', $this->price($deliveryDate));
}
public function LastPrice(): BelongsToMany
{
return $this->belongsToMany(PriceList::class, 'price_list_prices', 'product_id', 'price_list_id')->select('id')
->withTimestamps()
->withPivot(['price'])
->where('available', '<=', Carbon::today()->format('Y-m-d'))
->orderBy('available', 'desc')->orderBy('id', 'desc');
// ->limit(1)
// ->as('priceListPrice')
}
public function PriceList(): BelongsToMany
{
return $this->belongsToMany(PriceList::class, 'price_list_prices', 'product_id', 'price_list_id')
->withTimestamps()
->withPivot(['price']);
// ->as('priceListPrice')
}
public function ProfitCenter(): BelongsToMany
{
return $this->belongsToMany(ProfitCenter::class, 'profit_center_favorites')->withTimestamps();
}
public function picture(): MorphOne
{
return $this->morphOne(Attachment::class, 'attachable')->where('attachType', '=', 'picture');
}
public function specification(): MorphOne
{
return $this->morphOne(Attachment::class, 'attachable')->where('attachType', '=', 'specification');
}
public function getActualPriceList(?string $deliveryDate = null): ?PriceList
{
$price = $this->belongsToMany(PriceList::class, 'price_list_prices', 'product_id', 'price_list_id')->select('id')
// ->withTimestamps()
->withPivot(['price']);
if (! $deliveryDate) {
$deliveryDate = Carbon::today()->format('Y-m-d');
}
$price->where('available', '<=', $deliveryDate);
$price->orderBy('available', 'desc')->orderBy('id', 'asc');
// $price->first();
return $price->get()->first();
}
}

146
app/Models/ProductGroup.php Normal file
View File

@ -0,0 +1,146 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kalnoy\Nestedset\NodeTrait;
/**
* @property int id
* @property string|null productNo
* @property string|null name
* @property ProductTypeEnum|null type
* @property DbStatusFieldEnum status
* @property bool canSee
* @property timestamp|null created_at
* @property timestamp|null updated_at
* @property timestamp|null deleted_at
*/
class ProductGroup extends Model
{
use HasFactory,NodeTrait,SoftDeletes;
protected $fillable = [
'productNo',
'name',
'type',
'status',
'canSee',
];
protected ?array $needsId = null;
private function getNodeToArray($node, $needChild, $maxDepth = 999)
{
if ($this->needsId) {
if (! in_array($node->id, $this->needsId)) {
return false;
}
}
$productGroupArray = $node->toArray();
$productGroupArray['isLeaf'] = $node->isLeaf();
if (! $productGroupArray['isLeaf'] && $node->depth < $maxDepth) {
$productGroupArray['children'] = $this->getChildNodesArray($node, $maxDepth);
if (count($productGroupArray['children']) < 1) {
$productGroupArray['isLeaf'] = true;
}
}
return $productGroupArray;
}
private function getChildNodesArray($node, $maxDepth = 999)
{
$childrenArray = [];
$children = ProductGroup::find($node->id)->descendants()->withDepth()->having('depth', '=', $node->depth + 1)->get();
foreach ($children as $child) {
if ($node->depth <= $maxDepth) {
if ($children = $this->getNodeToArray($child, true, $maxDepth)) {
$childrenArray[] = $children;
}
}
}
return $childrenArray;
}
public function allToTreeArray($NodeId = 1, $maxDepth = 999)
{
$productGroup = $this->withDepth()->where('id', $NodeId)->get()->first();
return $this->getNodeToArray($productGroup, true, $maxDepth);
}
public function nodesWithParentToTree(array $nodesId)
{
$this->needsId = [];
foreach ($nodesId as $nodeId) {
$this->needsId = array_unique(array_merge($this->needsId, $this->ancestorsAndSelf($nodeId)->pluck('id')->toArray()));
}
return $this->allToTreeArray();
}
/**
* add parents Array, parentsId Array, ParentsName Array, hasChild parameter
*/
public function allWithParents($maxDepth = 999): array
{
// $productGroupArray=$this->with('ancestors')->get()->toArray();
$productGroupArray = [];
$productGroups = $this->withDepth()->get();
foreach ($productGroups as $item) {
if ($item->depth > $maxDepth) {
continue;
}
$children = ProductGroup::descendantsOf($item);
(count($children) > 0) ? $item->hasChild = true : $item->hasChild = false;
$parents = ProductGroup::ancestorsOf($item);
$item->parents = $parents->toArray();
$item->parentsNames = ProductGroup::ancestorsOf($item)->pluck('name')->toArray();
$item->parentsPath = implode('/', ProductGroup::ancestorsOf($item)->pluck('name')->toArray());
$item->parentsIds = ProductGroup::ancestorsOf($item)->pluck('id')->toArray();
$item->parentsIdPointer = implode('_', ProductGroup::ancestorsOf($item)->pluck('name')->toArray());
$productGroupArray[] = $item->toArray();
}
return $productGroupArray;
}
/**
* add parents Array, parentsId Array, ParentsName Array, hasChild parameter
*/
public function allWithPath($maxDepth = 999): array
{
$pathSeparator = '/';
$pointerSeparator = '_';
$productGroupArray = [];
$productGroups = $this->withDepth()->get();
foreach ($productGroups as $item) {
if ($item->depth > $maxDepth) {
continue;
}
$children = ProductGroup::descendantsOf($item);
(count($children) > 0) ? $item->hasChild = true : $item->hasChild = false;
$parents = ProductGroup::ancestorsOf($item);
$item->parentsNames = ProductGroup::ancestorsOf($item)->pluck('name')->toArray();
$item->parentsIds = ProductGroup::ancestorsOf($item)->pluck('id')->toArray();
$item->parentsPath = implode('/', ProductGroup::ancestorsOf($item)->pluck('name')->toArray());
$item->parentsIdPointer = implode('_', ProductGroup::ancestorsOf($item)->pluck('name')->toArray());
if (count($item->parentsIds) > 0) {
$item->fullPath = $item->parentsPath.$pathSeparator.$item->name;
$item->fullPointer = $item->parentsIdPointer.$pointerSeparator.$item->name;
} else {
$item->fullPath = $item->name;
$item->fullPointer = $item->name;
}
$productGroupArray[] = $item->toArray();
}
return $productGroupArray;
}
}

128
app/Models/ProfitCenter.php Normal file
View File

@ -0,0 +1,128 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property Collection<Supplier> suppliers
*/
class ProfitCenter extends BaseAuditable
{
protected $guarded = ['id', 'created_at', ' updated_at'];
protected $appends = ['fullAddress', 'primaryPhone'];
use SoftDeletes;
/**
* The users that belong to the ProfitCenter.
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, 'profit_center_users')->withTimestamps();
}
/**
* The suppliers that belong to the ProfitCenter.
*/
public function suppliers(): BelongsToMany
{
return $this->belongsToMany(Supplier::class)->withTimestamps();
}
public function contact(): MorphMany
{
return $this->morphMany(Contact::class, 'contactable');
}
public function address(): MorphMany
{
return $this->morphMany(Address::class, 'attachable');
}
public function attachment(): MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
}
public function syncContactRelations(array $contactIds): bool
{
return $this->syncMorph(Contact::class, 'contactable', $contactIds);
}
public function syncRelations(array $relIds, $relType): bool
{
return $this->syncMorph($relType, 'attachable', $relIds);
}
public function syncMorph($class, $classFunctionName, $ids = []): bool
{
if (! class_exists($class)) {
$class = __NAMESPACE__.'\\'.$class;
if (! class_exists($class)) {
return false;
}
}
$f = new \ReflectionClass($class);
$relationFunctionName = lcfirst($f->getShortName());
if (method_exists($this, $relationFunctionName)) {
$associated = $this->$relationFunctionName()->pluck('id')->toArray();
$needToRemove = array_diff($associated, $ids);
$needToAdd = array_diff($ids, $associated);
if (count($needToRemove) > 0) {
foreach ($needToRemove as $id) {
$item = $class::find($id);
$item->$classFunctionName()->dissociate($this);
$item->save();
}
}
if (count($needToAdd) > 0) {
foreach ($needToAdd as $id) {
$item = $class::find($id);
$item->$classFunctionName()->associate($this);
$item->save();
}
}
return true;
}
return false;
}
public function getFullAddressAttribute(): string
{
return "{$this->postCode} {$this->city} {$this->street}";
return $this->postCode.' '.$this->city.' '.$this->street;
}
public function getPrimaryPhoneAttribute(): ?string
{
if (! $this->mobil) {
if ($this->phone) {
return $this->phone;
} else {
return null;
}
}
return $this->mobil;
}
/**
* The Product that belong to the ProfitCenter.
*/
public function favorites(): BelongsToMany
{
return $this->belongsToMany(Product::class, 'profit_center_favorites')->withTimestamps();
}
public function favoritesBySupplier($supplierId): BelongsToMany
{
return $this->belongsToMany(Product::class, 'profit_center_favorites')->where('supplier_id', '=', $supplierId);
}
}

13
app/Models/Role.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Laratrust\Models\Role as LaratrustRole;
/**
* @method static where(string $string, string $string1)
*/
class Role extends LaratrustRole
{
public $guarded = [];
}

5
app/Models/Service.php Normal file
View File

@ -0,0 +1,5 @@
<?php
namespace App\Models;
class Service extends BaseAuditable {}

84
app/Models/Supplier.php Normal file
View File

@ -0,0 +1,84 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class Supplier extends BaseAuditable
{
use SoftDeletes;
protected $guarded = ['id', 'created_at', ' updated_at'];
protected $appends = ['productGroupNames'];
public function getProductGroupNamesAttribute(): string
{
return $this->productGroup()->pluck('name');
}
public function contact(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Contact::class, 'contactable');
}
public function contactOrderMail(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Contact::class, 'contactable')->where('type', 'like', 'orderMail');
}
public function productGroup(): BelongsToMany
{
return $this->belongsToMany(ProductGroup::class, 'supplier_product_group')->withTimestamps();
}
public function service(): BelongsToMany
{
return $this->belongsToMany(Service::class, 'supplier_services')->withTimestamps();
}
public function profitCenter(): BelongsToMany
{
return $this->belongsToMany(ProfitCenter::class)->withTimestamps();
}
public function attachment(): \Illuminate\Database\Eloquent\Relations\MorphMany
{
return $this->morphMany(Attachment::class, 'attachable');
}
public function syncContactRelations(array $contactIds): bool
{
return $this->syncMorph(Contact::class, 'contactable', $contactIds);
}
public function syncMorph($class, $classFunctionName, $ids = []): bool
{
$f = new \ReflectionClass($class);
$relationFunctionName = lcfirst($f->getShortName());
if (method_exists($this, $relationFunctionName)) {
$associated = $this->$relationFunctionName()->pluck('id')->toArray();
$needToRemove = array_diff($associated, $ids);
$needToAdd = array_diff($ids, $associated);
if (count($needToRemove) > 0) {
foreach ($needToRemove as $id) {
$item = $class::find($id);
$item->$classFunctionName()->dissociate($this);
$item->save();
}
}
if (count($needToAdd) > 0) {
foreach ($needToAdd as $id) {
$item = $class::find($id);
$item->$classFunctionName()->associate($this);
$item->save();
}
}
return true;
}
return false;
}
}

View File

@ -0,0 +1,137 @@
<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class SupplierNotifier extends Model
{
use HasFactory;
protected int $minHour = 0;
protected array $notifierHour = [3, 8, 24];
protected array $workHour = [
1 => [4, 18],
2 => [4, 18],
3 => [4, 18],
4 => [4, 18],
5 => [4, 16],
6 => [23, -1],
0 => [23, -1],
];
private Carbon $nowTime;
public function __construct()
{
parent::__construct();
$this->minHour = $this->notifierHour[0];
$this->nowTime = Carbon::now();
}
private function getNextTime($timeStr, $needHour): string
{
$Time = Carbon::createFromDate($timeStr);
$nextDay = $Time->copy()->nextWeekday();
$dayRecentHour = $this->workHour[$nextDay->dayOfWeek][1] - $this->workHour[$nextDay->dayOfWeek][0];
if ($needHour < $dayRecentHour) {
// datum visszaad
return $nextDay->setTime($this->workHour[$nextDay->dayOfWeek][0] + $needHour, $Time->minute)->toDateTimeString();
} else {
// return 'rec>'.var_export([$Time,$needHour,$dayRecentHour],true);
return $this->getNextTime($Time->copy()->nextWeekday(), ($needHour - $dayRecentHour));
}
}
public function getLowestWorkTime($timeStr): string
{
$Time = Carbon::createFromDate($timeStr);
/*
* ha korábabn adták le mint az adott nap első munkaórája, akkor az kerül beállításra
*/
if ($Time->hour < $this->workHour[$Time->dayOfWeek][0]) {
$Time->setTime($this->workHour[$Time->dayOfWeek][0], 0);
// var_dump($Time->toDateTimeString(),'Set workStart hour');
}
/*
* ha késöbb adták le mint az adott nap utolsó munkaórája, akkor a következő munkanap első órája kerül beállításra
*/
if ($Time->hour >= $this->workHour[$Time->dayOfWeek][1]) {
$Time->nextWeekday();
$Time->setTime($this->workHour[$Time->dayOfWeek][0], 0);
// var_dump($Time->toDateTimeString(),'Set NexDay');
}
return $Time->toDateTimeString();
}
public function makeTime($timeStr): array
{
/*
$timeStr='2023-09-08 15:12:12'; //péntek in work
$timeStr='2023-09-08 6:12:12'; //péntek +3+8
$timeStr='2023-09-08 17:12:12'; //péntek out of work
$timeStr='2023-09-08 11:12:12'; //péntek +3
$timeStr='2023-09-04 07:12:12'; //hetfő +3+8
$timeStr='2023-09-04 03:12:12'; //hetfő before work
$timeStr='2023-09-04 18:12:12'; //hetfő out of work
$timeStr='2023-09-04 07:12:12'; //hetfő +3+8
*/
$Time = Carbon::createFromDate($timeStr);
// var_dump($Time->toDateTimeString(),'Original');
$Time = Carbon::createFromDate($this->getLowestWorkTime($timeStr));
$endOfDay = Carbon::create($Time);
$endOfDay = $endOfDay->setTime($this->workHour[$Time->dayOfWeek][1], 0);
// var_dump('aaa>'.$endOfDay->toDateTimeString().' '.$Time->toDateTimeString());
$dayRecentHour = $Time->diffInHours($endOfDay);
$notifiedDateTime = [];
foreach ($this->notifierHour as $needHour) {
if ($dayRecentHour < $needHour) {
$notifiedDateTime[] = $this->getNextTime($Time, ($needHour - $dayRecentHour));
} else {
$notifiedDateTime[] = $Time->copy()->addHour($needHour)->toDateTimeString();
}
}
return $notifiedDateTime;
}
public function addNotificationsForOrderArchive(int $orderArchiveID, int $supplierID, array $times)
{
foreach ($times as $time) {
$SupplierNotifier = new SupplierNotifier;
$SupplierNotifier->order_archive_id = $orderArchiveID;
$SupplierNotifier->supplier_id = $supplierID;
$SupplierNotifier->need_send = $time;
$SupplierNotifier->save();
}
}
public function makeNotificationsForOrderArchive(int $orderArchiveID)
{
$OrderArchive = OrderArchive::find($orderArchiveID);
$times = $this->makeTime($OrderArchive->sentTime);
$this->addNotificationsForOrderArchive($OrderArchive->id, $OrderArchive->supplier_id, $times);
}
/**
* The items that belong to the OrderArchive.
*/
public function orderArchive(): BelongsTo
{
return $this->belongsTo(OrderArchive::class);
}
public function supplier(): BelongsTo
{
return $this->belongsTo(Supplier::class);
}
}

13
app/Models/Test.php Normal file
View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use App\Traits\SelfReferenceTraits;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
use HasFactory;
use SelfReferenceTraits;
}

63
app/Models/User.php Normal file
View File

@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Laratrust\Contracts\LaratrustUser;
use Laratrust\Traits\HasRolesAndPermissions;
use Laravel\Sanctum\HasApiTokens;
/**
* @property Collection<ProfitCenter> profitCenters
*/
class User extends Authenticatable implements LaratrustUser
{
use HasApiTokens, HasFactory, Notifiable;
use HasRolesAndPermissions;
// ,\OwenIt\Auditing\Auditable
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
];
}
/**
* The profitCenter that belong to the user.
*/
public function profitCenters(): BelongsToMany
{
return $this->belongsToMany(ProfitCenter::class, 'profit_center_users')->withTimestamps();
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
class systemParameters extends BaseAuditable
{
use SoftDeletes;
protected $guarded = ['id', 'created_at', ' updated_at'];
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Providers;
use App\Repositories\AddressRepository;
use App\Repositories\AddressRepositoryInterface;
use App\Repositories\ContactRepository;
use App\Repositories\ContactRepositoryInterface;
use App\Repositories\OrderRepository;
use App\Repositories\OrderRepositoryInterface;
use App\Repositories\PackRepository;
use App\Repositories\PackRepositoryInterface;
use App\Repositories\PriceListRepository;
use App\Repositories\PriceListRepositoryInterface;
use App\Repositories\ProducerRepository;
use App\Repositories\ProducerRepositoryInterface;
use App\Repositories\ProductRepository;
use App\Repositories\ProductRepositoryInterface;
use App\Repositories\ProfitCenterRepository;
use App\Repositories\ProfitCenterRepositoryInterface;
use App\Repositories\SupplierRepository;
use App\Repositories\SupplierRepositoryInterface;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->bind(AddressRepositoryInterface::class, AddressRepository::class);
$this->app->bind(ContactRepositoryInterface::class, ContactRepository::class);
$this->app->bind(OrderRepositoryInterface::class, OrderRepository::class);
$this->app->bind(PackRepositoryInterface::class, PackRepository::class);
$this->app->bind(PriceListRepositoryInterface::class, PriceListRepository::class);
$this->app->bind(ProducerRepositoryInterface::class, ProducerRepository::class);
$this->app->bind(ProductRepositoryInterface::class, ProductRepository::class);
$this->app->bind(ProfitCenterRepositoryInterface::class, ProfitCenterRepository::class);
$this->app->bind(SupplierRepositoryInterface::class, SupplierRepository::class);
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
$this->registerPolicies();
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*/
protected function configureRateLimiting(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}

View File

@ -0,0 +1,151 @@
<?php
namespace App\Repositories;
use App\Models\Address;
use App\Models\Contact;
use App\Traits\RepositoryRelationshipsTraits;
class AddressRepository implements AddressRepositoryInterface
{
use RepositoryRelationshipsTraits;
private string $Model;
private array $defaultRelations = [];
public function __construct()
{
$this->Model = Address::class;
$this->actualRelations = $this->defaultRelations;
}
/**
* Get's a record by it's ID
*
* @param int
*/
public function get($id)
{
return Contact::find($id);
}
/**
* Get's all records.
*
* @return mixed
*/
public function all()
{
return Contact::all();
}
/**
* Deletes a record.
*
* @param int
*/
public function delete($id)
{
Contact::destroy($id);
}
/**
* Updates a post.
*
* @param int
* @param array
*/
public function update($id, array $data)
{
Contact::find($id)->update($data);
}
public function add($data): ?int
{
$obj = new $this->Model;
$obj->canSee = true;
$obj->status == \App\Enums\DbStatusFieldEnum::draft;
$obj->fill($data);
$obj->save();
return $obj->id;
}
public function associate($id, $relationId, $relationClass): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationClass::find($relationId)) {
return false;
}
$ret = false;
if ($item->attachable()->associate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
public function dissociate($id, $relationId, $relationClass): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationClass::find($relationId)) {
}
$ret = false;
if ($item->attachable()->dissociate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
public function setRelationItem($id, $relationId, $relationType): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationType::find($relationId)) {
return false;
}
$ret = false;
if ($item->attachable()->associate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
public function unsetRelationItem($id, $relationId, $relationType): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationType::find($relationId)) {
return false;
}
$ret = false;
if ($item->attachable()->dissociate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Repositories;
interface AddressRepositoryInterface
{
/**
* Get's a record by it's ID
*
* @param int
*/
public function get($id);
/**
* Get's all records.
*
* @return mixed
*/
public function all();
/**
* Deletes a record.
*
* @param int
*/
public function delete($id);
/**
* Updates a record.
*
* @param int
* @param array
*/
public function update($id, array $data);
}

View File

@ -0,0 +1,110 @@
<?php
namespace App\Repositories;
use App\Models\Contact;
use App\Traits\RepositoryRelationshipsTraits;
class ContactRepository implements ContactRepositoryInterface
{
use RepositoryRelationshipsTraits;
private string $Model;
private array $defaultRelations = [];
public function __construct()
{
$this->Model = Contact::class;
$this->actualRelations = $this->defaultRelations;
}
/**
* Get's a record by it's ID
*
* @param int
*/
public function get($id)
{
return Contact::find($id);
}
/**
* Get's all records.
*
* @return mixed
*/
public function all()
{
return Contact::all();
}
/**
* Deletes a record.
*
* @param int
*/
public function delete($id)
{
Contact::destroy($id);
}
/**
* Updates a post.
*
* @param int
* @param array
*/
public function update($id, array $data)
{
Contact::find($id)->update($data);
}
public function add($data): ?int
{
$obj = new $this->Model;
$obj->canSee = true;
$obj->status == \App\Enums\DbStatusFieldEnum::draft;
$obj->fill($data);
$obj->save();
return $obj->id;
}
public function setContactRelation($id, $relationId, $relationType): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationType::find($relationId)) {
return false;
}
$ret = false;
if ($item->contactable()->associate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
public function unsetContactRelation($id, $relationId, $relationType): bool
{
if (! $item = $this->Model::find($id)) {
return false;
}
if (! $attachedItem = $relationType::find($relationId)) {
}
$ret = false;
if ($item->contactable()->dissociate($attachedItem)) {
if ($item->save()) {
$ret = true;
}
}
return $ret;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Repositories;
interface ContactRepositoryInterface
{
/**
* Get's a record by it's ID
*
* @param int
*/
public function get($id);
/**
* Get's all records.
*
* @return mixed
*/
public function all();
/**
* Deletes a record.
*
* @param int
*/
public function delete($id);
/**
* Updates a record.
*
* @param int
* @param array
*/
public function update($id, array $data);
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Repositories;
use App\Models\Order;
class OrderRepository extends RepositoryBase implements OrderRepositoryInterface
{
/**
* @var array[]
*/
private array $defaultRelations = [];
public function __construct()
{
parent::__construct(Order::class, $this->defaultRelations);
}
}

Some files were not shown because too many files have changed in this diff Show More