main
This commit is contained in:
commit
43b72c7521
|
|
@ -0,0 +1,18 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[docker-compose.yml]
|
||||
indent_size = 4
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=laravel
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
FILESYSTEM_DRIVER=local
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
MEMCACHED_HOST=127.0.0.1
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailhog
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
MAIL_FROM_ADDRESS=null
|
||||
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
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
* text=auto
|
||||
|
||||
*.blade.php diff=html
|
||||
*.css diff=css
|
||||
*.html diff=html
|
||||
*.md diff=markdown
|
||||
*.php diff=php
|
||||
|
||||
/.github export-ignore
|
||||
CHANGELOG.md export-ignore
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/node_modules
|
||||
/public/hot
|
||||
/public/storage
|
||||
/storage/*.key
|
||||
/vendor
|
||||
.env
|
||||
.env.backup
|
||||
.phpunit.result.cache
|
||||
docker-compose.override.yml
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
/.idea
|
||||
/.vscode
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
php:
|
||||
preset: laravel
|
||||
version: 8
|
||||
disabled:
|
||||
- no_unused_imports
|
||||
finder:
|
||||
not-name:
|
||||
- index.php
|
||||
- server.php
|
||||
js:
|
||||
finder:
|
||||
not-name:
|
||||
- webpack.mix.js
|
||||
css: true
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
<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"></a></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.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.
|
||||
|
||||
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 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 [Patreon page](https://patreon.com/taylorotwell).
|
||||
|
||||
### Premium Partners
|
||||
|
||||
- **[Vehikl](https://vehikl.com/)**
|
||||
- **[Tighten Co.](https://tighten.co)**
|
||||
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
|
||||
- **[64 Robots](https://64robots.com)**
|
||||
- **[Cubet Techno Labs](https://cubettech.com)**
|
||||
- **[Cyber-Duck](https://cyber-duck.co.uk)**
|
||||
- **[Many](https://www.many.co.uk)**
|
||||
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
|
||||
- **[DevSquad](https://devsquad.com)**
|
||||
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
|
||||
- **[OP.GG](https://op.gg)**
|
||||
- **[WebReinvent](https://webreinvent.com/?utm_source=laravel&utm_medium=github&utm_campaign=patreon-sponsors)**
|
||||
- **[Lendio](https://lendio.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).
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,213 @@
|
|||
<?php
|
||||
namespace App\Classes;
|
||||
|
||||
/**
|
||||
* Class PhpXlsxGenerator
|
||||
* Export data to MS Excel. PHP XLSX generator
|
||||
* Author: codexworld.com@gmail.com
|
||||
*/
|
||||
class SimpleCSVGen
|
||||
{
|
||||
|
||||
protected $_delimiter;
|
||||
protected $_enclosure;
|
||||
protected $_linebreak;
|
||||
protected $_csv = '';
|
||||
|
||||
public static function parse($filename_or_data, $is_data, $delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
|
||||
{
|
||||
$csv = new static($delimiter, $enclosure, $linebreak);
|
||||
$csv->_csv = $is_data ? $filename_or_data : file_get_contents($filename_or_data);
|
||||
return $csv;
|
||||
}
|
||||
public static function parseFile($filename, $delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
|
||||
{
|
||||
return static::parse($filename, false, $delimiter, $enclosure, $linebreak);
|
||||
}
|
||||
public static function parseData($csv_content, $delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
|
||||
{
|
||||
return static::parse($csv_content, true, $delimiter, $enclosure, $linebreak);
|
||||
}
|
||||
|
||||
public static function import($filename_or_data, $is_data = false, $delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
|
||||
{
|
||||
return (new static($delimiter, $enclosure, $linebreak))->toArray($filename_or_data, $is_data);
|
||||
}
|
||||
public static function export($items, $delimiter = ',', $enclosure = '"', $linebreak = "\r\n")
|
||||
{
|
||||
return (new static($delimiter, $enclosure, $linebreak))->fromArray($items);
|
||||
}
|
||||
public function __construct($delimiter = 'auto', $enclosure = 'auto', $linebreak = 'auto')
|
||||
{
|
||||
$this->_delimiter = $delimiter;
|
||||
$this->_enclosure = $enclosure;
|
||||
$this->_linebreak = $linebreak;
|
||||
}
|
||||
public function delimiter($set = false)
|
||||
{
|
||||
if ($set !== false) {
|
||||
return $this->_delimiter = $set;
|
||||
}
|
||||
if ($this->_delimiter === 'auto') {
|
||||
// detect delimiter
|
||||
if (($p = strpos($this->_csv, $this->_enclosure . ',')) > 0
|
||||
&& ($this->_csv[$p-1] !== $this->_enclosure)
|
||||
) {
|
||||
$this->_delimiter = ',';
|
||||
} elseif (($p = strpos($this->_csv, $this->_enclosure."\t")) > 0
|
||||
&& ($this->_csv[$p-1] !== $this->_enclosure)
|
||||
) {
|
||||
$this->_delimiter = "\t";
|
||||
} elseif (($p = strpos($this->_csv, $this->_enclosure . ';')) > 0
|
||||
&& ($this->_csv[$p-1] !== $this->_enclosure)
|
||||
) {
|
||||
$this->_delimiter = ';';
|
||||
} elseif (strpos($this->_csv, ',') !== false) {
|
||||
$this->_delimiter = ',';
|
||||
} elseif (strpos($this->_csv, "\t") !== false) {
|
||||
$this->_delimiter = "\t";
|
||||
} elseif (strpos($this->_csv, ';') !== false) {
|
||||
$this->_delimiter = ';';
|
||||
} else {
|
||||
$this->_delimiter = ',';
|
||||
}
|
||||
}
|
||||
return $this->_delimiter;
|
||||
}
|
||||
public function enclosure($set = false)
|
||||
{
|
||||
if ($set !== false) {
|
||||
return $this->_enclosure = $set;
|
||||
}
|
||||
if ($this->_enclosure === 'auto') {
|
||||
// detect quot
|
||||
if (strpos($this->_csv, '"') !== false) {
|
||||
$this->_enclosure = '"';
|
||||
} else if (strpos($this->_csv, "'") !== false) {
|
||||
$this->_enclosure = "'";
|
||||
} else {
|
||||
$this->_enclosure = '"';
|
||||
}
|
||||
}
|
||||
return $this->_enclosure;
|
||||
}
|
||||
public function linebreak($set = false)
|
||||
{
|
||||
if ($set !== false) {
|
||||
return $this->_linebreak = $set;
|
||||
}
|
||||
if ($this->_linebreak === 'auto') {
|
||||
if (strpos($this->_csv, "\r\n") !== false) {
|
||||
$this->_linebreak = "\r\n";
|
||||
} else if (strpos($this->_csv, "\n") !== false) {
|
||||
$this->_linebreak = "\n";
|
||||
} else if (strpos($this->_csv, "\r") !== false) {
|
||||
$this->_linebreak = "\r";
|
||||
} else {
|
||||
$this->_linebreak = "\r\n";
|
||||
}
|
||||
}
|
||||
return $this->_linebreak;
|
||||
}
|
||||
public function rows()
|
||||
{
|
||||
return $this->toArray();
|
||||
}
|
||||
public function toArray($filename = null, $is_csv_content = false)
|
||||
{
|
||||
|
||||
if ($filename) {
|
||||
$this->_csv = $is_csv_content ? $filename : file_get_contents($filename);
|
||||
}
|
||||
|
||||
$CSV_LINEBREAK = $this->linebreak();
|
||||
$CSV_ENCLOSURE = $this->enclosure();
|
||||
$CSV_DELIMITER = $this->delimiter();
|
||||
|
||||
|
||||
$r = array();
|
||||
$cnt = strlen($this->_csv);
|
||||
|
||||
$esc = false;
|
||||
$i = $k = $n = 0;
|
||||
$r[$k][$n] = '';
|
||||
|
||||
while ($i < $cnt) {
|
||||
$ch = $this->_csv[$i];
|
||||
$chch = ($i < $cnt-1) ? $ch.$this->_csv[$i+1] : $ch;
|
||||
|
||||
if ($ch === $CSV_LINEBREAK) {
|
||||
if ($esc) {
|
||||
$r[$k][$n] .= $ch;
|
||||
} else {
|
||||
$k++;
|
||||
$n = 0;
|
||||
$esc = false;
|
||||
$r[$k][$n] = '';
|
||||
}
|
||||
} else if ($chch === $CSV_LINEBREAK) {
|
||||
if ($esc) {
|
||||
$r[$k][$n] .= $chch;
|
||||
} else {
|
||||
$k++;
|
||||
$n = 0;
|
||||
$esc = false;
|
||||
$r[$k][$n] = '';
|
||||
}
|
||||
$i++;
|
||||
} else if ($ch === $CSV_DELIMITER) {
|
||||
if ($esc) {
|
||||
$r[$k][$n] .= $ch;
|
||||
} else {
|
||||
$n++;
|
||||
$r[$k][$n] = '';
|
||||
$esc = false;
|
||||
}
|
||||
} else if ($chch === $CSV_ENCLOSURE.$CSV_ENCLOSURE && $esc) {
|
||||
$r[$k][$n] .= $CSV_ENCLOSURE;
|
||||
$i++;
|
||||
} elseif ($ch === $CSV_ENCLOSURE) {
|
||||
$esc = !$esc;
|
||||
} else {
|
||||
$r[$k][$n] .= $ch;
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
return $r;
|
||||
}
|
||||
public function fromArray($items)
|
||||
{
|
||||
|
||||
if (!is_array($items)) {
|
||||
trigger_error('CSV::export array required', E_USER_WARNING);
|
||||
return false;
|
||||
}
|
||||
|
||||
$CSV_DELIMITER = $this->delimiter();
|
||||
$CSV_ENCLOSURE = $this->enclosure();
|
||||
$CSV_LINEBREAK = $this->linebreak();
|
||||
|
||||
$result = '';
|
||||
foreach ($items as $i) {
|
||||
$line = '';
|
||||
|
||||
foreach ($i as $v) {
|
||||
if (is_string($v) && $v !== '') {
|
||||
if (strpos($v, $CSV_ENCLOSURE) !== false) {
|
||||
$v = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $v);
|
||||
}
|
||||
|
||||
if ((strpos($v, $CSV_DELIMITER) !== false)
|
||||
|| (strpos($v, $CSV_ENCLOSURE) !== false)
|
||||
|| (strpos($v, $CSV_LINEBREAK) !== false)) {
|
||||
$v = $CSV_ENCLOSURE . $v . $CSV_ENCLOSURE;
|
||||
}
|
||||
}
|
||||
$line .= $line ? $CSV_DELIMITER . $v : $v;
|
||||
}
|
||||
$result .= $result ? $CSV_LINEBREAK . $line : $line;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
|
||||
use App\Http\Controllers\Admin\AdminDashboardController;
|
||||
use App\Http\Controllers\Admin\FinDocController;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AlertBalanceCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'dashboard:alertBalance';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Command description';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$controller = new AdminDashboardController();
|
||||
$controller->alertBalance();
|
||||
$controllerFinDocController = new FinDocController();
|
||||
$controllerFinDocController->payPingQuery();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Http\Controllers\Admin\AdminDashboardController;
|
||||
use App\Http\Controllers\Admin\FinDocController;
|
||||
use App\Http\Controllers\Admin\PriceController;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CallB750GetPriceCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'price:b750';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Command description';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
Log::info('CallB750GetPriceCommand started.');
|
||||
$this->b750Counter = Cache::increment('b750_counter'); // افزایش شمارنده در کش
|
||||
if ($this->b750Counter >= 15) {
|
||||
$controller = new AdminDashboardController();
|
||||
$controller->alertBalance();
|
||||
$controllerFinDocController = new FinDocController();
|
||||
$controllerFinDocController->payPingQuery();
|
||||
Cache::forget('b750_counter'); // بازنشانی شمارنده
|
||||
}
|
||||
|
||||
$controller = new PriceController();
|
||||
$controller->b750();
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use App\Jobs\GetB750PanelPriceJob;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*
|
||||
* @param \Illuminate\Console\Scheduling\Schedule $schedule
|
||||
* @return void
|
||||
*/
|
||||
protected function schedule(Schedule $schedule)
|
||||
{
|
||||
// $schedule->command('inspire')->hourly();
|
||||
$schedule->command('price:b750')->everyMinute();
|
||||
// $schedule->command('dashboard:alertBalance')->everyFifteenMinutes();
|
||||
$schedule->command('dashboard:alertBalance')->everyMinute();
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function commands()
|
||||
{
|
||||
$this->load(__DIR__.'/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithEvents;
|
||||
use Maatwebsite\Excel\Events\BeforeExport;
|
||||
use Maatwebsite\Excel\Events\AfterSheet;
|
||||
|
||||
class ExcelCollection implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* TableEngineExport constructor.
|
||||
*/
|
||||
public function __construct($export, $cols)
|
||||
{
|
||||
$this->export = $export;
|
||||
$this->show = array_keys($cols);
|
||||
$this->head = array_values($cols);
|
||||
}
|
||||
|
||||
public function collection()
|
||||
{
|
||||
|
||||
return $this->export->map(function ($value, $key) {
|
||||
|
||||
$exp = [];
|
||||
$all = $value->toArray();
|
||||
foreach ($this->show as $val) {
|
||||
$exp[$val] = Arr::get($all, $val);
|
||||
}
|
||||
return collect($exp);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public function registerEvents(): array
|
||||
{
|
||||
return [
|
||||
AfterSheet::class => function (AfterSheet $event) {
|
||||
$event->sheet->getDelegate()->setRightToLeft(true);
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function headings(): array
|
||||
{
|
||||
return $this->head;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,303 @@
|
|||
<?php
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
use App\DB\Model;
|
||||
use Hekmatinasser\Verta\Verta;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: AraNote
|
||||
* Date: 12/04/2018
|
||||
* Time: 10:32 PM
|
||||
*/
|
||||
class Filter
|
||||
{
|
||||
|
||||
protected $type, $value, $crt, $name, $opt, $nl, $fn = ['where'], $args;
|
||||
/** @var Builder */
|
||||
public $query;
|
||||
|
||||
public $isArrayJson;
|
||||
|
||||
/**
|
||||
* Filter constructor.
|
||||
* @param $type
|
||||
* @param $text
|
||||
* @param $critical
|
||||
* @param $scope
|
||||
* @param $gt
|
||||
*/
|
||||
public function __construct(Builder $query, $data, $isFirst = false)
|
||||
{
|
||||
$this->query = $query;
|
||||
$this->isFirst = $isFirst;
|
||||
|
||||
foreach ($data as $key => $dt) {
|
||||
$this->{$key} = $dt;
|
||||
}
|
||||
if (isset($this->key) && starts_with($this->key, 'array')) {
|
||||
$this->isArrayJson = true;
|
||||
$this->key = str_replace_first('array@', '', $this->key);
|
||||
}
|
||||
|
||||
if (isset($this->key) && starts_with($this->key, 'object@')) {
|
||||
$this->key = str_replace_first('object@', '', $this->key);
|
||||
$this->key = str_replace('.', '->', $this->key);
|
||||
}
|
||||
// $this->field = $query->getModel()->convertColumns($this->field);
|
||||
$this->type = $data['type'] ?? 'text';
|
||||
$this->field = $data['field'] ?? null;
|
||||
$this->master = $data['master'] ?? null;
|
||||
$this->op = $data['op'] ?? null;
|
||||
$this->crt = $data['crt'] ?? null;
|
||||
$this->field = explode('.', $this->field);
|
||||
if (!is_null($this->master)) {
|
||||
$this->master = explode('.', $this->master);
|
||||
}
|
||||
$this->initFilter();
|
||||
}
|
||||
|
||||
public static function init($query, $data, $isFirst)
|
||||
{
|
||||
|
||||
return new Filter($query, $data, $isFirst);
|
||||
}
|
||||
|
||||
|
||||
public function getWhereHas()
|
||||
{
|
||||
if ($this->cr == 'or' && !$this->isFirst) return 'orWhereHas';
|
||||
return 'whereHas';
|
||||
}
|
||||
|
||||
public function run()
|
||||
{
|
||||
|
||||
if (sizeof($this->getNativeField()) > 1 && !Str::startsWith($this->getField(0), 'meta')) {
|
||||
$this->query->{$this->getWhereHas()}($this->snakeToCamelCase($this->getField(0)), function ($q) {
|
||||
if (sizeof($this->getNativeField()) > 2) {
|
||||
$q->whereHas($this->getField(1), function ($q2) {
|
||||
return $q2->{$this->getFn()}(...$this->args);
|
||||
});
|
||||
} else {
|
||||
return $q->{$this->getFn()}(...$this->args);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
$this->query->{$this->getFn()}(...$this->args);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
function snakeToCamelCase($string, $capitalizeFirstCharacter = false)
|
||||
{
|
||||
|
||||
$str = str_replace('_', '', ucwords($string, '_'));
|
||||
|
||||
if (!$capitalizeFirstCharacter) {
|
||||
$str = lcfirst($str);
|
||||
}
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
|
||||
public
|
||||
function getOpt()
|
||||
{
|
||||
return [
|
||||
'eq' => ($this->nl == 0) ? '=' : '<>',
|
||||
'gt' => ($this->nl == 0) ? '<' : '>',
|
||||
'lt' => ($this->nl == 0) ? '>' : '<',
|
||||
'bt' => ($this->nl == 0) ? '<>' : '='
|
||||
][$this->opt];
|
||||
}
|
||||
|
||||
public function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
|
||||
{
|
||||
|
||||
$str = str_replace('-', '', ucwords($string, '-'));
|
||||
|
||||
if (!$capitalizeFirstCharacter) {
|
||||
$str = lcfirst($str);
|
||||
}
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
public function getFn()
|
||||
{
|
||||
return $this->dashesToCamelCase(join('-', $this->fn));
|
||||
}
|
||||
|
||||
|
||||
public function getField($index= null)
|
||||
{
|
||||
if(is_null($index))
|
||||
return last($this->getNativeField());
|
||||
return $this->getNativeField()[$index];
|
||||
}
|
||||
|
||||
|
||||
public function getNativeField()
|
||||
{
|
||||
if (is_array($this->master)) {
|
||||
return $this->master;
|
||||
}
|
||||
return $this->field;
|
||||
}
|
||||
|
||||
|
||||
public function autoCorrectFieldName()
|
||||
{
|
||||
$map = config('maptable.convert_fields', []);
|
||||
if (Arr::has($map, $this->getNativeField())) {
|
||||
|
||||
$this->getNativeField()[sizeof($this->getNativeField()) - 1] = $map[Arr::last($this->getNativeField())];
|
||||
}
|
||||
|
||||
|
||||
$dc = config('maptable.convert_date', []);
|
||||
if ($this->type == 'date' && in_array($this->getField(), $dc)) {
|
||||
$this->value = Verta::parse($this->value)->datetime();
|
||||
}
|
||||
}
|
||||
|
||||
public function initFilter()
|
||||
{
|
||||
$this->autoCorrectFieldName();
|
||||
|
||||
if ($this->isArrayJson) {
|
||||
return ['and' => 'whereRaw', 'or' => 'orWhereRaw'][$this->crt];
|
||||
}
|
||||
if (is_null($this->args)) {
|
||||
$this->args = [];
|
||||
}
|
||||
|
||||
switch ($this->type) {
|
||||
case "date":
|
||||
$this->fn[] = 'date';
|
||||
break;
|
||||
}
|
||||
|
||||
switch ($this->op) {
|
||||
case "gt" :
|
||||
$this->args = [$this->getField(), '>', $this->value];
|
||||
break;
|
||||
case "lt" :
|
||||
$this->args = [$this->getField(), '<', $this->value];
|
||||
break;
|
||||
case "eq" :
|
||||
$this->args = [$this->getField(), $this->value];
|
||||
break;
|
||||
case "gte" :
|
||||
$this->args = [$this->getField(), '>=', $this->value];
|
||||
break;
|
||||
case "lte" :
|
||||
$this->args = [$this->getField(), '<=', $this->value];
|
||||
break;
|
||||
case "bet" :
|
||||
$this->fn[] = 'between';
|
||||
break;
|
||||
case "not" :
|
||||
$this->args = [$this->getField(), '<>', $this->value];
|
||||
break;
|
||||
case "nn" :
|
||||
$this->fn[] = 'not';
|
||||
$this->fn[] = 'null';
|
||||
$this->args = [$this->getField()];
|
||||
break;
|
||||
case "null" :
|
||||
$this->fn[] = 'null';
|
||||
// if (sizeof($this->field) > 1) {
|
||||
//
|
||||
// } else {
|
||||
//
|
||||
// }
|
||||
$this->args = [$this->getField()];
|
||||
break;
|
||||
case "sw" :
|
||||
$this->args = [$this->getField(), 'like', $this->value . '%'];
|
||||
break;
|
||||
case "ew" :
|
||||
$this->args = [$this->getField(), 'like', '%' . $this->value];
|
||||
break;
|
||||
case "has" :
|
||||
$this->args = [$this->getField(), 'like', '%' . $this->value . '%'];
|
||||
break;
|
||||
case "in" :
|
||||
$this->fn[] = ['in'];
|
||||
break;
|
||||
|
||||
}
|
||||
if (sizeof($this->args) == 0) {
|
||||
$this->args = [$this->getField(), $this->value];
|
||||
}
|
||||
|
||||
if ($this->cr == 'or' && !$this->isFirst) {
|
||||
array_unshift($this->fn, 'or');
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
protected function getArgs()
|
||||
{
|
||||
if ($this->isArrayJson) {
|
||||
if ($this->nl == 1) {
|
||||
return ["JSON_CONTAINS($this->key, '$this->value') = 0"];
|
||||
} elseif ($this->nl == 0) {
|
||||
return ["JSON_CONTAINS($this->key, '$this->value')"];
|
||||
}
|
||||
}
|
||||
|
||||
switch ($this->type) {
|
||||
case 'number':
|
||||
case 'date':
|
||||
$t = isset($this->key) ? [$this->key] : [$this->getLastField()];
|
||||
if ($this->nl < 2) {
|
||||
$t[] = $this->getOp();
|
||||
$t[] = $this->value;
|
||||
}
|
||||
return $t;
|
||||
break;
|
||||
case 'text':
|
||||
$t = isset($this->key) ? [$this->key] : [$this->getLastField()];
|
||||
|
||||
if ($this->nl == 0) {
|
||||
$t[] = 'LIKE';
|
||||
$t[] = '%' . $this->value . '%';
|
||||
} elseif ($this->nl == 1) {
|
||||
$t[] = 'NOT LIKE';
|
||||
$t[] = '%' . $this->value . '%';
|
||||
}
|
||||
return $t;
|
||||
break;
|
||||
case 'select':
|
||||
case 'switch':
|
||||
$t = isset($this->key) ? [$this->key] : [$this->getLastField()];
|
||||
if ($this->nl == 0) {
|
||||
$t[] = '=';
|
||||
$t[] = $this->value;
|
||||
} elseif ($this->nl == 1) {
|
||||
$t[] = '<>';
|
||||
$t[] = $this->value;
|
||||
}
|
||||
return $t;
|
||||
break;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
private function getLastField()
|
||||
{
|
||||
return Arr::last($this->getNativeField());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
|
||||
|
||||
class QuerySelector
|
||||
{
|
||||
public static function run(Request $request)
|
||||
{
|
||||
|
||||
if (!$request->has('action')) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
$input = $request->all();
|
||||
if (!isset($input['query']) && !isset($input['default'])) {
|
||||
return response()->json(null);
|
||||
}
|
||||
$result = QuerySelector::searchQuery($request->all());
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
public static function searchQuery($input)
|
||||
{
|
||||
|
||||
$conf = Arr::get(config('query'), $input['action'], null);
|
||||
// dd($conf);
|
||||
if (is_null($conf)) {
|
||||
return null;
|
||||
}
|
||||
$conf = (object)$conf;
|
||||
if (isset($conf->fn) && isset($input['query'])) {
|
||||
return call_user_func($conf->fn, $input['query'], $input['extra'] ?? null);
|
||||
}
|
||||
$cols = explode(',', $conf->cols);
|
||||
if (isset($input['query'])) {
|
||||
$query = $conf->model::where($cols[0], 'like', '%' . $input['query'] . '%');
|
||||
}
|
||||
|
||||
|
||||
if (isset($input['default'])) {
|
||||
if (is_array($input['default'])) {
|
||||
$query = $conf->model::whereIn('id', $input['default']);
|
||||
} else {
|
||||
$query = $conf->model::whereId($input['default']);
|
||||
}
|
||||
}
|
||||
if (isset($conf->where)) {
|
||||
foreach ($conf->where as $ww) {
|
||||
$query->where(...$ww);
|
||||
}
|
||||
}
|
||||
if (isset($conf->select)) {
|
||||
$select = (is_callable($conf->select)) ? call_user_func($conf->select) : $conf->select;
|
||||
return $query->select($select)->limit(20)->get()->toArray();
|
||||
} else {
|
||||
return $query->select(array_merge(['id'], $cols))->limit(20)->get()->toArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: AraNote
|
||||
* Date: 12/04/2018
|
||||
* Time: 10:34 PM
|
||||
*/
|
||||
class Scope
|
||||
{
|
||||
public $items, $query;
|
||||
|
||||
/**
|
||||
* Scope constructor.
|
||||
* @param $items
|
||||
*/
|
||||
public function __construct($query, $items)
|
||||
{
|
||||
$this->query = $query;
|
||||
$this->items = $items;
|
||||
}
|
||||
|
||||
|
||||
public static function init($query, $items)
|
||||
{
|
||||
return new Scope($query, $items);
|
||||
}
|
||||
|
||||
|
||||
public function run()
|
||||
{
|
||||
foreach ($this->items as $index => $item) {
|
||||
Filter::init($this->query, $item, $index == 0)->run();
|
||||
}
|
||||
// dd($this->query->toSql());
|
||||
return $this->query;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
namespace App\DB\Te;
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: AraNote
|
||||
* Date: 12/04/2018
|
||||
* Time: 10:32 PM
|
||||
*/
|
||||
class Search
|
||||
{
|
||||
|
||||
protected $cols, $text, $query;
|
||||
|
||||
public static function query(&$query, $cols, $search)
|
||||
{
|
||||
$query->where(function ($q) use ($cols, $search) {
|
||||
$first = true;
|
||||
foreach ($cols as $col) {
|
||||
if (self::hasJoin($col)) {
|
||||
$exp = explode('.', $col);
|
||||
if (sizeof($exp) > 2) {
|
||||
if ($first){
|
||||
$whereHas = 'whereHas';
|
||||
}else{
|
||||
$whereHas = 'orWhereHas';
|
||||
}
|
||||
$q->$whereHas
|
||||
($exp[0], function ($q) use ($exp, $search) {
|
||||
return $q->whereHas($exp[1], function ($q2) use ($exp, $search) {
|
||||
|
||||
// return $q2->where($exp[2], 'LIKE', '%' . $search . '%');
|
||||
return $q2->whereRaw('lower(`'.$exp[2].'`) like ?', ['%' . strtolower($search) . '%']);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
if ($first){
|
||||
$whereHas1 = 'whereHas';
|
||||
}else{
|
||||
$whereHas1 = 'orWhereHas';
|
||||
}
|
||||
$q->$whereHas1
|
||||
// $q->{($first) ? 'whereHas' : 'orWhereHas'}
|
||||
($exp[0], function ($q) use ($exp, $search) {
|
||||
return $q->whereRaw('lower(`'.$exp[1].'`) like ?', ['%' . strtolower($search) . '%']);
|
||||
// return $q->where($exp[1], 'LIKE', '%' . $search . '%');
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if ($first){
|
||||
$where = 'whereRaw';
|
||||
}else{
|
||||
$where = 'orWhereRaw';
|
||||
}
|
||||
// return $q->whereRaw('lower(`'.$col.'`) like ?', ['%' . strtolower($search) . '%']);
|
||||
$q->$where('lower(`'.$col.'`) like ?', ['%' . strtolower($search) . '%']);
|
||||
// $q->{($first) ? 'where' : 'orWhere'}($col, 'LIKE', '%' . $search . '%');
|
||||
// $q->{($first) ? 'whereRaw ' : 'orWhereRaw '}($col, 'LIKE', '%' . $search . '%');
|
||||
}
|
||||
if ($first) {
|
||||
$first = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static function hasJoin($col)
|
||||
{
|
||||
return sizeof(explode('.', $col)) > 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
<?php
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
use App\DB\Model;
|
||||
use App\Excel\TableExport;
|
||||
use App\User;
|
||||
use Carbon\Carbon;
|
||||
use Hekmatinasser\Verta\Verta;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\View;
|
||||
use Illuminate\Support\Str;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
class TableEngine
|
||||
{
|
||||
/////////
|
||||
protected $max = 5000, $cols, $type, $selection, $selectionHidden;
|
||||
|
||||
/** @var Search */
|
||||
protected $search;
|
||||
|
||||
/** @var Scope */
|
||||
protected $scope;
|
||||
|
||||
/** @var Model */
|
||||
protected $query;
|
||||
|
||||
|
||||
/** @var TableEngineInput */
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* TableEngine constructor.
|
||||
* @param $filters
|
||||
*/
|
||||
public function __construct(&$query, $inp, $i18nPrefix)
|
||||
{
|
||||
$this->query = $query;
|
||||
$this->i18nPrefix = $i18nPrefix;
|
||||
$this->input = TableEngineInput::create($inp);
|
||||
$this->filterQuery();
|
||||
|
||||
}
|
||||
|
||||
public static function create(&$query, $inp, $i18nPrefix = '')
|
||||
{
|
||||
return new TableEngine($query, $inp, $i18nPrefix);
|
||||
}
|
||||
|
||||
|
||||
public static function viewPrint($id)
|
||||
{
|
||||
view()->addNamespace('TE', app_path('DB/Te'));
|
||||
$json = json_decode(Storage::disk('public')->get($id . '.json', ""));
|
||||
return view('TE::views.print', ['records' => $json->records, 'meta' => $json->meta, 'Arr' => Arr::class]);
|
||||
}
|
||||
|
||||
public function initSearch($cols)
|
||||
{
|
||||
if ($this->input->hasSearch()) {
|
||||
Search::query($this->query, $cols, $this->input->search);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function hidden($cols)
|
||||
{
|
||||
$this->selection = $cols;
|
||||
$this->selectionHidden = true;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function select($cols)
|
||||
{
|
||||
$this->selection = $cols;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function batchOperation($func)
|
||||
{
|
||||
if ($this->input->hasSelectCommand() && $this->input->hasSelectItems()) {
|
||||
call_user_func($func,
|
||||
(object)['command' => $this->input->selectCommand,
|
||||
'items' => $this->input->selectItems]
|
||||
);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
public function execute()
|
||||
{
|
||||
$this->query->get();
|
||||
return $this->query;
|
||||
}
|
||||
|
||||
public function total()
|
||||
{
|
||||
$this->query->get();
|
||||
return $this->query;
|
||||
}
|
||||
|
||||
public function export(&$export = null)
|
||||
{
|
||||
|
||||
|
||||
$ret = [
|
||||
'query' => [
|
||||
'limit' => $this->input->limit,
|
||||
'filters' => $this->input->filters,
|
||||
'filtersOpt' => $this->input->filtersOpt,
|
||||
'search' => $this->input->search,
|
||||
'key' => $this->input->key,
|
||||
'select' => $this->input->columns,
|
||||
'total' => $this->query->count(),
|
||||
'sort' => $this->input->sort,
|
||||
'page' => $this->input->page
|
||||
]
|
||||
];
|
||||
$this->sortQuery();
|
||||
|
||||
if (!($this->input->op == 'excel' || $this->input->op == 'json' || $this->input->op == 'print')) {
|
||||
$this->query
|
||||
->limit($this->input->limit)
|
||||
->offset(($this->input->page - 1) * $this->input->limit);
|
||||
}
|
||||
|
||||
|
||||
if (is_null($this->selectionHidden)) {
|
||||
$ret['rows'] = $this->query->select($this->selection)->get();
|
||||
|
||||
} else {
|
||||
$e = $this->query->get();
|
||||
foreach ($e as $model) {
|
||||
$model->addHidden($this->selection);
|
||||
};
|
||||
|
||||
|
||||
$ret['rows'] = $e->toArray();
|
||||
}
|
||||
if ($this->input->op == 'excel' || $this->input->op == 'json' || $this->input->op == 'print') {
|
||||
if ($this->input->op == 'excel') {
|
||||
$time = md5(time()) . '.xlsx';
|
||||
$ret['url'] = url('storage/excel/excel/' . $time);
|
||||
Excel::store(new ExcelCollection($ret['rows'], $this->input->getShowColumns($this->i18nPrefix)), 'excel/' . $time);
|
||||
} else if ($this->input->op == 'json' || $this->input->op == 'print') {
|
||||
$json = new ExcelCollection($ret['rows'], $this->input->getShowColumns($this->i18nPrefix));
|
||||
$time = md5(time()) . '.json';
|
||||
$exp = [
|
||||
'records' => $json->collection()->toArray(),
|
||||
'meta' => [
|
||||
'title' => $this->input->reportTitle,
|
||||
'columns' => $this->input->columnTitles,
|
||||
'created_at' => Verta::now()->formatJalaliDatetime()
|
||||
]
|
||||
];
|
||||
Storage::disk('public')->put($time, json_encode($exp));
|
||||
if ($this->input->op == 'print') {
|
||||
$ret['url'] = url('site/te/print/' . Str::before($time, '.json'));
|
||||
} else {
|
||||
$ret['url'] = url('storage/' . $time);
|
||||
}
|
||||
}
|
||||
unset($ret['rows']);
|
||||
}
|
||||
if (is_null($export)) {
|
||||
return $ret;
|
||||
}
|
||||
$export = $ret;
|
||||
}
|
||||
|
||||
|
||||
protected function sortQuery()
|
||||
{
|
||||
|
||||
if ($this->input->hasSort()) {
|
||||
|
||||
$r = explode('.', $this->input->sort->key);
|
||||
if (sizeof($r) > 1) {
|
||||
$inp = $this->input->sort->order;
|
||||
$this->query->with([$r[0] => function ($q) use ($r, $inp) {
|
||||
return $q->orderBy($r[1], ($this->input->sort->order == 'descending') ? 'DESC' : 'ASC');
|
||||
}]);
|
||||
} else {
|
||||
$this->query->orderBy(
|
||||
$this->input->sort->key,
|
||||
($this->input->sort->order == 'descending') ? 'DESC' : 'ASC');
|
||||
}
|
||||
} else {
|
||||
$this->query->orderBy('id', 'DESC');
|
||||
}
|
||||
}
|
||||
|
||||
protected function filterQuery()
|
||||
{
|
||||
if ($this->input->hasFilters()) {
|
||||
$this->query->where(function ($q) {
|
||||
return Scope::init($q, $this->input->filters)->run();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected function getWhere($op)
|
||||
{
|
||||
return Arr::get(['or' => 'orWhere', 'and' => 'where'], $op, 'where');
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: AraNote
|
||||
* Date: 18/04/2018
|
||||
* Time: 06:27 PM
|
||||
*/
|
||||
|
||||
namespace App\DB\Te;
|
||||
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class TableEngineInput
|
||||
{
|
||||
|
||||
public $columns;
|
||||
public $columnTitles;
|
||||
public $reportTitle;
|
||||
public $filters;
|
||||
public $filtersOpt;
|
||||
public $selectCommand;
|
||||
public $selectItems;
|
||||
public $limit = 1000;
|
||||
public $page;
|
||||
public $key;
|
||||
public $sort;
|
||||
public $search;
|
||||
public $op;
|
||||
|
||||
/**
|
||||
* TableEngineInput constructor.
|
||||
*/
|
||||
public function __construct($input)
|
||||
{
|
||||
if (isset($input['select'])) {
|
||||
$this->columns = array_filter($input['select'], function ($item) {
|
||||
return $item != 'opt';
|
||||
});
|
||||
}
|
||||
|
||||
if (isset($input['titles'])) {
|
||||
$this->columnTitles = $input['titles'];
|
||||
}
|
||||
if (isset($input['report_title'])) {
|
||||
$this->reportTitle = $input['report_title'];
|
||||
}
|
||||
|
||||
if (isset($input['filters'])) {
|
||||
$this->filters = $input['filters'];
|
||||
}
|
||||
|
||||
if (isset($input['limit'])) {
|
||||
$this->limit = $input['limit'];
|
||||
}
|
||||
|
||||
if (isset($input['page'])) {
|
||||
$this->page = $input['page'];
|
||||
}
|
||||
|
||||
if (isset($input['search'])) {
|
||||
$this->search = $input['search'];
|
||||
}
|
||||
|
||||
if (isset($input['text_search'])) {
|
||||
$this->search = $input['text_search'];
|
||||
}
|
||||
|
||||
if (isset($input['order'])) {
|
||||
$e = substr($input['order'], 0, 1);
|
||||
$col = substr($input['order'], 1);
|
||||
|
||||
$this->sort = (object)[
|
||||
'key' => $col,
|
||||
'order' => $e == '-' ? 'descending' : 'asc'
|
||||
];
|
||||
}
|
||||
|
||||
if (isset($input['filtersOpt'])) {
|
||||
$this->filtersOpt = $input['filtersOpt'];
|
||||
}
|
||||
|
||||
if (isset($input['selectCommand'])) {
|
||||
$this->selectCommand = $input['selectCommand'];
|
||||
}
|
||||
|
||||
if (isset($input['selectItems'])) {
|
||||
$this->selectItems = $input['selectItems'];
|
||||
}
|
||||
|
||||
if (isset($input['key'])) {
|
||||
$this->key = $input['key'];
|
||||
}
|
||||
if (isset($input['op'])) {
|
||||
$this->op = $input['op'];
|
||||
$this->page = 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static function create($input)
|
||||
{
|
||||
if (is_null($input)) {
|
||||
return null;
|
||||
}
|
||||
return new TableEngineInput($input);
|
||||
}
|
||||
|
||||
|
||||
public function hasSearch()
|
||||
{
|
||||
return !is_null($this->search);
|
||||
}
|
||||
|
||||
|
||||
public function hasFilters()
|
||||
{
|
||||
return !is_null($this->filters);
|
||||
}
|
||||
|
||||
public function hasCols()
|
||||
{
|
||||
return !is_null($this->columns);
|
||||
}
|
||||
|
||||
public function hasLimit()
|
||||
{
|
||||
return !is_null($this->limit);
|
||||
}
|
||||
|
||||
public function hasSort()
|
||||
{
|
||||
return !is_null($this->sort);
|
||||
}
|
||||
|
||||
|
||||
public function hasSelectCommand()
|
||||
{
|
||||
return !is_null($this->selectCommand);
|
||||
}
|
||||
|
||||
public function hasSelectItems()
|
||||
{
|
||||
return !is_null($this->selectItems);
|
||||
}
|
||||
|
||||
|
||||
public function getShowColumns($i18nPrefix)
|
||||
{
|
||||
$exp = [];
|
||||
foreach ($this->columns as $col) {
|
||||
if (isset($this->columnTitles[$col])) {
|
||||
$exp[$col] = $this->columnTitles[$col];
|
||||
} else {
|
||||
$exp[$col] = trans('field.' . $i18nPrefix . $col);
|
||||
}
|
||||
}
|
||||
return $exp;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
@font-face {
|
||||
font-family: 'Vazir', sans-serif;
|
||||
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Vazir', sans-serif;
|
||||
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
body, *:not(i) {
|
||||
font-family: 'Vazir', sans-serif;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
.container{max-width:980px;margin:auto;padding:10px}.body,header{border:1px solid #8080806e;padding:10px;border-radius:4px}.body{margin-top:10px}table{width:100%}table td,table th{text-align:right}table td:not(:last-child),table th:not(:last-child){border-left:1px solid #d6d6d6}table td:not(:first-child),table th:not(:first-child){padding-right:10px}table th{border-bottom:2px solid grey}table tr:not(:last-child) td{border-bottom:1px solid #d6d6d6}table tr:not(:last-child):nth-child(odd) td{background-color:#f7f7f7}.flex{display:flex}.fl-50{flex:50}.item .key{font-size:.9em}.item .key::after{content:" : "}.item .value{font-weight:800}
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
.container {
|
||||
max-width: 980px;
|
||||
margin: auto;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
header, .body {
|
||||
border: 1px solid #8080806e;
|
||||
padding: 10px;
|
||||
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.body {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
|
||||
th, td {
|
||||
text-align: right;
|
||||
&:not(:last-child) {
|
||||
border-left: 1px solid #d6d6d6;
|
||||
}
|
||||
&:not(:first-child) {
|
||||
padding-right: 10px;
|
||||
}
|
||||
}
|
||||
th {
|
||||
border-bottom: 2px solid grey;
|
||||
}
|
||||
|
||||
tr:not(:last-child) {
|
||||
td {
|
||||
border-bottom: 1px solid #d6d6d6;
|
||||
}
|
||||
&:nth-child(odd) {
|
||||
td {
|
||||
background-color: #f7f7f7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.fl-50 {
|
||||
flex: 50;
|
||||
}
|
||||
|
||||
.item {
|
||||
.key {
|
||||
font-size: 0.9em;
|
||||
&::after {
|
||||
content: " : ";
|
||||
}
|
||||
}
|
||||
.value {
|
||||
font-weight: 800;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
|
||||
return [
|
||||
'convert_fields' => [
|
||||
'caj' => 'created_at',
|
||||
'type_str' => 'type',
|
||||
'sts_str' => 'sts',
|
||||
'uaj' => 'updated_at',
|
||||
],
|
||||
'convert_date' => [
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'deleted_at'
|
||||
]
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
<!doctype html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ env('APP_NAME') }}</title>
|
||||
<link rel="stylesheet" href="{{url('assets/fonts/fonts.css')}}">
|
||||
<link rel="stylesheet" href="{{url('assets/css/print.css')}}">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<div style="text-align: center;font-size: 1.2em">{{config('app.name')}}</div>
|
||||
<hr>
|
||||
<div class="flex">
|
||||
<div class="item fl-50">
|
||||
<span class="key">عنوان گزارش</span>
|
||||
<span class="value">{{$title}}</span>
|
||||
</div>
|
||||
<div class="item fl-50">
|
||||
<span class="key">تاریخ گزارش</span>
|
||||
<span class="value">{{\Morilog\Jalali\Facades\jDate::forge()->format('Y/m/d-H:m')}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex">
|
||||
<div class="item fl-50">
|
||||
<span class="key">گزارش گیرنده</span>
|
||||
<span class="value">{{\Illuminate\Support\Facades\Auth::user()->name}}</span>
|
||||
</div>
|
||||
<div class="item fl-50">
|
||||
<span class="key">تعداد رکورد ها</span>
|
||||
<span class="value">{{sizeof($data['rows'])}}</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="body">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
@foreach($data['cols'] as $col)
|
||||
<th>@lang('cols.'.str_replace('.','_',$col))</th>
|
||||
@endforeach
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach($data['rows'] as $row)
|
||||
<tr>
|
||||
@foreach($data['cols'] as $col)
|
||||
@if(!is_array(array_get($row, $col, '')))
|
||||
<td>{{array_get($row, $col, '')}}</td>
|
||||
@else
|
||||
<td>{{join(',' , array_get($row, $col, ''))}}</td>
|
||||
@endif
|
||||
@endforeach
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
return [
|
||||
'sample_one' => [
|
||||
'model' => \App\MyModel::class,
|
||||
'cols' => "name,code",
|
||||
'select' => ['id as value', 'name as label']
|
||||
],
|
||||
'sample_two' => [
|
||||
'fn' => function ($query) {
|
||||
return \App\DB\MyModel::whereHas('cls', function ($q) {
|
||||
return $q->where('term_id', 2)->where('teacher_id', 1);
|
||||
})
|
||||
->select(['id as value', 'title as label'])
|
||||
->where('title', 'LIKE', '%' . $query . '%')
|
||||
->orWhere('code', 'LIKE', '%' . $query . '%')
|
||||
->get()
|
||||
->toArray();
|
||||
},
|
||||
],
|
||||
'sample_three' => [
|
||||
'model' => \App\DB\MyModel::class,
|
||||
'cols' => "title",
|
||||
'where' => [['sts', '>', '0']],
|
||||
'select' => ['id as value', 'title as label']
|
||||
],
|
||||
'sample_four' => [
|
||||
'model' => \App\DB\MyModel::class,
|
||||
'cols' => "title",
|
||||
'where' => [['w', 'course_level']],
|
||||
'select' => ['id as value', 'title as label']
|
||||
]
|
||||
];
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
<!doctype html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>{{ config('app.name') }}</title>
|
||||
<link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@v29.0.1/dist/font-face.css" rel="stylesheet" type="text/css" />
|
||||
|
||||
<style>
|
||||
<?php echo file_get_contents(app_path('DB/Te/assets/font.css'))?>
|
||||
</style>
|
||||
<style>
|
||||
<?php echo file_get_contents(app_path('DB/Te/assets/print.css'))?>
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<div style="text-align: center;font-size: 1.2em">{{config('app.name')}}</div>
|
||||
<hr>
|
||||
<div class="flex">
|
||||
<div class="item fl-50">
|
||||
<span class="key">عنوان گزارش</span>
|
||||
<span class="value">{{$meta->title}}</span>
|
||||
</div>
|
||||
<div class="item fl-50">
|
||||
<span class="key">تاریخ گزارش</span>
|
||||
<span class="value">{{$meta->created_at}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex">
|
||||
<div class="item fl-50">
|
||||
<span class="key">تعداد رکورد ها</span>
|
||||
<span class="value">{{sizeof($records)}}</span>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div class="body">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
@foreach($meta->columns as $col)
|
||||
<th>{{$col}}</th>
|
||||
@endforeach
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach($records as $row)
|
||||
<tr>
|
||||
@foreach($meta->columns as $key=>$val)
|
||||
@if(!is_array($Arr::get((array)$row, $key, '')))
|
||||
<td>{{$Arr::get((array)$row, $key, '')}}</td>
|
||||
@else
|
||||
<td>{{join(',' , $Arr::get((array)$row, $key, ''))}}</td>
|
||||
@endif
|
||||
@endforeach
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
window.print();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* 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 for validation exceptions.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
$telegram_token = '7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k';
|
||||
Http::get("https://api.wwwapp.ir/telegran_send.php", [
|
||||
'botToken' => $telegram_token,
|
||||
'chatId' => "-1002312965723",
|
||||
'message' => " لیمان جدید ".$e->getMessage()."\n\n".$e->getFile() ."\n\n". "line".$e->getLine(),
|
||||
]);
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Cnt;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
|
||||
class AdminConstController extends Controller
|
||||
{
|
||||
public function storeNumberToSendMassageInOrder(Request $request)
|
||||
{
|
||||
try {
|
||||
|
||||
if (Cnt::where('key', 'numberToSendMassageInOrder')->where('value', $request->phone)->exists()) {
|
||||
return response()->json(['error' => 'Duplicate number'], 409); // 409 Conflict status code
|
||||
}
|
||||
|
||||
// Create a new Cnt instance
|
||||
$cnt = new Cnt();
|
||||
$cnt->key = "numberToSendMassageInOrder";
|
||||
$cnt->value = $request->phone;
|
||||
$cnt->title_fa = $request->status;
|
||||
$cnt->save();
|
||||
|
||||
// Return a success response
|
||||
return response()->json(['id' => $cnt->id], 201);
|
||||
} catch (\Exception $e) {
|
||||
// Handle any errors that may occur
|
||||
return response()->json(['error' => 'Failed to save phone number', 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function getNumberToSendMassageInOrder()
|
||||
{
|
||||
$cnts = Cnt::where("key", "numberToSendMassageInOrder")
|
||||
->select("id", "title_fa as status", "value as phone")
|
||||
->get();
|
||||
|
||||
return response()->json($cnts);
|
||||
}
|
||||
public function putNumberToSendMassageInOrder(Request $request)
|
||||
{
|
||||
try {
|
||||
// if (Cnt::where('key', 'numberToSendMassageInOrder')->where('value', $request->phone)->exists()) {
|
||||
// return response()->json(['error' => 'Duplicate number'], 400);
|
||||
// } erorr in self number
|
||||
$cnt = Cnt::find($request->id);
|
||||
if (!$cnt) {
|
||||
return response()->json(['error' => 'Record not found'], 404);
|
||||
}
|
||||
// Create a new Cnt instance
|
||||
$cnt->key = "numberToSendMassageInOrder";
|
||||
$cnt->value = $request->phone;
|
||||
$cnt->title_fa = $request->status;
|
||||
$cnt->save();
|
||||
|
||||
// Return a success response
|
||||
return response()->json(['message' => 'Phone number changed successfully'], 200);
|
||||
} catch (\Exception $e) {
|
||||
// Handle any errors that may occur
|
||||
return response()->json(['error' => 'Failed to save phone number', 'message' => $e->getMessage()], 500);
|
||||
}
|
||||
}
|
||||
public function deleteNumberToSendMassageInOrder($id)
|
||||
{
|
||||
$cnt = Cnt::find($id);
|
||||
|
||||
if ($cnt) {
|
||||
$cnt->delete();
|
||||
return response()->json(['message' => 'Phone number deleted successfully'], 200); // 200 OK status code
|
||||
} else {
|
||||
return response()->json(['message' => 'Phone number not found'], 404); // 404 Not Found status code
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,726 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperPackageController;
|
||||
use App\Http\Controllers\Admin\OrderController as AdminOrderController;
|
||||
use App\Http\Controllers\Admin\FinDocController as AdminFinController;
|
||||
use App\Http\Controllers\Admin\FinDocTallaController as AdminFinDocTallaController;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\FinancialDoc;
|
||||
use App\Models\FinDocTalla;
|
||||
use App\Models\Message;
|
||||
use App\Models\Order;
|
||||
use App\Models\User;
|
||||
use App\Models\PackageProduct;
|
||||
use App\Models\Product;
|
||||
use App\Models\Price;
|
||||
use Illuminate\Http\Request;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
use App\DB\Te\TableEngine;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
use App\Classes\SimpleXLSXGen;
|
||||
use App\Classes\PhpXlsxGenerator;
|
||||
use App\Classes\SimpleCSVGen;
|
||||
|
||||
class AdminDashboardController extends Controller
|
||||
{
|
||||
private $null;
|
||||
|
||||
public function listPageDExl()
|
||||
{
|
||||
$customers = Customer::all()->toArray();
|
||||
$headers = array_keys($customers[0] ?? []);
|
||||
array_unshift($customers, $headers);
|
||||
foreach ($customers as &$customer) {
|
||||
if (isset($customer['mobile'])) {
|
||||
$customer['mobile'] = ' ' . $customer['mobile'] . ' ';
|
||||
}
|
||||
}
|
||||
return response()->stream(function () use ($customers) {
|
||||
$output = fopen('php://output', 'w');
|
||||
fwrite($output, "\xEF\xBB\xBF");
|
||||
foreach ($customers as $row) {
|
||||
fputcsv($output, $row);
|
||||
}
|
||||
fclose($output);
|
||||
}, 200, [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8', // نوع محتوا
|
||||
'Content-Disposition' => 'attachment; filename="customers.csv"', // برای دانلود فایل
|
||||
'Cache-Control' => 'no-cache', // جلوگیری از کش شدن فایل
|
||||
'Pragma' => 'no-cache', // جلوگیری از کش شدن فایل
|
||||
]);
|
||||
}
|
||||
|
||||
public function messagesTable(Request $request)
|
||||
{
|
||||
// استخراج دادهها از جدول Messages
|
||||
$records = Message::whereNotNull('sms'); // فرض بر این است که نام فیلد صحیح 'sms' است
|
||||
|
||||
// تنظیمات TableEngine
|
||||
$table = TableEngine::create($records, $request->all())
|
||||
->initSearch([]) // تنظیم فیلدهای جستجو در صورت نیاز
|
||||
->select([
|
||||
'id', 'sms', 'receiver', // لیست فیلدهای مورد نیاز را اضافه کنید
|
||||
// سایر فیلدها و محاسبات اضافی در صورت نیاز
|
||||
]);
|
||||
// برگرداندن دادهها در قالب JSON
|
||||
return response()->json($table->export());
|
||||
}
|
||||
|
||||
public function getBalance(Request $request)
|
||||
{
|
||||
$response = [];
|
||||
$savedData=[];
|
||||
|
||||
$startDate = Carbon::parse($request->startDate)->startOfDay();
|
||||
$endDate = Carbon::parse($request->endDate)->endOfDay();
|
||||
|
||||
$startDateJalali = $request->fromDate ?? Jalalian::forge($startDate)->format('Y-m-d');
|
||||
$endDateJalali = $request->fromDate ?? Jalalian::forge($endDate)->format('Y-m-d');
|
||||
$DoNewMoshtari = [100, "", $startDateJalali, $endDateJalali,];
|
||||
$response['$startDateJalali'] = $startDateJalali;
|
||||
|
||||
[$reizhesabs = Http::withoutVerifying()
|
||||
->timeout(2)
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoListAsnad' => $DoNewMoshtari
|
||||
])->json(), $DoNewMoshtari];
|
||||
// return $s;
|
||||
|
||||
|
||||
|
||||
// foreach ($reizhesabs as &$rizhesab) {
|
||||
//
|
||||
//
|
||||
//// $telegram_token = '7467099619:AAF2V6yYcbAb8oSIRSCyH5i2GKfdWVO3a7k';
|
||||
//// Http::get("https://api.wwwapp.ir/telegran_send.php", [
|
||||
//// 'botToken' => $telegram_token,
|
||||
//// 'chatId' => "-1002312965723",
|
||||
//// 'message' => " ته حساب::: " . $rizhesab["NO"],
|
||||
//// ]);
|
||||
//
|
||||
// if (isset($rizhesab["NO"])) {
|
||||
//
|
||||
// if ($rizhesab["NO"] == "فروش طلا" or $rizhesab["NO"] == "خريد طلا") {
|
||||
//
|
||||
// if (!Order::where(['finance_code' => $rizhesab['Factor_Code']])->exists()) {
|
||||
// $CuF = Customer::where("tahesab_id", $rizhesab["MCode"])->first();
|
||||
//
|
||||
// $request = new Request([
|
||||
// "finance_code" => $rizhesab["Factor_Code"],
|
||||
// "amount" => $rizhesab["Vazn"],
|
||||
// 'customer_id' => $CuF->id,
|
||||
// "cash" => abs($rizhesab['Mali']),
|
||||
// "description" => $rizhesab["Sharh1"],
|
||||
// "direction" => ($rizhesab["Mali"] ) > 0 ? 1 : 2,
|
||||
// "pay_at" => Jalalian::fromFormat('Y/m/d', $rizhesab["Tarikh"])->toCarbon()->format('Y-m-d H:i:s'),// shmsi "1403/12/12" to miladi "2025-12-12 10:50:50"
|
||||
// "price" => $rizhesab["Mazaneh"],
|
||||
// "product_id" => 2,
|
||||
// "method" => 'TAHESAB',
|
||||
//
|
||||
// ]);
|
||||
// $AdminOrderController = new AdminOrderController();
|
||||
// $newOrder = $AdminOrderController->store($request);
|
||||
// $savedData[]['$rizhesab'] =$rizhesab;
|
||||
// $savedData[]['$newOrder'] =$newOrder;
|
||||
//// $savedData[]['t'] ="فروش طلا";
|
||||
// }
|
||||
//
|
||||
// }
|
||||
// if ($rizhesab["NO"] == "واريز نقد به بانک (از مشتري)" or $rizhesab["NO"] == "برداشت نقد از بانک (به مشتري)") {
|
||||
//
|
||||
// if (!FinancialDoc::where(['finance_code' => $rizhesab['Factor_Code']])->exists()) {
|
||||
// $CuF = Customer::where("tahesab_id", $rizhesab["MCode"])->first();
|
||||
//
|
||||
// if($CuF){
|
||||
// $request = new Request([
|
||||
// 'amount' => abs($rizhesab['Mali']),
|
||||
// 'customer_id' => $CuF->id,
|
||||
// 'date_at' => Jalalian::fromFormat('Y/m/d', $rizhesab["Tarikh"])->toCarbon()->format('Y-m-d H:i:s'),
|
||||
// 'receive_account_number' => 'TAHESAB',
|
||||
// 'receive_bank' => 'TAHESAB',
|
||||
// 'receive_bank_card' => 'TAHESAB',
|
||||
// 'receive_name' => 'TAHESAB',
|
||||
// 'send_account_number' => 'TAHESAB',
|
||||
// 'send_bank' => $rizhesab['Name_Bank'],
|
||||
// "product_id" => 2,
|
||||
// 'id' => $rizhesab['Sh_Factor'],
|
||||
// 'type' => ($rizhesab['NO']=="برداشت نقد از بانک (به مشتري)" )? 2 : 1,
|
||||
// 'track_number' => $rizhesab['Sh_Cheq'],
|
||||
// 'finance_code' => $rizhesab['Factor_Code'],
|
||||
// 'finance_Sh_factor' => $rizhesab['Sh_Factor'],
|
||||
//// 'description'=>$rizhesab['description']
|
||||
//
|
||||
// ]);
|
||||
// }
|
||||
//
|
||||
// $AdminFinController = new AdminFinController();
|
||||
// $savedData[]['$newFinDoc'] = $createdFin = $AdminFinController->store($request);
|
||||
// $savedData[]['$newFinDocV'] = $AdminFinController->verify($createdFin->id);
|
||||
// $savedData[]['$rizhesab'] =$rizhesab;
|
||||
//// $savedData[]['t'] ="واريز نقد به بانک (از مشتري)" ;
|
||||
//
|
||||
// }
|
||||
// }
|
||||
// if ($rizhesab["NO"] == "خروج آبشده" or $rizhesab["NO"] == "ورود آبشده") {
|
||||
// if (!FinDocTalla::where(['finance_code' => $rizhesab['Factor_Code']])->exists()) {
|
||||
// $CuF = Customer::where("tahesab_id", $rizhesab["MCode"])->first();
|
||||
//
|
||||
// if($CuF){
|
||||
// $request = new Request([
|
||||
// 'ang' => $rizhesab['Sh_Sharti'],
|
||||
// 'ayar' => $rizhesab['Ayar'],
|
||||
// 'customer_id' => $CuF->id,
|
||||
// 'date_at' => Jalalian::fromFormat('Y/m/d', $rizhesab["Tarikh"])->toCarbon()->format('Y-m-d H:i:s'),
|
||||
// 'description' => $rizhesab['Sharh1'],
|
||||
// 'lab' => $rizhesab['Name_az'],
|
||||
// 'product_id'=>2,
|
||||
// 'weight' => $rizhesab['Vazn'],
|
||||
// 'type' =>($rizhesab['NO'] == "خروج آبشده")? 1 : 2,
|
||||
// 'finance_code' => $rizhesab['Factor_Code'],
|
||||
// 'finance_Sh_factor' => $rizhesab['Sh_Factor'],
|
||||
// ]);
|
||||
// }
|
||||
//
|
||||
// $AdminFinDocTallaController = new FinDocTallaController();
|
||||
// $savedData[]['$newFinDoc'] = $AdminFinDocTallaControllerR = $AdminFinDocTallaController->store($request);
|
||||
// $newFinTallaDocData = json_decode( $AdminFinDocTallaControllerR->content(), true);
|
||||
// $savedData[]['$newFinDocV'] = $AdminFinDocTallaController->verify($newFinTallaDocData['id']);
|
||||
// $savedData[]['$rizhesab'] =$rizhesab;
|
||||
//// $savedData[]['t'] ="خروج آبشده" ;
|
||||
// }
|
||||
// }
|
||||
// if($rizhesab["NO"] == "خروج متفرقه" or $rizhesab["NO"] == "ورود متفرقه"){
|
||||
// if(!FinDocTalla::where(['finance_code' => $rizhesab['Factor_Code']])->exists()){
|
||||
// $CuF = Customer::where("tahesab_id", $rizhesab["MCode"])->first();
|
||||
//
|
||||
// if($CuF){
|
||||
// $request=new Request([
|
||||
// 'ayar' => $rizhesab['Ayar'],
|
||||
// 'weight' => $rizhesab['Vazn'],
|
||||
// 'customer_id' => $CuF->id,
|
||||
// 'description' => $rizhesab['Sharh1'],
|
||||
// 'date_at' => Jalalian::fromFormat('Y/m/d', $rizhesab["Tarikh"])->toCarbon()->format('Y-m-d H:i:s'),
|
||||
// 'description' => $rizhesab['Sharh1'],
|
||||
// 'product_id'=>2,
|
||||
// 'type' =>($rizhesab['NO'] == "خروج متفرقه")? 1 : 2,
|
||||
// 'finance_code' => $rizhesab['Factor_Code'],
|
||||
// 'finance_Sh_factor' => $rizhesab['Sh_Factor'],
|
||||
// ]);
|
||||
// }
|
||||
//
|
||||
// $AdminFinDocTallaController = new FinDocTallaController();
|
||||
// $savedData[]['$newFinDoc'] = $AdminFinDocTallaControllerR = $AdminFinDocTallaController->store($request);
|
||||
// $newFinTallaDocData = json_decode( $AdminFinDocTallaControllerR->content(), true);
|
||||
// $savedData[]['$newFinDocV'] = $AdminFinDocTallaController->verify($newFinTallaDocData['id']);
|
||||
// $savedData[]['$rizhesab'] =$rizhesab;
|
||||
//
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
|
||||
$response["liman"] = [];
|
||||
$response["kalhor"] = [];
|
||||
// پیدا کردن مقدار اکثریت برای ستون ها
|
||||
$result = Product::select('products.reading_method', 'prices.price')
|
||||
->join('prices', 'products.id', '=', 'prices.product_id')
|
||||
->groupBy('products.reading_method', 'prices.price')
|
||||
->orderByRaw('COUNT(*) DESC')
|
||||
->first();
|
||||
// $response = [
|
||||
// "reading_method" => $result->reading_method ?? null,
|
||||
// "price" => $result->price ?? null,
|
||||
// "p" => $result ?? null,
|
||||
// ];
|
||||
|
||||
$response["reading_method"] = $result->reading_method ?? null;
|
||||
$response["price"] = $result->price ?? null;
|
||||
$response["p"] = $result ?? null;
|
||||
$response["prices"] = Http::get('https://pricing.liman.gold/pricingApi', [])->json();
|
||||
|
||||
$response["pay_at_update"] = Order::whereNull('pay_at')->update(['pay_at' => DB::raw('created_at')]);
|
||||
//liman
|
||||
$response["liman"]["orders"] = Order::with(['customer', 'transaction', 'product', 'admin'])->where('customer_id', '!=', 12)
|
||||
->where('sts', 2)->whereBetween('pay_at', [$startDate, $endDate])
|
||||
->orderBy('pay_at', 'desc')
|
||||
->get(['*', Order::$SELECT_STS_STR, Order::$SELECT_CAJ]);
|
||||
$response["liman"]["balance"]["gold"] = 0;
|
||||
$response["liman"]["balance"]["cash"] = 0;
|
||||
$response["liman"]["balance"]["profit_at_moment_all"] = 0;
|
||||
$response["liman"]["balance_abs"]["gold"] = 0;
|
||||
$response["liman"]["balance_abs"]["cash"] = 0;
|
||||
foreach ($response["liman"]["orders"] as &$OrderGoldBalanceRow) {
|
||||
$OrderGoldBalanceRow->profit_at_moment = round(($OrderGoldBalanceRow->amount * ($result->price / config('change_mesghal')) - $OrderGoldBalanceRow->payment_amount) / 10000) * 10000;
|
||||
// $OrderGoldBalanceRow->profit_at_moment_amount2 =$result->price;
|
||||
// $OrderGoldBalanceRow->profit_at_moment_amount =$OrderGoldBalanceRow->amount;
|
||||
// $OrderGoldBalanceRow->profit_at_moment_payment_amount =$OrderGoldBalanceRow->payment_amount;
|
||||
|
||||
if ($OrderGoldBalanceRow->direction == 1) {
|
||||
$response["liman"]["balance"]["gold"] += $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance"]["profit_at_moment_all"] += $OrderGoldBalanceRow->profit_at_moment;
|
||||
$response["liman"]["balance"]["cash"] -= $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
if ($OrderGoldBalanceRow->direction == 2) {
|
||||
$response["liman"]["balance"]["gold"] -= $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance"]["profit_at_moment_all"] -= $OrderGoldBalanceRow->profit_at_moment;
|
||||
$response["liman"]["balance"]["cash"] += $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
$response["liman"]["balance_abs"]["gold"] += $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance_abs"]["cash"] += $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
$response['goldBalanceOfLiman'] = -$response["liman"]["balance"]["gold"];
|
||||
$response['cashBalanceOfLiman'] = -$response["liman"]["balance"]["cash"];
|
||||
//kalhor
|
||||
$response["kalhor"]["orders"]['body'] = [
|
||||
'FromDate' => Jalalian::forge($startDate)->format('Y/m/d'),
|
||||
'ItemId' => 0,
|
||||
'OrderIndex' => 0,
|
||||
'ToDate' => Jalalian::forge($endDate)->format('Y/m/d')
|
||||
];
|
||||
$response["kalhor"]["orders"] = Http::withHeaders(config('kalhor.headers'))
|
||||
->withCookies(config('kalhor.cookies'), 'b750.ir')
|
||||
->post('https://b750.ir/Deal/DealsList', $response["kalhor"]["orders"]['body'])
|
||||
->json();
|
||||
$response["kalhor"]["balance"]["gold"] = 0;
|
||||
$response["kalhor"]["balance"]["cash"] = 0;
|
||||
$response["kalhor"]["balance_abs"]["gold"] = 0;
|
||||
$response["kalhor"]["balance_abs"]["cash"] = 0;
|
||||
if (!empty($response["kalhor"]["orders"]['Data'])) {
|
||||
foreach ($response["kalhor"]["orders"]['Data'] as $data) {
|
||||
if ($data['DeclineReason'] == 0 and $data['OrderStatusStr'] != "لغو شده") { //رد نشده بود
|
||||
if ($data['DealTypeStr'] == "خرید" or $data['DealTypeStr'] == "خرید _ دستی") {
|
||||
$response["kalhor"]["balance"]['gold'] += $data['Count'];
|
||||
$response["kalhor"]["balance"]['cash'] -= $data['TotalPrice'];
|
||||
$direction = 2;
|
||||
} elseif ($data['DealTypeStr'] == "فروش") {
|
||||
$response["kalhor"]["balance"]['gold'] -= $data['Count'];
|
||||
$response["kalhor"]["balance"]['cash'] += $data['TotalPrice'];
|
||||
$direction = 1;
|
||||
}
|
||||
$response["kalhor"]["balance_abs"]['gold'] += $data['Count'];
|
||||
$response["kalhor"]["balance_abs"]['cash'] += $data['TotalPrice'];
|
||||
|
||||
if (Order::where('ref_id', $data['OrderCode'])->doesntExist()) {
|
||||
$request = new Request([
|
||||
'amount' => $data['Count'],
|
||||
'customer_id' => 12,
|
||||
'method' => "liman",
|
||||
'direction' => $direction,
|
||||
'product_id' => 2,
|
||||
"price" => $data['Mazane'],
|
||||
"cash" => $data['TotalPrice'],
|
||||
'ref_id' => $data['OrderCode'],
|
||||
'pay_at' => Carbon::now(),
|
||||
'description' => "FROM KALHOR"
|
||||
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$response["kalhor"]["newOrders"][$data['OrderCode']] = $AdminOrderController->store($request);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$response['goldBalanceOfKalhor'] = $response["kalhor"]["balance"]["gold"];
|
||||
$response['cashBalanceOfKalhor'] = $response["kalhor"]["balance"]["cash"];
|
||||
//main
|
||||
$response['cashBalance'] = -$response["liman"]["balance"]["cash"] + $response["kalhor"]["balance"]["cash"];
|
||||
$response['goldBalance'] = -$response["liman"]["balance"]["gold"] + $response["kalhor"]["balance"]["gold"];
|
||||
//mazaneh
|
||||
$changeMesghal = config('change_mesghal');
|
||||
|
||||
$response['mazanehBalanceOfKalhor'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? ($response["kalhor"]["balance_abs"]["cash"] / $response["kalhor"]["balance_abs"]["gold"]) * $changeMesghal
|
||||
: 0;
|
||||
|
||||
$response['mazanehBalanceOfLiman'] = $response["liman"]["balance_abs"]["gold"] != 0
|
||||
? ($response["liman"]["balance_abs"]["cash"] / $response["liman"]["balance_abs"]["gold"]) * $changeMesghal
|
||||
: 0;
|
||||
|
||||
$totalGold = $response["liman"]["balance_abs"]["gold"] + $response["kalhor"]["balance_abs"]["gold"];
|
||||
$response['mazanehBalance'] = $totalGold != 0
|
||||
? (($response["liman"]["balance_abs"]["cash"] + $response["kalhor"]["balance_abs"]["cash"]) / $totalGold) * $changeMesghal
|
||||
: 0;
|
||||
|
||||
/* $response['mazanehBalanceOfKalhor'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? ( $response["kalhor"]["balance_abs"]["cash"] / $response["kalhor"]["balance_abs"]["gold"])
|
||||
* $changeMesghal : 0;
|
||||
$response['mazanehBalanceOfLiman'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? ( $response["liman"]["balance_abs"]["cash"] / $response["liman"]["balance_abs"]["gold"])
|
||||
* $changeMesghal : 0;
|
||||
$response['mazanehBalance'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? (($response["liman"]["balance_abs"]["cash"]+$response["kalhor"]["balance_abs"]["cash"]) /
|
||||
($response["liman"]["balance_abs"]["gold"]+$response["kalhor"]["balance_abs"]["gold"]))
|
||||
* $changeMesghal : 0;*/
|
||||
$response['oo'] = $reizhesabs;
|
||||
$response['savedData'] = $savedData;
|
||||
return $response;
|
||||
|
||||
}
|
||||
|
||||
public function alertBalance()
|
||||
{
|
||||
$request = new Request([
|
||||
'startDate' => Carbon::today(),
|
||||
'endDate' => Carbon::today()
|
||||
]);
|
||||
$Balance = $this->getBalance($request);
|
||||
// $this->sendMessage("09372281182", "مظنه از {$Balance['goldBalanceOfKalhor']} رد شد!{$Balance['goldBalanceOfLiman']} مظنه فعلی: {$Balance['goldBalance']} گرم.");
|
||||
if ($Balance['goldBalance'] > 50 || $Balance['goldBalance'] < -50) {
|
||||
if ($cntsForSms = Cnt::where('key', 'numberToSendMassageInOrder')->where('title_fa', 'true')->get()) {
|
||||
foreach ($cntsForSms as $cntForSms) {
|
||||
$this->sendMessage($cntForSms->value, "مظنه از ۵۰ رد شد! مظنه فعلی: {$Balance['goldBalance']} گرم.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function getOrders(Request $request)
|
||||
{
|
||||
|
||||
// تنظیم تاریخهای پیشفرض و تبدیل به جلالی
|
||||
$Date['start'] = $request->startDate ? Carbon::parse($request->startDate)->startOfDay() : Carbon::now()->subDays(1)->startOfDay();
|
||||
$Date['end'] = $request->endDate ? Carbon::parse($request->endDate)->endOfDay() : Carbon::now()->endOfDay();
|
||||
|
||||
// تبدیل تاریخهای میلادی به جلالی
|
||||
$Date['start_jalali'] = Jalalian::fromCarbon($Date['start'])->format('Y-m-d');
|
||||
$Date['end_jalali'] = Jalalian::fromCarbon($Date['end'])->format('Y-m-d');
|
||||
|
||||
$response = [];
|
||||
$response['Date'] = $Date;
|
||||
$response["tahesab"] = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => 'tahesabDB'])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoListAsnad' => [
|
||||
100, // Count_Last
|
||||
"", // Moshtari_Code
|
||||
$Date['start_jalali'], // AzTarikhShamsi
|
||||
$Date['end_jalali'], // TaTarikhShamsi
|
||||
]
|
||||
])->json();
|
||||
$response["liman"] = Order::with(['customer'])->where('customer_id', '!=', 12)->where('sts', 2)->whereBetween('pay_at', [$Date['start'], $Date['end']])->get();
|
||||
return $response;
|
||||
|
||||
$response["pay_at_update"] = Order::whereNull('pay_at')->update(['pay_at' => DB::raw('created_at')]);
|
||||
//liman
|
||||
$response["liman"]["orders"] = Order::where('customer_id', '!=', 12)->where('sts', 2)->whereBetween('pay_at', [$startDate, $endDate])->get();
|
||||
$response["liman"]["balance"]["gold"] = 0;
|
||||
$response["liman"]["balance"]["cash"] = 0;
|
||||
$response["liman"]["balance_abs"]["gold"] = 0;
|
||||
$response["liman"]["balance_abs"]["cash"] = 0;
|
||||
foreach ($response["liman"]["orders"] as $OrderGoldBalanceRow) {
|
||||
if ($OrderGoldBalanceRow->direction == 1) {
|
||||
$response["liman"]["balance"]["gold"] += $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance"]["cash"] -= $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
if ($OrderGoldBalanceRow->direction == 2) {
|
||||
$response["liman"]["balance"]["gold"] -= $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance"]["cash"] += $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
$response["liman"]["balance_abs"]["gold"] += $OrderGoldBalanceRow->amount;
|
||||
$response["liman"]["balance_abs"]["cash"] += $OrderGoldBalanceRow->total_price;
|
||||
}
|
||||
$response['goldBalanceOfLiman'] = -$response["liman"]["balance"]["gold"];
|
||||
$response['cashBalanceOfLiman'] = -$response["liman"]["balance"]["cash"];
|
||||
//kalhor
|
||||
$response["kalhor"]["orders"]['body'] = [
|
||||
'FromDate' => Jalalian::forge($startDate)->format('Y/m/d'),
|
||||
'ItemId' => 0,
|
||||
'OrderIndex' => 0,
|
||||
'ToDate' => Jalalian::forge($endDate)->format('Y/m/d')
|
||||
];
|
||||
$response["kalhor"]["orders"] = Http::withHeaders(config('kalhor.headers'))
|
||||
->withCookies(config('kalhor.cookies'), 'b750.ir')
|
||||
->post('https://b750.ir/Deal/DealsList', $response["kalhor"]["orders"]['body'])
|
||||
->json();
|
||||
$response["kalhor"]["balance"]["gold"] = 0;
|
||||
$response["kalhor"]["balance"]["cash"] = 0;
|
||||
$response["kalhor"]["balance_abs"]["gold"] = 0;
|
||||
$response["kalhor"]["balance_abs"]["cash"] = 0;
|
||||
if (!empty($response["kalhor"]["orders"]['Data'])) {
|
||||
foreach ($response["kalhor"]["orders"]['Data'] as &$data) {
|
||||
$data['0_save_in_liman'] = 0;
|
||||
if ($data['DeclineReason'] == 0 and $data['OrderStatusStr'] != "لغو شده") { //رد نشده بود
|
||||
$data['0_save_in_liman'] = 1;
|
||||
if ($data['DealTypeStr'] == "خرید" or $data['DealTypeStr'] == "خرید _ دستی") {
|
||||
$response["kalhor"]["balance"]['gold'] += $data['Count'];
|
||||
$response["kalhor"]["balance"]['cash'] -= $data['TotalPrice'];
|
||||
$direction = 2;
|
||||
} elseif ($data['DealTypeStr'] == "فروش") {
|
||||
$response["kalhor"]["balance"]['gold'] -= $data['Count'];
|
||||
$response["kalhor"]["balance"]['cash'] += $data['TotalPrice'];
|
||||
$direction = 1;
|
||||
}
|
||||
$response["kalhor"]["balance_abs"]['gold'] += $data['Count'];
|
||||
$response["kalhor"]["balance_abs"]['cash'] += $data['TotalPrice'];
|
||||
|
||||
if (Order::where('ref_id', $data['OrderCode'])->doesntExist()) {
|
||||
$request = new Request([
|
||||
'amount' => $data['Count'],
|
||||
'customer_id' => 12,
|
||||
'method' => "liman",
|
||||
'direction' => $direction,
|
||||
'product_id' => 2,
|
||||
"price" => $data['Mazane'],
|
||||
"cash" => $data['TotalPrice'],
|
||||
'ref_id' => $data['OrderCode'],
|
||||
'pay_at' => Carbon::now(),
|
||||
'description' => "FROM KALHOR"
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$response["kalhor"]["newOrders"][$data['OrderCode']] = $AdminOrderController->store($request);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$response['goldBalanceOfKalhor'] = $response["kalhor"]["balance"]["gold"];
|
||||
$response['cashBalanceOfKalhor'] = $response["kalhor"]["balance"]["cash"];
|
||||
//main
|
||||
$response['cashBalance'] = -$response["liman"]["balance"]["cash"] + $response["kalhor"]["balance"]["cash"];
|
||||
$response['goldBalance'] = -$response["liman"]["balance"]["gold"] + $response["kalhor"]["balance"]["gold"];
|
||||
//mazaneh
|
||||
$changeMesghal = config('change_mesghal');
|
||||
|
||||
$response['mazanehBalanceOfKalhor'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? ($response["kalhor"]["balance_abs"]["cash"] / $response["kalhor"]["balance_abs"]["gold"])
|
||||
* $changeMesghal : 0;
|
||||
$response['mazanehBalanceOfLiman'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? ($response["liman"]["balance_abs"]["cash"] / $response["liman"]["balance_abs"]["gold"])
|
||||
* $changeMesghal : 0;
|
||||
$response['mazanehBalance'] = $response["kalhor"]["balance_abs"]["gold"] != 0
|
||||
? (($response["liman"]["balance_abs"]["cash"] + $response["kalhor"]["balance_abs"]["cash"]) /
|
||||
($response["liman"]["balance_abs"]["gold"] + $response["kalhor"]["balance_abs"]["gold"]))
|
||||
* $changeMesghal : 0;
|
||||
return $response;
|
||||
|
||||
}
|
||||
|
||||
public function index2()
|
||||
{
|
||||
$return = [];
|
||||
$users = Customer::all();
|
||||
// Fetch all products with their prices
|
||||
$returnProduct = Product::with("prices")->get();
|
||||
// Filter unique prices for each product
|
||||
$this->null = null;
|
||||
//remove duplicate dates
|
||||
foreach ($returnProduct as $index => $product) {
|
||||
$uniquePrices = [];
|
||||
$dataOld = $this->null;
|
||||
foreach ($product->prices as $price) {
|
||||
if ($dataOld !== $price->date_at) {
|
||||
$uniquePrices[] = $price;
|
||||
}
|
||||
$dataOld = $price->date_at;
|
||||
}
|
||||
$return["product"][$index] = [
|
||||
'title' => $product->title,
|
||||
'unit' => $product->unit,
|
||||
'prices' => $uniquePrices
|
||||
];
|
||||
}
|
||||
// Count and filter users by type
|
||||
$return["count_users_all"] = $users->count();
|
||||
$return["count_agent"] = $users->where("type", 1)->count();
|
||||
$return["count_users"] = $users->where("type", 2)->count();
|
||||
$Customers = Customer::with("Transaction")->get();
|
||||
|
||||
|
||||
$counterUsers = 0;
|
||||
foreach ($Customers as $customer) {
|
||||
// return $customer;
|
||||
$filteredUsers['name'] = $customer->name;
|
||||
$filteredUsers['mobile'] = $customer->mobile;
|
||||
$filteredUsers['type'] = $customer->type;
|
||||
$filteredUsers['byeGram'] = 0;
|
||||
$filteredUsers['sellGram'] = 0;
|
||||
// return $customer/*->gram*/;
|
||||
foreach ($customer->transaction as $transaction) {
|
||||
if ($transaction->note == "واریز بابت خرید") {
|
||||
$filteredUsers['byeGram'] += $transaction->amount;
|
||||
} elseif ($transaction->note == "برداشت بابت فروش") {
|
||||
$filteredUsers['sellGram'] += $transaction->amount;
|
||||
}
|
||||
}
|
||||
$filteredUsers['sellGram'] = -$filteredUsers['sellGram'];
|
||||
$filteredUsers['sellGram'] = $filteredUsers['byeGram'] + $filteredUsers['sellGram'];
|
||||
if (isset($filteredUsers['sellGram']) && is_numeric($filteredUsers['sellGram'])) {
|
||||
$filteredUsers['sellGram'] = number_format((float)$filteredUsers['sellGram'], 1);
|
||||
}
|
||||
|
||||
$users[$counterUsers++] = $filteredUsers;
|
||||
|
||||
}
|
||||
// Decode JSON data into a PHP array
|
||||
$data = json_decode($users, true);
|
||||
|
||||
// Function to sort the array by 'byeGram' in descending order
|
||||
usort($data, function ($a, $b) {
|
||||
return $b['byeGram'] <=> $a['byeGram'];
|
||||
});
|
||||
$return['top_five_byers'] = array_slice($data, 0, 5);
|
||||
usort($data, function ($a, $b) {
|
||||
return $b['sellGram'] <=> $a['sellGram'];
|
||||
});
|
||||
$return['top_five_sellers'] = array_slice($data, 0, 5);
|
||||
$return['allSellGram'] = array_reduce($data, function ($carry, $item) {
|
||||
return $carry + $item['sellGram'];
|
||||
}, 0);
|
||||
$return['allByeGram'] = array_reduce($data, function ($carry, $item) {
|
||||
return $carry + $item['byeGram'];
|
||||
}, 0);
|
||||
$return['top_five_byers'] = Customer::with('Transaction')
|
||||
->withCount('Transaction') // شمارش تعداد تراکنشها
|
||||
->orderBy('transaction_count', 'desc') // مرتبسازی بر اساس بیشترین تعداد تراکنش
|
||||
->take(5) // محدود کردن نتیجه به ۵ مشتری
|
||||
->get()
|
||||
->map(function ($customer) {
|
||||
return [
|
||||
'name' => $customer->name, // ترکیب نام و نام خانوادگی یا استفاده از فیلد name
|
||||
'mobile' => $customer->mobile, // فرض میکنیم فیلد mobile در مدل موجود است
|
||||
'byeGram' => 0, // فرض بر این است که تراکنشها دارای فیلد byeGram هستند
|
||||
'sellGram' => $customer->transaction_count, // فرض بر این است که تراکنشها دارای فیلد sellGram هستند
|
||||
'type' => $customer->type, // فرض میکنیم نوع مشتری بر اساس تراکنشها تعیین میشود
|
||||
];
|
||||
});
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$return = [];
|
||||
$users = Customer::all();
|
||||
|
||||
// Fetch all products with their prices
|
||||
$returnProduct = Product::with("prices")->get();
|
||||
|
||||
// Remove duplicate dates in product prices
|
||||
foreach ($returnProduct as $product) {
|
||||
$uniquePrices = [];
|
||||
$dataOld = null; // Initialize to null
|
||||
foreach ($product->prices as $price) {
|
||||
if ($dataOld !== $price->date_at) {
|
||||
$uniquePrices[] = $price;
|
||||
}
|
||||
$dataOld = $price->date_at;
|
||||
}
|
||||
$return["product"][] = [
|
||||
'title' => $product->title,
|
||||
'unit' => $product->unit,
|
||||
'prices' => $uniquePrices
|
||||
];
|
||||
}
|
||||
|
||||
// Count and filter users by type
|
||||
$return["count_users_all"] = $users->count();
|
||||
$return["count_agent"] = $users->where("type", 1)->count();
|
||||
$return["count_users"] = $users->where("type", 2)->count();
|
||||
|
||||
$usersData = []; // To store filtered users
|
||||
$Customers = Customer::with("transaction")->get();
|
||||
|
||||
foreach ($Customers as $customer) {
|
||||
$filteredUsers = [
|
||||
'name' => $customer->name,
|
||||
'mobile' => $customer->mobile,
|
||||
'type' => $customer->type,
|
||||
'byeGram' => 0,
|
||||
'sellGram' => 0,
|
||||
];
|
||||
|
||||
foreach ($customer->transaction as $transaction) {
|
||||
if ($transaction->note == "واریز بابت خرید") {
|
||||
$filteredUsers['byeGram'] += $transaction->amount;
|
||||
} elseif ($transaction->note == "برداشت بابت فروش") {
|
||||
$filteredUsers['sellGram'] += $transaction->amount;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the net sellGram
|
||||
$filteredUsers['sellGram'] = -$filteredUsers['sellGram'] + $filteredUsers['byeGram'];
|
||||
|
||||
// Format sellGram without commas
|
||||
$filteredUsers['sellGram'] = is_numeric($filteredUsers['sellGram'])
|
||||
? number_format((float)$filteredUsers['sellGram'], 1, '.', '') // No thousands separator
|
||||
: '0.0'; // Handle non-numeric case
|
||||
|
||||
$usersData[] = $filteredUsers; // Store filtered user data
|
||||
}
|
||||
|
||||
|
||||
// Sort users by sellGram and take the top five sellers
|
||||
usort($usersData, function ($a, $b) {
|
||||
return $b['sellGram'] <=> $a['sellGram'];
|
||||
});
|
||||
$return['top_five_sellers'] = array_slice($usersData, 0, 5);
|
||||
|
||||
// Calculate totals
|
||||
$return['allSellGram'] = array_reduce($usersData, function ($carry, $item) {
|
||||
return $carry + (float)str_replace(',', '', $item['sellGram']);
|
||||
}, 0);
|
||||
$return['allByeGram'] = array_reduce($usersData, function ($carry, $item) {
|
||||
return $carry + $item['byeGram'];
|
||||
}, 0);
|
||||
|
||||
// Fetch top five buyers based on transaction count
|
||||
$return['top_five_byers'] = Customer::with('transaction')
|
||||
->withCount('transaction')
|
||||
->orderBy('transaction_count', 'desc')
|
||||
->take(5)
|
||||
->get()
|
||||
->map(function ($customer) {
|
||||
return [
|
||||
'name' => $customer->name,
|
||||
'mobile' => $customer->mobile,
|
||||
'byeGram' => 0, // Assuming byeGram is set elsewhere
|
||||
'sellGram' => $customer->transaction_count, // Assuming sellGram is based on transaction count
|
||||
'type' => $customer->type,
|
||||
];
|
||||
});
|
||||
|
||||
return $return; // Return structured response
|
||||
|
||||
}
|
||||
|
||||
public function sse()
|
||||
{
|
||||
return 1;
|
||||
$response = new StreamedResponse(function () {
|
||||
while (true) {
|
||||
// ارسال داده به صورت JSON
|
||||
echo "data: " . json_encode(['message' => 'Hello, world!']) . "\n\n";
|
||||
|
||||
// اطمینان از ارسال دادهها به مرورگر
|
||||
ob_flush();
|
||||
flush();
|
||||
|
||||
// توقف به مدت 1 ثانیه
|
||||
sleep(1);
|
||||
}
|
||||
});
|
||||
|
||||
$response->headers->set('Content-Type', 'text/event-stream');
|
||||
$response->headers->set('Cache-Control', 'no-cache');
|
||||
$response->headers->set('Connection', 'keep-alive');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperPackageController;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Package;
|
||||
use App\Models\PackageProduct;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class BasePackageController extends SuperPackageController
|
||||
{
|
||||
public function __construct(Request $request)
|
||||
{
|
||||
$customers = Customer::where('type',1)->select('id')->get()->pluck('id')->toArray();
|
||||
$request->request->add(['user_creator_id'=>auth('user')->id(),'is_base'=>true,'title'=>'base','customers'=>$customers]);
|
||||
parent::__construct(['sub_packages.product'], ['*'], null, ['title']);
|
||||
}
|
||||
public function getOne(){
|
||||
$package = Package::with(['sub_packages.product'])->where('is_base',true)->first();
|
||||
return response()->json($package);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\Cnt;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ConstController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(Cnt::class, [], ['*'], null, null, ['key']);
|
||||
}
|
||||
|
||||
public function showValue($key){
|
||||
$cnt = Cnt::where('key',$key)
|
||||
->select('id','value','title_fa')->get();
|
||||
return response()->json($cnt);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,453 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductCredit;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
|
||||
class CustomerController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->with = ['agent', 'avatar'];
|
||||
$this->search = ['name', 'mobile'];
|
||||
$this->select = ['*', Customer::$SELECT_CAJ, Customer::$SELECT_TYPE_STR];
|
||||
parent::__construct(Customer::class, $this->with, $this->select, 'customer', null, $this->search);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
|
||||
if (isset($data['agent_id']) && !empty($data['agent_id'])) {
|
||||
$agentName = Customer::where('id', $data['agent_id'])->first(['name']);
|
||||
$agentName = $agentName ? $agentName->name : 'ندارد';
|
||||
} else {
|
||||
$agentName = 'ندارد';
|
||||
}
|
||||
if (isset($data['fname']) && isset($data['lname'])) {
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
if (strlen($data['mobile']) != 11) {
|
||||
return response()->json([
|
||||
'message' => 'شماره را کامل وارد کنید'
|
||||
], 422);
|
||||
}
|
||||
if (Customer::where('mobile', $data['mobile'])->exists()) {
|
||||
return response()->json([
|
||||
'message' => '!! شماره موبایل وارد شده قبلا ثبت شده است'
|
||||
], 422);
|
||||
}
|
||||
if (!isset($data['password'])) {
|
||||
$data['password'] = trim($data['mobile']);
|
||||
}
|
||||
$user = Customer::create($data);
|
||||
|
||||
new WalletInterface($user->id, $user->type);
|
||||
$DoNewMoshtari = [
|
||||
$data['name'], // Name
|
||||
$agentName, // GoroupName
|
||||
$data['mobile'], // Tel
|
||||
$user->id, // Address
|
||||
];
|
||||
if ($this->Config('tahesab') == "send_importent") {
|
||||
$response = Http::withoutVerifying()
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db') ])
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewMoshtari' => $DoNewMoshtari
|
||||
])->json();
|
||||
if (isset($response['OK'])) {
|
||||
$data['tahesab_id'] = $response['OK'];
|
||||
$user->tahesab_id = $data['tahesab_id'];
|
||||
$user->save();
|
||||
} elseif (isset($response['ERROR'])) {
|
||||
// برگرداندن پیام خطا به صورت JSON با کد وضعیت 422
|
||||
return response()->json([
|
||||
'message' => $response['ERROR']
|
||||
], 422);
|
||||
} else {
|
||||
// مدیریت زمانی که پاسخ غیرمنتظره باشد
|
||||
return response()->json([
|
||||
'message' => 'پاسخ غیرمنتظره دریافت شد'
|
||||
], 400); // یا 422 بسته به شرایط
|
||||
}
|
||||
}
|
||||
$message = $this->Config('name_fa') . "\n" .
|
||||
'همکار گرامی ' . $data['name'] . "\n" .
|
||||
'نام کاربری : ' . trim($data['mobile']) . "\n" .
|
||||
"ورود به اکانت خرید و فروش: " . $this->Config('user_url');
|
||||
|
||||
if ($user->type == 1) {
|
||||
$message .= "\n" . "ورود به اکانت نمایندگی : " . $this->Config('agent_url');
|
||||
}
|
||||
|
||||
self::Send(trim($data['mobile']), $message);
|
||||
return $this->resultCreate($user->id);
|
||||
|
||||
}
|
||||
public function saveCustomer(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
|
||||
if (isset($data['agent_id']) && !empty($data['agent_id'])) {
|
||||
$agentName = Customer::where('id', $data['agent_id'])->first(['name']);
|
||||
$agentName = $agentName ? $agentName->name : 'ندارد';
|
||||
} else {
|
||||
$agentName = 'ندارد';
|
||||
}
|
||||
if (isset($data['fname']) && isset($data['lname'])) {
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
if (strlen($data['mobile']) != 11) {
|
||||
return response()->json([
|
||||
'message' => 'شماره را کامل وارد کنید'
|
||||
], 422);
|
||||
}
|
||||
if (Customer::where('mobile', $data['mobile'])->exists()) {
|
||||
return response()->json([
|
||||
'message' => '!! شماره موبایل وارد شده قبلا ثبت شده است'
|
||||
], 422);
|
||||
}
|
||||
if (!isset($data['password'])) {
|
||||
$data['password'] = trim($data['mobile']);
|
||||
}
|
||||
$user = Customer::create($data);
|
||||
|
||||
new WalletInterface($user->id, $user->type);
|
||||
$DoNewMoshtari = [
|
||||
$data['name'], // Name
|
||||
$agentName, // GoroupName
|
||||
$data['mobile'], // Tel
|
||||
$user->id, // Address
|
||||
];
|
||||
if ($this->Config('tahesab') == "send_importent") {
|
||||
$response = Http::withoutVerifying()
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db') ])
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewMoshtari' => $DoNewMoshtari
|
||||
])->json();
|
||||
if (isset($response['OK'])) {
|
||||
$data['tahesab_id'] = $response['OK'];
|
||||
$user->tahesab_id = $data['tahesab_id'];
|
||||
$user->save();
|
||||
} elseif (isset($response['ERROR'])) {
|
||||
// برگرداندن پیام خطا به صورت JSON با کد وضعیت 422
|
||||
return response()->json([
|
||||
'message' => $response['ERROR']
|
||||
], 422);
|
||||
} else {
|
||||
// مدیریت زمانی که پاسخ غیرمنتظره باشد
|
||||
return response()->json([
|
||||
'message' => 'پاسخ غیرمنتظره دریافت شد'
|
||||
], 400); // یا 422 بسته به شرایط
|
||||
}
|
||||
}
|
||||
$message = $this->Config('name_fa') . "\n" .
|
||||
'همکار گرامی ' . $data['name'] . "\n" .
|
||||
'نام کاربری : ' . trim($data['mobile']) . "\n" .
|
||||
"ورود به اکانت خرید و فروش: " . $this->Config('user_url');
|
||||
|
||||
if ($user->type == 1) {
|
||||
$message .= "\n" . "ورود به اکانت نمایندگی : " . $this->Config('agent_url');
|
||||
}
|
||||
|
||||
self::Send(trim($data['mobile']), $message);
|
||||
return $this->resultCreate($user->id);
|
||||
|
||||
}
|
||||
public function updateCustomer(Request $request,$id)
|
||||
{
|
||||
// $data = $request->only(['gender','fname','lname','mobile','n_code','birth_date','password','agent_id','type_str','group','tahesab_id',]);
|
||||
$data = $request->all();
|
||||
|
||||
if (isset($data['fname'])) {
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
if (strlen($data['mobile']) != 11) {
|
||||
return response()->json([
|
||||
'message' => 'شماره را کامل وارد کنید'
|
||||
], 422);
|
||||
}
|
||||
// if (Customer::where('mobile', $data['mobile'])->exists()) {
|
||||
// return response()->json([
|
||||
// 'message' => '!! شماره موبایل وارد شده قبلا ثبت شده است'
|
||||
// ], 422);
|
||||
// }
|
||||
if (!isset($data['password'])) {
|
||||
$data['password'] = trim($data['mobile']);
|
||||
}
|
||||
if (($data['type_str'] == 'کاربر')) {
|
||||
$data['type'] = 2;
|
||||
}elseif (($data['type_str'] == 'نماینده')){
|
||||
$data['type'] = 1;
|
||||
|
||||
if (Customer::where('type', 1)->count() > 11) {
|
||||
return response()->json([
|
||||
'message' => 'تعداد نمایندگان از حد مجاز بیشتر است.'
|
||||
], 422);
|
||||
}
|
||||
if (isset($data['agent_id'])) {
|
||||
$agent = Customer::find($data['agent_id']);
|
||||
|
||||
if ($agent && $agent->agent_id) {
|
||||
$parentAgent = Customer::find($agent->agent_id);
|
||||
|
||||
if ($parentAgent && $parentAgent->agent_id) {
|
||||
return response()->json([
|
||||
'message' => 'سظح نماینده از حد مجاز بیشتر است.'
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
}else{
|
||||
// $user = Customer::findOrFail($id)->first();
|
||||
// $user->agent_id = null;
|
||||
// $user->save();
|
||||
}
|
||||
}else{
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
$user = Customer::findOrFail($id)->update($data);
|
||||
$user = Customer::findOrFail($id)->first();
|
||||
|
||||
if (!isset($data['agent_id'])) {
|
||||
$user->agent_id = null;
|
||||
$user->save();
|
||||
}
|
||||
return $this->resultCreate($user);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$query_table = Customer::with($this->with)->where("is_archive", false)->where('type', $request->type);
|
||||
TableEngine::create($query_table, $request)
|
||||
->initSearch($this->search)
|
||||
->select($this->select)
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
|
||||
public function tableArchive(Request $request)
|
||||
{
|
||||
$query_table = Customer::with($this->with)->where("is_archive", true)->where('type', $request->type);
|
||||
TableEngine::create($query_table, $request)
|
||||
->initSearch($this->search)
|
||||
->select($this->select)
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
|
||||
public function agentTable(Request $request)
|
||||
{
|
||||
try {
|
||||
$customerSync = $this->customerSync();
|
||||
} catch (\Exception $e) {
|
||||
$customerSync = "مشکل در اتصال به ته حساب";
|
||||
}
|
||||
$request->request->add(['type' => 1]);
|
||||
return response()->json($this->table($request));
|
||||
}
|
||||
|
||||
public function customerTable(Request $request)
|
||||
{
|
||||
try {
|
||||
$customerSync = $this->customerSync();
|
||||
} catch (\Exception $e) {
|
||||
$customerSync = "مشکل در اتصال به ته حساب";
|
||||
}
|
||||
$request->request->add(['type' => 2]);
|
||||
$responce = $this->table($request);
|
||||
$responce["customerSync"] = $customerSync;
|
||||
return response()->json($responce);
|
||||
}
|
||||
public function customerToggleType($id)
|
||||
{
|
||||
$customerVal= Customer::find($id);
|
||||
$customerVal->type = ($customerVal->type == 1) ? 2 : 1;
|
||||
$customerVal->agent_id = ($customerVal->type == 2) ? $this->Config('main_agent_id') : null;
|
||||
$customerVal->save();
|
||||
return response()->json(["message"=>$customerVal],200);
|
||||
|
||||
}
|
||||
public function customerAll(Request $request)
|
||||
{
|
||||
$customerSync = $this->customerSync();
|
||||
|
||||
try {
|
||||
$customerSync = $this->customerSync();
|
||||
} catch (\Exception $e) {
|
||||
$customerSync = "مشکل در اتصال به ته حساب";
|
||||
}
|
||||
// $responce = $this->table($request);
|
||||
$query_table = Customer::with($this->with)->where("is_archive", false);
|
||||
TableEngine::create($query_table, $request)
|
||||
->initSearch(['name', 'mobile', 'customer_type','agent.name'])
|
||||
->select(['*', Customer::$SELECT_CAJ, Customer::$SELECT_TYPE_STR])
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
$responce["customerSync"] = $customerSync;
|
||||
return response()->json($responce);
|
||||
}
|
||||
public function customerSync()
|
||||
{
|
||||
|
||||
$notExestes = [];
|
||||
$DoNewMoshtari = [
|
||||
0, // Name
|
||||
100000000000, // GoroupName
|
||||
];
|
||||
|
||||
$response = Http::withoutVerifying()->timeout(2)
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoListMoshtari' => $DoNewMoshtari
|
||||
])->json();
|
||||
|
||||
foreach ($response as $customerData) {
|
||||
if (!is_array($customerData)) {
|
||||
continue; //این شرط if قسمت به کد ها اضافه شد
|
||||
}
|
||||
// return $response;
|
||||
if (isset($customerData['Mobile']) && strlen($customerData['Mobile']) < 9) {
|
||||
continue;
|
||||
}
|
||||
$existingCustomer = Customer::where('mobile', $customerData['Mobile'])->first();
|
||||
if ($existingCustomer) {
|
||||
// Check if tahesab_id needs to be updated
|
||||
if ($existingCustomer->tahesab_id !== $customerData['Code']) {
|
||||
$notExestes[] = [
|
||||
'existing' => $existingCustomer,
|
||||
'incoming' => $customerData,
|
||||
];
|
||||
$existingCustomer->update(['tahesab_id' => $customerData['Code']]);
|
||||
}
|
||||
} else {
|
||||
$notExestes[] = $customerData;
|
||||
Customer::create([
|
||||
'fname' => $customerData['Name'],
|
||||
'name' => $customerData['Name'],
|
||||
'gid' => $customerData['GID'],
|
||||
'group_name' => $customerData['GoroupName'] ?? null,
|
||||
'tahesab_id' => $customerData['Code'],
|
||||
'type' => 2,
|
||||
'active' => 0,
|
||||
'mobile' => $customerData['Mobile'] !== "null" ? $customerData['Mobile'] : null,
|
||||
'code_melli' => $customerData['CodeMelli'] ?? null,
|
||||
'address' => $customerData['Address'] ?? null,
|
||||
'city' => $customerData['City'] ?? null,
|
||||
'birth_date' => $customerData['BDate'] ?? null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return response()->json($notExestes);
|
||||
}
|
||||
|
||||
public function agentArchiveTable(Request $request)
|
||||
{
|
||||
$request->request->add(['type' => 1]);
|
||||
return response()->json($this->tableArchive($request));
|
||||
}
|
||||
|
||||
public function customerArchiveTable(Request $request)
|
||||
{
|
||||
$request->request->add(['type' => 2]);
|
||||
return response()->json($this->tableArchive($request));
|
||||
}
|
||||
|
||||
public function listAgent()
|
||||
{
|
||||
$agent = Customer::where('type',1)->orWhere('type',3)->select(['name', 'id', 'mobile'])
|
||||
->get();
|
||||
return response()->json($agent);
|
||||
}
|
||||
|
||||
public function listCustomer(Request $request,$agent_id=null)
|
||||
{
|
||||
|
||||
if (isset($request->product_id)) {
|
||||
$productId = $request->product_id;
|
||||
$customer = Customer::select('id', 'name', 'mobile')->with(['Wallet' =>
|
||||
function ($query) use ($productId) {
|
||||
$query->where(function ($q) use ($productId) {
|
||||
$q->whereNull('product_id')
|
||||
->orWhere('product_id', $productId);
|
||||
})->select('credit', 'product_id', 'owner');
|
||||
}])
|
||||
->where("is_archive", false)
|
||||
->get();
|
||||
return response()->json($customer);
|
||||
} else {
|
||||
$query = Customer::select(['name', 'id', 'mobile', 'type'])
|
||||
->where("is_archive", false);
|
||||
|
||||
if ($agent_id != null) {
|
||||
$query->where("agent_id", $agent_id);
|
||||
}
|
||||
|
||||
$customer = $query->get();
|
||||
return response()->json($customer);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function archive($id)
|
||||
{
|
||||
$query = Customer::findOrFail($id);
|
||||
$query->update([
|
||||
'is_archive' => !$query->is_archive
|
||||
]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function barayand($customer_id)
|
||||
{
|
||||
$wallet = Wallet::where('owner', $customer_id)->whereNull('product_id')->first();
|
||||
$rial = $wallet->credit;
|
||||
$value = 0;
|
||||
$price = 0;
|
||||
$product_value = 0;
|
||||
$products = Product::with(['price'])->where('for_barayand', true)->get();
|
||||
foreach ($products as $product) {
|
||||
$p_wallet = Wallet::where('owner', $customer_id)->where('product_id', $product->id)->first();
|
||||
if ($p_wallet) {
|
||||
$rial += ($product->wallet->credit * $product->price->price);
|
||||
$value += $product->wallet->credit;
|
||||
}
|
||||
$price += $product->price->price;
|
||||
}
|
||||
if ($price > 0) {
|
||||
$price = $price / count($products);
|
||||
$product_value = $value + $wallet->credit / $price;
|
||||
}
|
||||
return response()->json([
|
||||
'rial' => $rial,
|
||||
'product' => $product_value
|
||||
]);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\CustomerCredit;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
|
||||
class CustomerCreditController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
foreach ($data as $item) {
|
||||
CustomerCredit::create($item);
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
foreach ($request->all() as $credit) {
|
||||
// ابتدا رکوردهای موجود را حذف کنید
|
||||
CustomerCredit::where('customer_id', $id)
|
||||
->where('product_id', $credit['product_id'])
|
||||
->delete();
|
||||
|
||||
// سپس رکوردهای جدید را ایجاد کنید
|
||||
CustomerCredit::create([
|
||||
"customer_id" => $id,
|
||||
"product_id" => $credit['product_id'],
|
||||
"buy_credit" => $credit['buy_credit'],
|
||||
"sell_credit" => $credit['sell_credit'],
|
||||
]);
|
||||
}
|
||||
$credits = CustomerCredit::where('customer_id', $id)->get();
|
||||
return $credits;
|
||||
|
||||
}
|
||||
|
||||
public function listCredit($id)
|
||||
{
|
||||
|
||||
// try {
|
||||
// $user = Customer::find($id);
|
||||
// $data['wallet'] = Wallet::with(["product"])->where('owner', $user->id)->whereNull("product_id")->first();
|
||||
// $walletCredit = $data['wallet']['credit'];
|
||||
// $response = Http::withoutVerifying()
|
||||
// ->withToken($this->Config('tahesab_token'))
|
||||
// ->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
// ->post($this->Config('tahesab_api'), [
|
||||
// 'getmandehesabbycode' => [$user->tahesab_id]
|
||||
// ])->json();
|
||||
//
|
||||
//
|
||||
// $data['TC'] = (int)$response['MandeHesab'][0]['MandeyeKolBePool'];
|
||||
// $data['LC'] = $walletCredit;
|
||||
// $data['difference'] = $difference = (int)$response['MandeHesab'][0]['MandeyeKolBePool'] - $walletCredit;
|
||||
// $cash_interface = new WalletInterface($user->id, $user->type);
|
||||
// $_type = $difference > 0 ? 1 : 2;
|
||||
// $deposit = $difference > 0 ? true : false;
|
||||
// if ($difference > 10000000 || $difference < -10000000) {
|
||||
// new TransactionInterface($cash_interface, $_inp = [
|
||||
// "amount" => $difference,
|
||||
// 'expire_at' => now(),
|
||||
// 'active' => true,
|
||||
// 'note' => "اصلاح ریال"
|
||||
// ], $_type, $deposit,/*$withdraw_block,$deposit_block*/);
|
||||
// }
|
||||
//
|
||||
// } catch (\Exception $e) {
|
||||
// }
|
||||
|
||||
$credit = CustomerCredit::with('product.file')->where('customer_id', $id)->get();
|
||||
// $credit = [];
|
||||
// foreach ($credit as $item) {
|
||||
// if ($item->product && $item->product->active && $item->product->show) {
|
||||
// $price_gram = Product::with('price')->where('id', $item->product_id)->first()->price->price_gram;
|
||||
// $balance = Wallet::where('owner', $id)->whereNull('product_id')->first()->credit / $price_gram;
|
||||
// $item->buy_credit = $item->buy_credit + $balance;
|
||||
// $item->buy_credit = number_format($item->buy_credit);
|
||||
// $item->sell_credit = $item->sell_credit - $balance;
|
||||
// $item->sell_credit = number_format($item->sell_credit);
|
||||
// }
|
||||
// }
|
||||
|
||||
return response()->json($credit);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\File;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class FileController extends Controller
|
||||
{
|
||||
/**
|
||||
* make directory in Public Storage By Date
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function createDir()
|
||||
{
|
||||
$now = Verta();
|
||||
$path = preg_replace('/-/', '/', $now->formatDate());
|
||||
if (!Storage::exists($path)) {
|
||||
Storage::makeDirectory($path);
|
||||
Storage::makeDirectory($path . '/' . 'thumb');
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
public function store(Request $request)
|
||||
{
|
||||
// Store FIle in Public Storage By Date
|
||||
// Date Sample is : <Year>/<Month>/<Day> of today
|
||||
|
||||
$data = $request->all();
|
||||
$path = $this->createDir();
|
||||
$data['original_name'] = $request->file('file')->getClientOriginalName();
|
||||
$data['ext'] = $request->file('file')->getClientOriginalExtension();
|
||||
if (!isset($data['title']) || is_null($data['title'])) {
|
||||
$data['title'] = $data['original_name'];
|
||||
}
|
||||
$file_name_src = md5(time() . $data['original_name']);
|
||||
$file_name = $file_name_src . '.' . $data['ext'];
|
||||
$file = $request->file('file');
|
||||
$data['has_thumb'] = false;
|
||||
$data['size'] = $file->getSize();
|
||||
$file->move(public_path('storage/' . $path . '/'), $file_name);
|
||||
$data['src'] = 'storage/' . $path . '/' . $file_name;
|
||||
// $data['size'] = $file->getSize();
|
||||
$data['user_id'] = auth()->id();
|
||||
$data['sts'] = 1;
|
||||
$file_create = File::create($data);
|
||||
return response()->json($file_create);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,269 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\Customer;
|
||||
use App\Models\FinancialDoc;
|
||||
use App\Models\Product;
|
||||
use http\Env\Response;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
|
||||
class FinDocController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->search = [ 'receive_name','finance_Sh_factor', 'track_number', 'customer.name'];
|
||||
parent::__construct(FinancialDoc::class, ['customer','admin', 'transaction'], ['*', FinancialDoc::$SELECT_CAJ, FinancialDoc::$SELECT_TYPE_STR, FinancialDoc::$SELECT_STS_STR],null,null, $this->search);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
//
|
||||
// if (!isset($data['type'])) {
|
||||
// return response()->json(['error' => 'Type field is missing'], 400);
|
||||
// }
|
||||
|
||||
|
||||
$data = $request->all();
|
||||
$data['sts'] = 1;
|
||||
$fin_doc = FinancialDoc::create($data);
|
||||
$fin_doc->type = $data['type'] ;
|
||||
$fin_doc->save();
|
||||
return $fin_doc;
|
||||
|
||||
|
||||
}
|
||||
public function verify($id)
|
||||
{
|
||||
$deposit = true;
|
||||
$note = 'سند ورودی';
|
||||
$fin_doc = FinancialDoc::findOrFail($id);
|
||||
$tahesab_banks_response = $response = Http::withoutVerifying()
|
||||
->withToken(Controller::Config('tahesab_token'))
|
||||
->withHeaders(['DBName' =>Controller::Config('tahesab_db')])
|
||||
->post(Controller::Config('tahesab_api'), [
|
||||
'DoListHesabBanki' => []
|
||||
])->json();
|
||||
$tahesab_banks = [];
|
||||
if (is_array($tahesab_banks_response) || is_object($tahesab_banks_response)) {
|
||||
foreach ($tahesab_banks_response as $banks) {
|
||||
if(is_array($banks) or is_object($banks)) { //تغییرات ایجاد شده خانوم سعیدی
|
||||
foreach ($banks as $bank) {
|
||||
$tahesab_banks[] = $bank;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$tahesab_bank = ($fin_doc->type == 2) ? $fin_doc['send_bank'] :$fin_doc['receive_bank'] ;
|
||||
$actionName = ($fin_doc->type == 2) ? 'سند خروجی' : 'سند ورودی';
|
||||
if (!in_array($tahesab_bank, $tahesab_banks)) {
|
||||
return response()->json([
|
||||
"message" => " در $actionName بانک $tahesab_bank موجود نیست. بانکهای موجود: " . implode(' | ', $tahesab_banks)
|
||||
], 422);
|
||||
}
|
||||
$cu = Customer::findOrFail($fin_doc->customer_id);
|
||||
$cash_interface = new WalletInterface($cu->id, $cu->type);
|
||||
if ($fin_doc->type == 2) {
|
||||
$deposit = false;
|
||||
$note = 'سند خروجی';
|
||||
}
|
||||
new TransactionInterface($cash_interface, $_inp = [
|
||||
"amount" => $fin_doc->amount,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'fin_doc_id' => $fin_doc->id,
|
||||
'note' => $note
|
||||
], $cu->type, $deposit);
|
||||
$fin_doc->sts = 2;
|
||||
$fin_doc->admin_id = auth()->id();
|
||||
|
||||
$fin_doc->save();
|
||||
$date = Jalalian::fromCarbon(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $fin_doc['date_at']));
|
||||
$shamsiYear = $date->getYear();
|
||||
$shamsiMonth = $date->getMonth();
|
||||
$shamsiDay = $date->getDay();
|
||||
|
||||
$finCustomer = Customer::where('id',$fin_doc['customer_id'])->first();
|
||||
$DoNewSanadVKHGOLD = [
|
||||
1, // Sabte_Kol_Or_Movaghat_1_0 (1 if type is main, else 0)
|
||||
$finCustomer->tahesab_id, // Moshtari_Code
|
||||
$fin_doc->id, // Factor_Number
|
||||
0, // Radif_Number
|
||||
$shamsiYear, // Shamsi_Year
|
||||
$shamsiMonth, // Shamsi_Month
|
||||
$shamsiDay, // Shamsi_Day
|
||||
$fin_doc['type'] == ($fin_doc->type == 2) ? 1 : 0, // IsVoroodOrKhorooj_0_1
|
||||
(int)$fin_doc['amount'], // Mablagh
|
||||
sprintf(
|
||||
"receive_account_number(شماره حساب دریافتکننده): %s,
|
||||
receive_bank(بانک دریافتکننده): %s,
|
||||
receive_name(نام دریافتکننده): %s,
|
||||
send_account_number(شماره حساب فرستنده): %s,
|
||||
send_bank(بانک فرستنده): %s,
|
||||
send_name(نام فرستنده): %s",
|
||||
$fin_doc['receive_account_number'],
|
||||
$fin_doc['receive_bank'],
|
||||
$fin_doc['receive_name'],
|
||||
$fin_doc['send_account_number'],
|
||||
$fin_doc['send_bank'],
|
||||
$fin_doc['send_name'],
|
||||
|
||||
) // Sharh
|
||||
];
|
||||
|
||||
// $response = Http::withoutVerifying()->withHeaders(['DBName' => 'tahesabDB7' ])->withToken('U4I3V1B3K3A5S3E1C7Y8D5R1S8J6N4S2B3W7O6S2I1D5U1L4R5D7T6V5U1B1U1H8L4C5V6N6V2U4M8Q8')->post('https://192.168.200.20:8081', [
|
||||
// 'DoNewSanadVKHVaghNaghd' => $DoNewSanadVKHGOLD
|
||||
// ]);
|
||||
|
||||
$DoNewSanadVKHGOLD = [
|
||||
1, // Sabte_Kol_Or_Movaghat_1_0 (1 if type is main, else 0)
|
||||
$finCustomer->tahesab_id, // Moshtari_Code
|
||||
$fin_doc->id, // Factor_Number
|
||||
0, // Radif_Number
|
||||
$shamsiYear, // Shamsi_Year
|
||||
$shamsiMonth, // Shamsi_Month
|
||||
$shamsiDay, // Shamsi_Day
|
||||
$fin_doc['type'] == ($fin_doc->type == 2) ? 1 : 0, // IsDayaftAzMoshtariOrPardakhtBeMoshtari_0_1
|
||||
(int)$fin_doc['amount'], // Mablagh
|
||||
sprintf(
|
||||
"receive_account_number(شماره حساب دریافتکننده): %s,
|
||||
receive_bank(بانک دریافتکننده): %s,
|
||||
receive_name(نام دریافتکننده): %s,
|
||||
send_account_number(شماره حساب فرستنده): %s,
|
||||
send_bank(بانک فرستنده): %s,
|
||||
send_name(نام فرستنده): %s",
|
||||
$fin_doc['receive_account_number'],
|
||||
$fin_doc['receive_bank'],
|
||||
$fin_doc['receive_name'],
|
||||
$fin_doc['send_account_number'],
|
||||
$fin_doc['send_bank'],
|
||||
$fin_doc['send_name'],
|
||||
// $fin_doc['finance_code']
|
||||
), // Sharh
|
||||
$tahesab_bank,
|
||||
$Code_Rahgiri = $fin_doc['track_number']
|
||||
];
|
||||
if(!isset($fin_doc->finance_code)) {
|
||||
$mainResponce = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewSanadVKHBank' => $DoNewSanadVKHGOLD
|
||||
])->json();
|
||||
$fin_doc->finance_code = $mainResponce['OK'];
|
||||
$fin_doc->finance_Sh_factor = $mainResponce['Sh_factor'];
|
||||
// $fin_doc->type=$mainResponce('Radif');
|
||||
$fin_doc->save();
|
||||
return response()->json(true);
|
||||
}
|
||||
}
|
||||
public function verifyAuto(Request $request ,$id)
|
||||
{
|
||||
|
||||
if (empty($request->pass_key) || $request->pass_key != "207@limaN") {
|
||||
return response()->json(["message" => "رمز نادرست میباشد"], 422);
|
||||
}
|
||||
$fin_doc = FinancialDoc::findOrFail($id);
|
||||
if ($fin_doc->type==1) {
|
||||
return response()->json(["message" => "عملیات مورد نظر برای سندهای از نوع واریز مجاز نیست."], 422);
|
||||
}
|
||||
if ($fin_doc->sts!=1) {
|
||||
return response()->json(["message" => "این پرداخت قبلاً ثبت شده است."], 422);
|
||||
}
|
||||
$token = '9u-exPK-6IeUQVKmLD9LvIE1Qmhnw_RV-MPZvg1r5zQ';
|
||||
// $productBody = [
|
||||
// 'title' => 'خروجی نقدی',
|
||||
// 'description' => 'ساخته شده توسط وبسایت لیمان گلد',
|
||||
// 'notifyUrl' => 'https://limangold.ir/kernel/notifyUrlInServer/withdraw/1',
|
||||
// 'transferType' => 0,
|
||||
// 'about' => 0,
|
||||
// 'settlements' => [
|
||||
// [
|
||||
// 'amount' => $fin_doc->amount, // مقدار را بهروز کنید
|
||||
// 'iban' => 'IR390120020000005586468860',
|
||||
// 'description' => 'پرداخت به امیر محمد حاج ابوالفتح',
|
||||
// 'clientRefId' => '1', // مقدار منحصر به فرد
|
||||
// 'mobile' => '09123456789', // شماره موبایل مشتری
|
||||
// 'nationalId' => '1234567890', // کد ملی مشتری
|
||||
// 'fullName' => 'امیر محمد حاج ابوالفتح',
|
||||
// ]
|
||||
// ]
|
||||
// ];
|
||||
$cu = Customer::find($fin_doc->customer_id);
|
||||
$productBody = [
|
||||
'title' => $cu->name . ' خروجی نقدی برای ',
|
||||
'description' => $fin_doc->description . ' ساخته شده توسط وبسایت لیمان گلد',
|
||||
'notifyUrl' => 'https://limangold.ir/kernel/notifyUrlInServer/withdraw/' . $fin_doc->id,
|
||||
'transferType' => 0,
|
||||
'about' => 0,
|
||||
'settlements' => [
|
||||
[
|
||||
'amount' => $fin_doc->amount,
|
||||
'iban' => 'IR' . $fin_doc->receive_bank_shaba,
|
||||
'description' => $fin_doc->description,
|
||||
'clientRefId' => '1', // مقدار منحصر به فرد
|
||||
'mobile' => '09123456789', // شماره موبایل مشتری
|
||||
'nationalId' => '1234567890', // کد ملی مشتری
|
||||
'fullName' => $fin_doc->receive_bank_shaba,
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . "$token",
|
||||
'Content-Type' => 'application/json',
|
||||
])->post("https://api.payping.ir/v1/cash-out/requests", $productBody);
|
||||
// $response = [
|
||||
// "requestCode" => "rbWMp",
|
||||
// "settlements" => [
|
||||
// [
|
||||
// "settlementCode" => "ky27nM",
|
||||
// "clientRefId" => "1"
|
||||
// ]
|
||||
// ]
|
||||
// ];
|
||||
if ($response->failed()) {
|
||||
return response()->json(['message' => $response[0]['error']], 422);
|
||||
}
|
||||
$fin_doc = FinancialDoc::findOrFail($id);
|
||||
$fin_doc->sts = 4;
|
||||
$fin_doc->pcode = $response['settlements'][0]['settlementCode'];
|
||||
$fin_doc->save();
|
||||
$this->payPingQuery();
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function payPingQuery()
|
||||
{
|
||||
$fins = FinancialDoc::query()->get();
|
||||
$token = '9u-exPK-6IeUQVKmLD9LvIE1Qmhnw_RV-MPZvg1r5zQ';
|
||||
$payping = Http::withToken($token)->get("https://api.payping.ir/v1/cash-out/requests/settlements")->json();
|
||||
foreach ($payping['data'] as $PPRow){
|
||||
foreach ($fins as $finRow){
|
||||
if ($PPRow['code'] == $finRow->track_number){
|
||||
$finRow->paypingdata = $PPRow;
|
||||
$finRow->save();
|
||||
if ($PPRow['status']==3){
|
||||
$finRow->sts = 2;
|
||||
$finRow->track_number = $PPRow['bankTransferReference'];
|
||||
$finRow->description = $PPRow['description']." کد پی پینگ ". $PPRow['code'];
|
||||
$finRow->save();
|
||||
}else{
|
||||
$finRow->sts = 3;
|
||||
$finRow->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return (true);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\Customer;
|
||||
use App\Models\FinDocTalla;
|
||||
use App\Models\Price;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Models\User;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
//use Carbon\Carbon;
|
||||
|
||||
|
||||
class FinDocTallaController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct(FinDocTalla::class, ['customer', 'transaction', 'product','admin'], ['*', FinDocTalla::$SELECT_DAJ, FinDocTalla::$SELECT_TYPE_STR, FinDocTalla::$SELECT_STS_STR]);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
|
||||
// $data = $request->all();
|
||||
// $data['sts'] = 1;
|
||||
// $fin_doc = FinDocTalla::create($data);
|
||||
// return $fin_doc;
|
||||
$data = $request->all();
|
||||
$data['sts'] = 1;
|
||||
$data['user_id'] = auth('user')->id();
|
||||
// $data['type']='type';
|
||||
$fin_doc = FinDocTalla::create($data);
|
||||
$fin_doc->type = $data['type'];
|
||||
$fin_doc->save();
|
||||
|
||||
return $this->resultCreate($fin_doc->id);
|
||||
}
|
||||
|
||||
public function verify($id)
|
||||
{
|
||||
$deposit = true;
|
||||
$note = 'سند ورود طلا';
|
||||
$fin_doc = FinDocTalla::findOrFail($id);
|
||||
$date = Jalalian::fromCarbon(\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $fin_doc['date_at']));
|
||||
$shamsiYear = $date->getYear();
|
||||
$shamsiMonth = $date->getMonth();
|
||||
$shamsiDay = $date->getDay();
|
||||
$finCustomer = Customer::where('id', $fin_doc['customer_id'])->first();
|
||||
$mOrM = 0;
|
||||
|
||||
$DoNewSanadVKHGOLD = [
|
||||
1, // Sabte_Kol_Or_Movaghat_1_0 (assuming type 1 is main, else 0)
|
||||
$finCustomer->tahesab_id, // Moshtari_Code
|
||||
$fin_doc->id, // Factor_Number
|
||||
1, // Radif_Number
|
||||
$shamsiYear, // Shamsi_Year
|
||||
$shamsiMonth, // Shamsi_Month
|
||||
$shamsiDay, // Shamsi_Day
|
||||
(float)$fin_doc['weight'], // Vazn
|
||||
(int)$fin_doc['ayar'], // Ayar
|
||||
(int)$fin_doc['ang'], // Ang_Number
|
||||
$fin_doc['lab'], // Name_az
|
||||
($fin_doc->type == 2) ? 1 : 0, // IsVoroodOrKhorooj_0_1 (example logic)
|
||||
($fin_doc->type_fin == "آبشده") ? 1 : 0,
|
||||
$fin_doc->description
|
||||
|
||||
|
||||
];
|
||||
$cash_interface = new WalletInterface($finCustomer->id, $finCustomer->type);
|
||||
if ($fin_doc->type == 2) {
|
||||
$deposit = false;
|
||||
$note = 'سند خروجی';
|
||||
}
|
||||
new TransactionInterface($cash_interface, $_inp = [
|
||||
"amount" => $fin_doc->amount,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'fin_doc_id' => $fin_doc->id,
|
||||
'note' => $note
|
||||
], $finCustomer->type, $deposit);
|
||||
|
||||
|
||||
if(!isset($fin_doc->finance_code)) {
|
||||
$mainResponce = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewSanadVKHGOLD' => $DoNewSanadVKHGOLD
|
||||
]);
|
||||
|
||||
$fin_doc->finance_code = $mainResponce['OK'];
|
||||
$fin_doc->finance_Sh_factor = $mainResponce['Sh_factor'];
|
||||
$fin_doc->admin_id = auth()->id();
|
||||
$fin_doc->save();
|
||||
|
||||
}
|
||||
|
||||
$cu = Customer::findOrFail($fin_doc->customer_id);
|
||||
$cash_interface = new WalletInterface($cu->id, $cu->type, $fin_doc->product_id);
|
||||
if ($fin_doc->type == 2) {
|
||||
$deposit = false;
|
||||
$note = 'سند خروج طلا';
|
||||
}
|
||||
$this->createTransactionFinDocTalla($cash_interface, $fin_doc->weight, $deposit, $fin_doc->id, $cu->type, $fin_doc->product_id, $note);
|
||||
$fin_doc->sts = 2;
|
||||
$fin_doc->save();
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = FinDocTalla::with(['user','customer']);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['type_fin',"customer.name",'lab'])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function createTransactionFinDocTalla($wallet_interface, $amount, $deposit, $fin_doc_id, $_type, $product_id, $note)
|
||||
{
|
||||
new TransactionInterface($wallet_interface, $_inp = [
|
||||
"amount" => $amount,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'fin_doc_talla_id' => $fin_doc_id,
|
||||
'product_id' => $product_id,
|
||||
'note' => $note
|
||||
], $_type, $deposit);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Havaleh;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
|
||||
class HavalehController extends Controller
|
||||
{
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = Havaleh::with('creator_customer','getter_customer',"product");
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*',Havaleh::$SELECT_STS_STR,
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function show($id){
|
||||
return response()->json(
|
||||
Havaleh::with(['creator_customer','getter_customer'])->select(['*',Havaleh::$SELECT_STS_STR])->findOrFail($id)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public function changeStatus(Request $request)
|
||||
{
|
||||
|
||||
$data = $request->all();
|
||||
|
||||
|
||||
$havaleh = Havaleh::findOrFail($data['havaleh_id']);
|
||||
|
||||
if ($havaleh->sts == 1){
|
||||
return response()->json(true);
|
||||
}
|
||||
if ($data['sts'] == 2){
|
||||
$havaleh->update(['sts'=>$data['sts']]);
|
||||
return response()->json(true);
|
||||
}
|
||||
if ($data['sts'] == 1){
|
||||
$getter = Customer::findOrFail($data['getter_customer_id'])->toArray();
|
||||
//bug
|
||||
// عملیات کم کردن از و اضافه کردن به کیف پول
|
||||
|
||||
//کم کردن
|
||||
// - _type چیه ؟ -
|
||||
|
||||
$creator = $havaleh->creator_customer()->get()->toArray()[0];
|
||||
$cash_interface = new WalletInterface($creator['id'], $creator['type'],$havaleh->product_id);
|
||||
$this->createTransactionHavale($cash_interface,$havaleh['amount'],false,1,$havaleh->id);
|
||||
|
||||
//افزودن
|
||||
$product_interface = new WalletInterface($getter['id'], $getter['type'],$havaleh->product_id);
|
||||
$this->createTransactionHavale($product_interface,$havaleh['amount'],true,1,$havaleh->id);
|
||||
|
||||
$havaleh->update(['sts'=>$data['sts'],'getter_customer_id'=>$data['getter_customer_id']]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
public function createTransactionHavale($wallet_interface, $amount,$deposit,$_type,$havaleh_id){
|
||||
new TransactionInterface($wallet_interface, $_inp = [
|
||||
"amount"=> $amount,
|
||||
"product_id"=>$wallet_interface->wallet->product_id,
|
||||
'expire_at'=>now(),
|
||||
'active'=>true,
|
||||
'havaleh_id'=>$havaleh_id,
|
||||
'note'=>'بابت حواله'
|
||||
], $_type, $deposit);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Models\Message;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Carbon\Carbon;
|
||||
|
||||
|
||||
class MassageController extends Controller
|
||||
{
|
||||
public function messagesTable(Request $request)
|
||||
{
|
||||
// استخراج دادهها از جدول Messages
|
||||
$records = Message::whereNotNull('sms'); // فرض بر این است که نام فیلد صحیح 'sms' است
|
||||
|
||||
// تنظیمات TableEngine
|
||||
$table = TableEngine::create($records, $request->all())
|
||||
->initSearch(['receiver','sms']) // تنظیم فیلدهای جستجو در صورت نیاز
|
||||
->select([
|
||||
'id', 'sms', 'receiver', // لیست فیلدهای مورد نیاز را اضافه کنید
|
||||
// سایر فیلدها و محاسبات اضافی در صورت نیاز
|
||||
]);
|
||||
// برگرداندن دادهها در قالب JSON
|
||||
return response()->json($table->export());
|
||||
}
|
||||
/**
|
||||
* Display a listing of the messages.
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$messages = Message::all();
|
||||
return response()->json($messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created message in storage.
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'sms' => 'required|string',
|
||||
'receiver' => 'required|string',
|
||||
]);
|
||||
|
||||
$message = Message::create($request->only(['sms', 'receiver']));
|
||||
|
||||
return response()->json($message, 201);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified message.
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$message = Message::findOrFail($id);
|
||||
return response()->json($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified message in storage.
|
||||
*/
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$request->validate([
|
||||
'sms' => 'sometimes|required|string',
|
||||
'receiver' => 'sometimes|required|string',
|
||||
]);
|
||||
|
||||
$message = Message::findOrFail($id);
|
||||
$message->update($request->only(['sms', 'receiver']));
|
||||
|
||||
return response()->json($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified message from storage.
|
||||
*/
|
||||
public function destroy($id)
|
||||
{
|
||||
$message = Message::findOrFail($id);
|
||||
$message->delete();
|
||||
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
public function getSmsList(Request $request )
|
||||
{
|
||||
// return 1;
|
||||
if($request->Header('sicrtToken') !== 'dlrA0mAsfpixA5wgCOPK2khVtFE32vBLGqUHvSvLVkMaHNdHE5'){
|
||||
return response()->json(['auth_needed'],401);
|
||||
}
|
||||
function SmsPrice($sms)
|
||||
{
|
||||
$charCount = mb_strlen($sms, "UTF-8");
|
||||
$isPersian = preg_match('/[آ-ی]/u', $sms);
|
||||
$isEnglish = preg_match('/[a-zA-Z]/u', $sms);
|
||||
$limit = ($isPersian && !$isEnglish) ? [70, 64, 67] : [160, 146, 153];
|
||||
$smsCount = ceil($charCount / $limit[0]);
|
||||
if ($isEnglish) {
|
||||
$smsCount *= 2;
|
||||
}
|
||||
return $smsCount;
|
||||
}
|
||||
|
||||
$startDate = Carbon::parse($request->startDate)->startOfDay();
|
||||
$endDate = Carbon::parse($request->endDate)->endOfDay();
|
||||
$messages = Message::with([])->whereBetween('created_at', [$request->startDate, $request->endDate])->get();
|
||||
foreach ($messages as $message) {
|
||||
if(strpos($message->platforms,'0098:')===0){
|
||||
$message->price=SmsPrice($message->sms);
|
||||
}else{
|
||||
$message->price =0;
|
||||
}
|
||||
$message->save();
|
||||
}
|
||||
return $messages;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\MessageNotification;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class MessageNotificationController extends Controller
|
||||
{
|
||||
public function getAdminMessages(Request $request)
|
||||
{
|
||||
$records = MessageNotification::query()
|
||||
->where('is_admin', true);
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['title','start_at'])
|
||||
->select([
|
||||
'*', MessageNotification::$SELECT_SAJ, MessageNotification::$SELECT_EAJ, MessageNotification::$SELECT_TYPE_STR
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function getAgentMessages(Request $request)
|
||||
{
|
||||
$records = MessageNotification::query()
|
||||
->where('is_admin', false);
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*', MessageNotification::$SELECT_SAJ, MessageNotification::$SELECT_EAJ, MessageNotification::$SELECT_TYPE_STR
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->only(['title', 'text', 'type', 'start_at', 'end_at']);
|
||||
$data['is_admin'] = true;
|
||||
$data['creator_id'] = auth('user')->user()->id;
|
||||
MessageNotification::query()->create($data);
|
||||
return response()->json(true);
|
||||
}
|
||||
public function destroy($id)
|
||||
{
|
||||
$user = auth('user')->user();
|
||||
$message = MessageNotification::query()->findOrFail($id);
|
||||
$message->delete();
|
||||
return response()->json(true);
|
||||
}
|
||||
public function active($id){
|
||||
$message = MessageNotification::query()->findOrFail($id);
|
||||
$message->update([
|
||||
'is_active' => !$message->is_active
|
||||
]);
|
||||
return response()->json(true);
|
||||
}
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$data = $request->only(['title', 'text', 'type', 'start_at', 'end_at']);
|
||||
MessageNotification::query()->findOrFail($id)->update($data);
|
||||
return response()->json(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,470 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Admin\OrderController as AdminOrderController;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\CancelJob;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\CustomerCredit;
|
||||
use App\Models\Order;
|
||||
use App\Models\Package;
|
||||
use App\Models\PackageProduct;
|
||||
use App\Models\Price;
|
||||
use App\Jobs\ValidateOrder;
|
||||
use App\Models\Product;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
|
||||
// $request = new Request([
|
||||
// "direction"=>$request->direction,
|
||||
// "price"=>$request->price,
|
||||
// "pay_at"=>$request->pay_at,
|
||||
// "amount"=>$request->amount,
|
||||
// "customer_id"=>23,
|
||||
// "product_id"=>2,
|
||||
// "description"=>$request->description,
|
||||
// "cash"=>$request->payment_amount,
|
||||
// ]);
|
||||
|
||||
// Check if an order with the same amount, direction, customer_id, and created_at already exists
|
||||
$existingOrder = Order::where('amount', $data['amount'])
|
||||
->where('direction', $data['direction'])
|
||||
->where('customer_id', $data['customer_id'])
|
||||
->where('pay_at', $data['pay_at'])
|
||||
->first();
|
||||
|
||||
if ($existingOrder) {
|
||||
return response()->json(['message' => 'Duplicate order detected'], 422);
|
||||
}
|
||||
|
||||
// If no duplicate order exists, create the new order
|
||||
|
||||
|
||||
$Customer = Customer::where('id', $data['customer_id'])->first();
|
||||
$product = Product::find($data['product_id']);
|
||||
|
||||
$add_sell_price = 0;
|
||||
$PriceMain = Price::where('product_id', $data['product_id'])->orderBy('id', 'desc')->first();
|
||||
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
$data['price'] = (float)$data['price'] / $mesghal_convert;
|
||||
$base = Package::where('is_base', true)->first();
|
||||
$package_base = PackageProduct::where('package_id', $base->id)->where('product_id', $data['product_id'])->first();
|
||||
$package = null;
|
||||
$package = PackageProduct::where('package_id', $Customer->package_id)->where('product_id', $data['product_id'])->first();
|
||||
|
||||
$data['customer_id'] = $Customer->id;
|
||||
$data['sts'] = 1;
|
||||
$data['payment_sts'] = 1;
|
||||
$data['type'] = $Customer->type;
|
||||
|
||||
$response['credit'] = $credit = CustomerCredit::firstOrCreate(
|
||||
['product_id' => $data['product_id'], 'customer_id' => $Customer->id,],
|
||||
['product_id' => $data['product_id'], 'customer_id' => $Customer->id,
|
||||
'buy_credit' => $product->default_credit, 'sell_credit' => $product->default_credit]);
|
||||
|
||||
if ($data['direction'] == 1) {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->buy_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->buy_gram_price;
|
||||
$data['fee_agent'] = $package->buy_gram_price;
|
||||
$data['total_fee_agent'] = $package->buy_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->buy_credit - $credit->blocked_buy_credit;
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_buy_credit' => $credit->blocked_buy_credit + $data['amount']
|
||||
]);
|
||||
} else {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->sell_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->sell_gram_price;
|
||||
$data['fee_agent'] = $package->sell_gram_price;
|
||||
$data['total_fee_agent'] = $package->sell_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->sell_credit - $credit->blocked_sell_credit;
|
||||
if ($remain < $data['amount']) {
|
||||
throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
|
||||
}
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_sell_credit' => $credit->blocked_sell_credit + $data['amount']
|
||||
]);
|
||||
}
|
||||
$data['total_price'] = $data['amount'] * $data['price'];
|
||||
$data['payment_remind'] = 0;
|
||||
$data['payment_amount'] = $data['total_price'];
|
||||
$data['agent_id'] = $Customer->agent_id;;
|
||||
$data['total_price_round'] = round($data['total_price'], -6);
|
||||
$data['price_id'] = $PriceMain->id;
|
||||
$data['admin_id'] = Auth::user()->id ?? 2;
|
||||
$order = Order::create($data);
|
||||
$request = [
|
||||
'method' => $data["method"],
|
||||
'order_id' => $order->id,
|
||||
'sts' => 2,
|
||||
];
|
||||
$request = new Request($request);
|
||||
$NewOrder = $this->changeStatus($request, $data["pay_at"]);
|
||||
return response()->json($NewOrder);
|
||||
}
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = Order::with(['customer.agent', 'product']);
|
||||
// $records->where('amount','=', (int)$request->input('amount'));
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['product.title', 'payment_amount', 'amount'])
|
||||
->select([
|
||||
'*', Order::$SELECT_STS_STR, Order::$SELECT_CAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
// fix round prise
|
||||
foreach ($records->cursor() as $order) {
|
||||
/* full prise by orginal prise
|
||||
if ($order->direction==1) {
|
||||
$order->total_price = $order->total_price_original + $order->total_fee_full;
|
||||
$order->save();
|
||||
}
|
||||
elseif ($order->direction==2) {
|
||||
$order->total_price = $order->total_price_original - $order->total_fee_full;
|
||||
$order->save();
|
||||
}*/
|
||||
$order->total_price_round = round($order->total_price, -6);
|
||||
$order->save();
|
||||
// if (!isset($order->total_price_round)) {
|
||||
// $order->total_price_round = round($order->total_price ,-5) ;
|
||||
// $order->save();
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function tableS(Request $request)
|
||||
{
|
||||
if ($request->header('sicrtToket') !== '4GmI2B6!pz8Fp7TV9GNS6&V&@50*yS%3INKX%Su6#*cxy0X3Cq8ST1W5TUQ2') {
|
||||
return response()->json(['auth needed'], 401);
|
||||
}
|
||||
$records = Order::with(['customer', 'product'])->whereNotNull('finance_code')->where('sts', 2)->orderBy('id', 'desc')->limit(2)->get();
|
||||
|
||||
// تبدیل نتیجه به JSON
|
||||
return response()->json($records);
|
||||
|
||||
}
|
||||
|
||||
public function verifyS(Request $request)
|
||||
{
|
||||
if ($request->header('sicrtToket') !== '4GmI2B6!pz8Fp7TV9GNS6&V&@50*yS%3INKX%Su6#*cxy0X3Cq8ST1W5TUQ2') {
|
||||
return response()->json(['auth needed'], 401);
|
||||
}
|
||||
$records = Order::where('id', $request[0]['refTo'])->first();
|
||||
$records->finance_order = $request->all();
|
||||
$records->save();
|
||||
|
||||
// تبدیل نتیجه به JSON
|
||||
return response()->json($records);
|
||||
|
||||
}
|
||||
|
||||
public function tableNew(Request $request)
|
||||
{
|
||||
$records = Order::with(['customer.agent', 'product'])->where('sts', 1);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['product_id->title'])
|
||||
->select([
|
||||
'*', Order::$SELECT_STS_STR, Order::$SELECT_CAJ
|
||||
])->export($records);
|
||||
foreach ($records['rows'] as &$order) {
|
||||
$order->direction = ($order->direction == 2)?1:2;
|
||||
$order->time_at = \Carbon\Carbon::parse($order->pay_at)->format('H:i:s');
|
||||
if ($_SERVER['HTTP_HOST'] == 'emexgold.com'){
|
||||
$order->rate_price_final_map = '';
|
||||
}
|
||||
}
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
$o= Order::with(['customer', 'product'])->select(['*', Order::$SELECT_STS_STR])->findOrFail($id);
|
||||
|
||||
return response()->json($o
|
||||
);
|
||||
}
|
||||
|
||||
public function changeStatus(Request $request, $adminCustomDate = null)
|
||||
{
|
||||
// return 1;
|
||||
// return ($this->Config('name_en') == "Liman Gold");
|
||||
|
||||
|
||||
$token = env('TOKEN_750_KALHOR');
|
||||
$data = $request->all();
|
||||
$order = Order::with(['product.price'])->findOrFail($data['order_id']);
|
||||
$directionText = ($order->direction == 1) ? 'Buy' : 'Sell';
|
||||
$product = Product::findOrFail($order->product_id);
|
||||
|
||||
|
||||
if ($order->sts == 2) {
|
||||
// return response()->json(true);
|
||||
}
|
||||
if ($data['sts'] == 2) {
|
||||
if ($order->direction == 1) {
|
||||
$this->createTransactionBuyWhenSuccess($order);
|
||||
} else {
|
||||
$this->createTransactionSellWhenSuccess($order);
|
||||
}
|
||||
} elseif ($data['sts'] == 3) {
|
||||
$mesghal = null;
|
||||
if ($request->has('offer_mesghal_price')) {
|
||||
$mesghal = $data['offer_mesghal_price'];
|
||||
}
|
||||
$order->update([
|
||||
'offer_price' => $data['offer_price'],
|
||||
'offer_mesghal_price' => $mesghal
|
||||
]);
|
||||
}
|
||||
if (!$order['pay_at']) {
|
||||
$order['pay_at'] = $order['created_at']; // Fallback to created_at if pay_at is not set
|
||||
}
|
||||
$dateOnly = substr($order['pay_at'], 0, 10); // "2024-08-24"
|
||||
$order->update(['sts' => $data['sts']]);
|
||||
$date = Jalalian::fromCarbon(\Carbon\Carbon::createFromFormat('Y-m-d', $dateOnly));
|
||||
$shamsiYear = $date->getYear();
|
||||
$shamsiMonth = $date->getMonth();
|
||||
$shamsiDay = $date->getDay();
|
||||
$orderCustomer = Customer::with(['package'])->where('id', $order->customer_id)->first();
|
||||
|
||||
$DoNewSanadBuySaleGOLD = [];
|
||||
|
||||
$DoNewSanadBuySaleGOLD[] = [
|
||||
1, // Sabte_Kol_Or_Movaghat_1_0 (assuming type 1 is main)
|
||||
$orderCustomer->tahesab_id, // Moshtari_Code
|
||||
$order->id, // Factor_Number
|
||||
0, // Radif_Number
|
||||
$shamsiYear, // Shamsi_Year
|
||||
$shamsiMonth, // Shamsi_Month
|
||||
$shamsiDay, // Shamsi_Day
|
||||
(float)$order->amount, // Vazn
|
||||
750, // Ayar
|
||||
null, // Ang_Number
|
||||
null, // Name_az
|
||||
$order->direction == 1 ? 1 : 0, // IsVoroodOrKhorooj_0_1
|
||||
$order->rate_price_final, // Mazaneh liman
|
||||
0, // MazanehIsMesghalOrGeram_0_1
|
||||
1, // IsMotefaregheOrAbshode_0_1
|
||||
$order->payment_amount, // MablaghKol
|
||||
$order->description, // description
|
||||
];
|
||||
// if (isset($order->agent_id)) {
|
||||
// if ($orderAgent = Customer::with(['package'])->where('id', $order->agent_id)->first()) {
|
||||
// $sub_customer = PackageProduct::where('package_id', $orderCustomer->package->id)->where('product_id', $order->product_id)->first();
|
||||
// if ($order->direction == 2) {
|
||||
// $agMazaneh = $order->price_in_mesghal + ($sub_customer->buy_price);
|
||||
// } else {
|
||||
// $agMazaneh = $order->price_in_mesghal - ($sub_customer->buy_price);
|
||||
// }
|
||||
// if ($order->input_mode == 'gold') {
|
||||
// $agGold = (float)$order->amount;
|
||||
// $agCash = $agGold * ($agMazaneh / 4.331802);
|
||||
// } else {
|
||||
// $agCash = $order->payment_amount;
|
||||
// $agGold = $agCash / $agMazaneh * 4.331802;
|
||||
// }
|
||||
// $DoNewSanadBuySaleGOLD[] = [
|
||||
// 1, // Sabte_Kol_Or_Movaghat_1_0 (assuming type 1 is main)
|
||||
// $orderAgent->tahesab_id, // Moshtari_Code
|
||||
// $order->id, // Factor_Number
|
||||
// 1, // Radif_Number
|
||||
// $shamsiYear, // Shamsi_Year
|
||||
// $shamsiMonth, // Shamsi_Month
|
||||
// $shamsiDay, // Shamsi_Day
|
||||
// $agGold, // Vazn
|
||||
// 750, // Ayar
|
||||
// null, // Ang_Number
|
||||
// null, // Name_az
|
||||
// $order->direction == 1 ? 1 : 0, // IsVoroodOrKhorooj_0_1
|
||||
// $agMazaneh, // Mazaneh
|
||||
// 0, // MazanehIsMesghalOrGeram_0_1
|
||||
// 1, // IsMotefaregheOrAbshode_0_1
|
||||
// $agCash, // MablaghKol
|
||||
// $order->description, // description
|
||||
// ];
|
||||
// $DoNewSanadBuySaleGOLD[] = [
|
||||
// 1, // Sabte_Kol_Or_Movaghat_1_0 (assuming type 1 is main)
|
||||
// $orderAgent->tahesab_id, // Moshtari_Code
|
||||
// $order->id, // Factor_Number
|
||||
// 2, // Radif_Number
|
||||
// $shamsiYear, // Shamsi_Year
|
||||
// $shamsiMonth, // Shamsi_Month
|
||||
// $shamsiDay, // Shamsi_Day
|
||||
// (float)$order->amount, // Vazn
|
||||
// 750, // Ayar
|
||||
// null, // Ang_Number
|
||||
// null, // Name_az
|
||||
// $order->direction == 1 ? 0 : 1, // IsVoroodOrKhorooj_0_1
|
||||
// $order->price_in_mesghal, // Mazaneh
|
||||
// 0, // MazanehIsMesghalOrGeram_0_1
|
||||
// 1, // IsMotefaregheOrAbshode_0_1
|
||||
// $order->payment_amount, // MablaghKol
|
||||
// $order->description,// description
|
||||
// ];
|
||||
// }
|
||||
// }
|
||||
$DoNewSanadBuySaleGOLD;
|
||||
$response = [];
|
||||
|
||||
if ($this->Config('tahesab') == "send_importent") {
|
||||
if ($order->sts == 2) {
|
||||
if (!$order->finance_code) {
|
||||
if ($product->finance_type == 'coin'){
|
||||
$DoNewSanadVKHSEKEH =[
|
||||
1, // Main record (1 = ثبت کل)
|
||||
$orderCustomer->tahesab_id, // Customer code
|
||||
$order->id, // Invoice number
|
||||
0, // Row number
|
||||
$shamsiYear, // Shamsi_Year
|
||||
$shamsiMonth, // Shamsi_Month
|
||||
$shamsiDay, // Shamsi_Day
|
||||
$order->product->amount*$order->amount, // Weight in grams
|
||||
750, // 18k gold (750)
|
||||
$order->amount, // 2 coins
|
||||
$order->product->title, // Coin name (Bahar Azadi)
|
||||
$order->direction == 1 ? 0 : 1, // IsVoroodOrKhorooj_0_1
|
||||
$order->price, // mazneh (optional)
|
||||
$order->total_price , // Total amount (12,500,000 Rials)
|
||||
$order->description , // Description
|
||||
// Invoice code (reference)
|
||||
];
|
||||
|
||||
$response[] = $mainResponce = Http::withoutVerifying()
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewSanadBuySaleSEKEH' => $DoNewSanadVKHSEKEH
|
||||
])->json();
|
||||
}else{
|
||||
foreach ($DoNewSanadBuySaleGOLD as $DoNewSanadBuySaleGOLDRow) {
|
||||
$response[] = $mainResponce = Http::withoutVerifying()
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoNewSanadBuySaleGOLD' => $DoNewSanadBuySaleGOLDRow
|
||||
])->json();
|
||||
}
|
||||
}
|
||||
$order->finance_code = $mainResponce['OK'];
|
||||
$order->finance_Sh_factor = $mainResponce['Sh_factor'];
|
||||
$order->save();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
$isCansel = ($order->sts == 2) ? 'تایید' : 'رد';
|
||||
$message = $orderCustomer->name . " عزیز" . "\n"
|
||||
. 'در تاریخ ' . verta()->format('Y/n/j H:i:s') . " سفارش شما $isCansel شد. " . "\n"
|
||||
. "با تشکر" . $this->Config('name_fa');
|
||||
|
||||
$this->sendMessage(trim($orderCustomer->mobile), $message);
|
||||
|
||||
|
||||
if($this->Config('name_en') == "appgold"){
|
||||
$teleresponse = null;
|
||||
if ($order->sts == 2) {
|
||||
|
||||
$mMaz = number_format($order['price_in_mesghal'] / 10000, 0);
|
||||
$mDirc = $order['direction'] == 2 ? "🔴" : "🟢";
|
||||
|
||||
if ($order['input_mode'] == 'cash') {
|
||||
$val = number_format($order['payment_amount'], 0);
|
||||
$eqalto = number_format($order['amount'], 3);
|
||||
} else {
|
||||
$eqalto = number_format($order['payment_amount'], 0);
|
||||
$val = number_format($order['amount'], 3);
|
||||
}
|
||||
$mCustomerName = $order['customer']['name'];
|
||||
$adminsMessage = $mDirc . " " . $mCustomerName;
|
||||
|
||||
if (isset($order['description'])) {
|
||||
$adminsMessage .= " (" . $order['description'] . ")";
|
||||
}
|
||||
$adminsMessage .= "\n" . "🛒 " . $product->title;
|
||||
$adminsMessage .= "\n" . " " . $val . "@" . $mMaz . "=" . $eqalto;
|
||||
|
||||
$botToken = '7547588069:AAFqjwkqUcR1gFEU0BVeZLsVY12FG_ULn28';
|
||||
$chatId = '-4762835299';
|
||||
$url = 'https://api.wwwapp.ir/telegran_send.php';
|
||||
|
||||
$teleresponse = Http::get($url, [
|
||||
'chatId' => $chatId,
|
||||
'message' => $adminsMessage,
|
||||
'botToken' => $botToken,
|
||||
]);
|
||||
}
|
||||
}
|
||||
return response()->json([
|
||||
'response' => $response,
|
||||
'order' => $order,
|
||||
]);
|
||||
|
||||
}
|
||||
|
||||
public function createTransactionClear($wallet_interface, $amount, $order)
|
||||
{
|
||||
$_type = $order->direction;
|
||||
new TransactionInterface($wallet_interface, $_inp = [
|
||||
"amount" => $amount,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'order_id' => $order->id,
|
||||
'note' => 'بابت تسویه سود'
|
||||
], $_type, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function clearing(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
$orders = Order::where('agent_id', $data['agent_id'])->whereDate('created_at', '<=', $data['end_at'])->where('sts', 2)->get();
|
||||
$wallet_interface = new WalletInterface($data['agent_id'], 1);
|
||||
foreach ($orders as $order) {
|
||||
$this->createTransactionClear($wallet_interface, $order->total_fee_agent, $order);
|
||||
$order->sts = 5;
|
||||
$order->save();
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Http\Controllers\SuperPackageController;
|
||||
use App\Models\Customer;
|
||||
use App\Models\{Package,CustomersSetting};
|
||||
use App\Models\PackageProduct;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class PackageController extends SuperPackageController
|
||||
{
|
||||
public function __construct(Request $request)
|
||||
{
|
||||
// $this->with = ['agent', 'avatar'];
|
||||
// $this->select = ['*', Customer::$SELECT_CAJ, Customer::$SELECT_TYPE_STR];
|
||||
// parent::__construct(Customer::class, $this->with, $this->select, 'customer', null, );
|
||||
|
||||
$request->request->add(['user_creator_id'=>auth('user')->id(),'is_base'=>false]);
|
||||
$this->search = ['agent.name', 'agent.mobile', 'title', 'customer.name'];
|
||||
|
||||
parent::__construct(['customer','agent','sub_packages.product'], ['*'], null, $this->search);
|
||||
}
|
||||
|
||||
// public function tablePackage(Request $request)
|
||||
// {
|
||||
// $data = $request->all();
|
||||
// if (isset($data["select"]) && is_null($data["select"])){
|
||||
// $data["select"] = [];
|
||||
// }
|
||||
// if (is_null($this->query)){
|
||||
// $query_table = Package::with($this->with)->where('for_agent', false);
|
||||
// }else{
|
||||
// $query_table = $this->query->where('is_base',false)->where('for_agent', false);
|
||||
// }
|
||||
// TableEngine::create($query_table, $data)
|
||||
// ->initSearch((['agent.name', 'agent.mobile', 'title', 'customer.name']))
|
||||
// ->select(['*', 'agent.mobile', 'title', 'customer.name'])
|
||||
// ->export($query_table);
|
||||
// return $query_table;
|
||||
// }
|
||||
|
||||
public function listPackageAgent($agent_id){
|
||||
$package = Package::where('agent_id',$agent_id)->get();
|
||||
return response()->json($package);
|
||||
}
|
||||
|
||||
public function tableAgent(Request $request)
|
||||
{
|
||||
$records = Package::query()
|
||||
->with(['sub_packages.product'])
|
||||
->where('is_base', false)
|
||||
->where('for_agent', true);
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['title','description','user_creator_id'])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function tableSettings(Request $request)
|
||||
{
|
||||
$records = CustomersSetting::query()
|
||||
->with(['agent','customer','product'])
|
||||
;
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['title'])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function listAgent()
|
||||
{
|
||||
$packages_for_agent = Package::query()
|
||||
->with(['sub_packages.product'])
|
||||
->where('is_base', false)
|
||||
->where('for_agent', true)
|
||||
->get();
|
||||
|
||||
return response()->json($packages_for_agent);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PermissionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
$permissions =Permission::where('user_type',$data['user_type'])->get()->toArray();
|
||||
$rids= array_column($permissions,'rid');
|
||||
if ($request->has('user_type')) {
|
||||
if (!is_int($request->input('user_type')) ) {
|
||||
$c = Cnt::where('key','user_type')
|
||||
->where('value',$request->input('user_type'))
|
||||
->first();
|
||||
if (is_null($c)){
|
||||
$c = Cnt::set('user_type', $request->input('user_type'));
|
||||
}
|
||||
$data['user_type'] = $c->id;
|
||||
}
|
||||
}
|
||||
foreach ($data['rid'] as $item){
|
||||
$key = array_search($item,$rids);
|
||||
if(!in_array($item , $rids)){
|
||||
Permission::create([
|
||||
'rid'=>$item,
|
||||
'user_type'=>$data['user_type']
|
||||
]);
|
||||
}
|
||||
else{
|
||||
unset($permissions[$key]);
|
||||
}
|
||||
}
|
||||
foreach ($permissions as $permission){
|
||||
Permission::find($permission['id'])->delete();
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function show($user_type)
|
||||
{
|
||||
$p =Permission::where('user_type',$user_type)
|
||||
->select('rid')
|
||||
->get()->pluck('rid')->toArray();
|
||||
$cnt = Cnt::findOrFail($user_type);
|
||||
return response()->json(['rid'=>$p,'user_type'=>$user_type, 'user_type_str'=>$cnt->value ]);
|
||||
}
|
||||
public function listConst(){
|
||||
return response()->json(Cnt::where('key','user_type')->get()->pluck('value'));
|
||||
}
|
||||
public function showRid(){
|
||||
$config = config('permission');
|
||||
return response()->json($config);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\DB\User;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Package;
|
||||
use App\Models\PackageProduct;
|
||||
use App\Models\Price;
|
||||
use App\Models\User as UserModel;
|
||||
use App\Models\PriceCandle;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Admin\BasePackageController as BC;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class PriceController extends Controller
|
||||
{
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
if (is_null($request->product_id)) {
|
||||
$this->updateAllProductPrice($request);
|
||||
return $this->b750();
|
||||
}
|
||||
$basePackage = Package::where('is_base', true)->first();
|
||||
$product = Product::with('price')->where('id', $request->product_id)->first();
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
|
||||
Price::where('product_id', $product->id)->update([
|
||||
'price' => $request->price,
|
||||
'price_gram' => $request->price / $mesghal_convert,
|
||||
'difference_provider' => 0 ,
|
||||
'difference' => $request->diff ??0 ,
|
||||
'difference_gram' => $request->diff??0 / $mesghal_convert,
|
||||
'difference_liman' => $request->diff??0,
|
||||
'date_at' => now()->format('Y-m-d'),
|
||||
'time_at' => now()->format('H:i:s'),
|
||||
]);
|
||||
$product->refresh();
|
||||
PackageProduct::where('product_id', $product->id)->where('package_id', $basePackage->id)->update([
|
||||
'buy_price' => $product->price->difference,
|
||||
'buy_gram_price' => $product->price->difference / $mesghal_convert,
|
||||
'sell_price' => $product->price->difference,
|
||||
'sell_gram_price' => $product->price->difference / $mesghal_convert,
|
||||
]);
|
||||
if ($request->is_auto){
|
||||
Product::where('id', $request->product_id)->update(['reading_method' => $request->reading_method]);
|
||||
}else{
|
||||
Product::where('id', $request->product_id)->update(['reading_method' =>'manual']);
|
||||
}
|
||||
return $this->b750();
|
||||
return response()->json(true);
|
||||
}
|
||||
public function updateAllProductPrice(Request $request)
|
||||
{
|
||||
|
||||
if ($request->has('reading_method') && $request->has('price')) {
|
||||
return response()->json(['message' => 'Cannot update both reading_method and price at the same time.'], 422);
|
||||
}
|
||||
$doChangePrice = true;
|
||||
// اگر فقط price آمده باشد، reading_method به "manual" تغییر میکند
|
||||
if ($request->has('price')) {
|
||||
$request->merge(['reading_method' => 'manual']);
|
||||
} // اگر فقط reading_method آمده باشد، قیمت تغییر نمیکند
|
||||
else if ($request->has('reading_method')) {
|
||||
$doChangePrice = false;
|
||||
}
|
||||
// اگر product_id نیامده باشد، روی همه محصولات اعمال میشود
|
||||
$products = is_null($request->product_id) ? Product::all() : Product::where('id', $request->product_id)->get();
|
||||
foreach ($products as $product) {
|
||||
// به روز رسانی اطلاعات محصول
|
||||
$product->update(['reading_method' => $request->reading_method]);
|
||||
if ($doChangePrice) {
|
||||
$lastP = Price::where('product_id', $product->id)->update([
|
||||
"price" => $request->price,
|
||||
"price_gram" => $request->price / config('change_mesghal'),
|
||||
"difference_liman" => $request->diff,
|
||||
"difference_gram" => $request->diff / config('change_mesghal'),
|
||||
"date_at" => date("Y-m-d"),
|
||||
"time_at" => now()->format("H:m:s"),
|
||||
"user_id" => auth('user')->id()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = Price::with(['user', 'product']);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(["product.title","user.name",'price','id',"user.id"])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function createLinkPricing(Request $request)
|
||||
{
|
||||
$user = UserModel::find(auth('user')->id());
|
||||
$user->token = md5(auth('user')->user().time());
|
||||
|
||||
// Convert the user object to an array for the HTTP request
|
||||
$requestData = $user->toArray();
|
||||
|
||||
$response = Http::post('https://pricing.liman.gold/auth/create_url_token', $requestData)->json();
|
||||
|
||||
return response()->json($response);
|
||||
|
||||
// $user =auth()->user();
|
||||
//
|
||||
// $keyToken='n2640NBlz%#X*88&470*';
|
||||
// $textToHash=$user->id.$keyToken;
|
||||
// $hash = hash_hmac('sha256', $textToHash, $keyToken);
|
||||
//
|
||||
// return response()->json([
|
||||
// 'user'=>$user,
|
||||
// 'hash'=>$hash,
|
||||
// 'message'=>'success'
|
||||
// ]);
|
||||
}
|
||||
|
||||
public function b750()
|
||||
{
|
||||
$response = Http::get('https://pricing.liman.gold/pricingApi', [])->json();
|
||||
$RPrices = $response;
|
||||
$products = Product::with('price')->where('active', 1)->get();
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
$basePackage = Package::where('is_base', true)->first();
|
||||
|
||||
foreach ($products as $product) {
|
||||
if (!$product->price) {
|
||||
$newPrice = Price::create([
|
||||
'price' => 1,
|
||||
'difference_liman' => 0,
|
||||
'product_id' => $product->id,
|
||||
]);
|
||||
$product->refresh();
|
||||
}
|
||||
$found = false;
|
||||
if (empty($RPrices)) {
|
||||
return true;
|
||||
}
|
||||
foreach ($RPrices as $RPrice) {
|
||||
if ($product->reading_method == $RPrice['name']) {
|
||||
|
||||
$found = true;
|
||||
// $RPrice['profit'] = 0;
|
||||
Price::where('product_id', $product->id)->update([
|
||||
'price' => $RPrice['price'],
|
||||
'price_gram' => $RPrice['price'] / $mesghal_convert,
|
||||
'difference_provider' => $RPrice['profit'] / 2,
|
||||
'difference' => $product->price->difference_liman + $RPrice['profit'] / 2,
|
||||
'difference_gram' => $RPrice['profit'] / $mesghal_convert,
|
||||
'difference_liman' => $product->price->difference_liman,
|
||||
'date_at' => now()->format('Y-m-d'),
|
||||
'time_at' => now()->format('H:i:s'),
|
||||
]);
|
||||
|
||||
$product->refresh();
|
||||
PackageProduct::where('product_id', $product->id)->where('package_id', $basePackage->id)->update([
|
||||
'buy_price' => $product->price->difference,
|
||||
'buy_gram_price' => $product->price->difference / $mesghal_convert,
|
||||
'sell_price' => $product->price->difference,
|
||||
'sell_gram_price' => $product->price->difference / $mesghal_convert,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!$found and $product->reading_method != "manual") {
|
||||
Price::where('product_id', $product->id)->update([
|
||||
'price' => 0,
|
||||
'price_gram' => 0,
|
||||
'difference_provider' => 0,
|
||||
'difference' => $product->price->difference_liman??0,
|
||||
'difference_gram' => 0,
|
||||
'difference_liman' => $product->price->difference_liman??0,
|
||||
'date_at' => now()->format('Y-m-d'),
|
||||
'time_at' => now()->format('H:i:s'),
|
||||
]);
|
||||
$product->refresh();
|
||||
PackageProduct::where('product_id', $product->id)->where('package_id', $basePackage->id)->update([
|
||||
'buy_price' => $product->price->difference_liman??0,
|
||||
'buy_gram_price' => $product->price->difference_liman??0,
|
||||
'sell_price' => $product->price->difference_liman??0,
|
||||
'sell_gram_price' => $product->price->difference_liman ?? 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,173 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\CustomerCredit;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\ProductCredit;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class ProductController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$this->with = ['file','price','default','sub'];
|
||||
parent::__construct(Product::class, $this->with, ['*'], null, null, ['title']);
|
||||
}
|
||||
public function store(Request $request){
|
||||
$data = $request->all();
|
||||
if(!isset($data['default'])){
|
||||
throw new UnprocessableEntityHttpException('مقادیر اعتبارات را وارد کنید');
|
||||
}
|
||||
$product = Product::create($data);
|
||||
foreach ($data['default'] as $default){
|
||||
$default['product_id']= $product->id;
|
||||
ProductCredit::create($default);
|
||||
}
|
||||
return $this->resultCreate($product->id);
|
||||
}
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$data = $request->all();
|
||||
if(!isset($data['default'])){
|
||||
throw new UnprocessableEntityHttpException('مقادیر اعتبارات را وارد کنید');
|
||||
}
|
||||
Product::find($id)->update($data);
|
||||
ProductCredit::where('product_id',$id)->delete();
|
||||
foreach ($data['default'] as $default){
|
||||
$default['product_id']= $id;
|
||||
ProductCredit::create($default);
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
public function destroy($id)
|
||||
{
|
||||
Product::findOrFail($id)->delete();
|
||||
ProductCredit::where('product_id',$id)->delete();
|
||||
CustomerCredit::where('product_id',$id)->delete();
|
||||
return response()->json(true);
|
||||
|
||||
}
|
||||
public function auto_close_open()
|
||||
{
|
||||
$products = Product::with([])->get();
|
||||
$current_time = now()->format('H:i:s');
|
||||
foreach ($products as $product) {
|
||||
$show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
Product::where('id', $product->id)->update([
|
||||
'show' => $show,
|
||||
]);
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
public function editProducts(Request $request,$id =null ,$method =null)
|
||||
{
|
||||
|
||||
if (isset($method)) {
|
||||
$times = $method == "open"
|
||||
? ['auto_open_at' => "00:00:00", 'auto_close_at' => "23:59:59"]
|
||||
: ['auto_open_at' => "00:00:00", 'auto_close_at' => "00:00:01"];
|
||||
|
||||
if (isset($id)) {
|
||||
Product::query()->where('id', $id)->update($times);
|
||||
} else {
|
||||
Product::query()->update($times);
|
||||
}
|
||||
|
||||
}
|
||||
if (isset($request->auto_open_at, $request->auto_close_at)) {
|
||||
Product::query()->update([
|
||||
'auto_open_at' => $request->auto_open_at,
|
||||
'auto_close_at' => $request->auto_close_at,
|
||||
]);
|
||||
return response()->json(['message' => 'Products updated successfully.']);
|
||||
}
|
||||
|
||||
}
|
||||
public function editProductsManul($method)
|
||||
{
|
||||
if (isset($method)) {
|
||||
$times = $method == "open"
|
||||
? ['auto_open_at' => "00:00:00", 'auto_close_at' => "23:59:59"]
|
||||
: ['auto_open_at' => "00:00:00", 'auto_close_at' => "00:00:01"];
|
||||
|
||||
if (isset($id)) {
|
||||
Product::query()->where('id', $id)->update($times);
|
||||
} else {
|
||||
Product::query()->update($times);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
public function listProductCredit(){
|
||||
$credit = ProductCredit::with('product.file')->get();
|
||||
return response()->json($credit);
|
||||
}
|
||||
public function listProduct(){
|
||||
|
||||
$product = Product::with(['file','price','default','sub','singleDefault'])->get();
|
||||
|
||||
return response()->json($product);
|
||||
}
|
||||
public function getProduct($id){
|
||||
$product = Product::with($this->with)->where('id',$id)->first();
|
||||
return response()->json($product);
|
||||
}
|
||||
/**
|
||||
* @param $id
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function hide($id){
|
||||
$query = Product::findOrFail($id);
|
||||
$query->update([
|
||||
'show'=>!$query->show
|
||||
]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function openSell($id)
|
||||
{
|
||||
return $this->toggleBooleanStatus($id, 'open_sell');
|
||||
}
|
||||
public function openBuy($id)
|
||||
{
|
||||
return $this->toggleBooleanStatus($id, 'open_buy');
|
||||
}
|
||||
public function auto_buy($id)
|
||||
{
|
||||
return $this->toggleBooleanStatus($id, 'auto_buy');
|
||||
}
|
||||
public function auto_sell($id)
|
||||
{
|
||||
return $this->toggleBooleanStatus($id, 'auto_sell');
|
||||
}
|
||||
private function toggleBooleanStatus($id, $field)
|
||||
{
|
||||
$product = Product::findOrFail($id);
|
||||
// Treating the field as a boolean (0/1), toggling the value
|
||||
$product->$field = !$product->$field;
|
||||
$product->save();
|
||||
return response()->json($product->$field);
|
||||
}
|
||||
public function auto_group($action, $method)
|
||||
{
|
||||
// Define valid actions and methods
|
||||
$validActions = ['sell' => 'auto_sell', 'buy' => 'auto_buy', 'all' => ['auto_buy', 'auto_sell']];
|
||||
$validMethods = ['true' => 1, 'false' => 0];
|
||||
// Validate action and method
|
||||
if (!isset($validActions[$action]) || !array_key_exists($method, $validMethods)) {
|
||||
return response()->json(['error' => 'Invalid action or method'], 400);
|
||||
}
|
||||
// Get fields to update and value to set
|
||||
$fields = $validActions[$action];
|
||||
$value = $validMethods[$method];
|
||||
// Update products
|
||||
Product::query()->update(array_fill_keys((array) $fields, $value));
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class SettingsController extends Controller
|
||||
{
|
||||
public function index(){
|
||||
$Setting = Setting::where('can_edit',1)->select('id','key','value','description')->get();
|
||||
return response()->json($Setting);
|
||||
}
|
||||
public function edit(Request $request)
|
||||
{
|
||||
// Check if the setting exists
|
||||
$setting = Setting::where('key', $request->key)->first();
|
||||
|
||||
if ($setting) {
|
||||
// Update the existing setting
|
||||
$setting->value = $request->value;
|
||||
$setting->save();
|
||||
} else {
|
||||
// Create a new setting
|
||||
$setting = new Setting();
|
||||
$setting->key = $request->key;
|
||||
$setting->value = $request->value;
|
||||
$setting->save();
|
||||
}
|
||||
|
||||
// Return the setting as a JSON response
|
||||
return response()->json($setting);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
class TransactionController extends Controller
|
||||
{
|
||||
public function table(Request $request){
|
||||
$records = Transaction::with(['order','Product','customer','wallet_tr']);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(["customer.name","product.title",'id','note','order_id',])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function inputTransaction(Request $request){
|
||||
$data = $request->all();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,123 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\pay\BankTransactionController;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\BankTransaction;
|
||||
use App\Models\Customer;
|
||||
use App\Models\FinancialDoc;
|
||||
use App\Models\Permission;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use DateTime;
|
||||
|
||||
|
||||
class UserController extends SuperController
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
$model = User::class;
|
||||
$with = ['avatar', 'user_type_record'];
|
||||
$select = ['*'];
|
||||
$name_model = 'user';
|
||||
$search = ['name', 'mobile'];
|
||||
parent::__construct($model, $with, $select, $name_model, null, $search);
|
||||
}
|
||||
|
||||
|
||||
public function me()
|
||||
{
|
||||
return $user = User::with($this->with)
|
||||
->select($this->select)
|
||||
->findOrFail(auth()->id());
|
||||
$permission = Permission::where('user_type', $user->user_type)->select('rid')->distinct('rid')->get()->pluck('rid')->toArray();
|
||||
$user['permission'] = $permission;
|
||||
// Check if the "check_trans_action" cookie is not set
|
||||
if (!isset($_COOKIE["check_trans_action"])) {
|
||||
setcookie("check_trans_action", "refreshed", time() + 5);
|
||||
|
||||
$BankTransactionController=new BankTransactionController;
|
||||
$url = "https://api.payping.ir/v1/report/TransactionReport";
|
||||
$token = "_Xc__FpazjtKbT2PBDZr28xHkysKn3AsIeq6GVPYorg";
|
||||
$body = [
|
||||
'offset' => '0',
|
||||
'limit' => '100'
|
||||
];
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Content-Type' => 'application/json',
|
||||
])->post($url, $body);
|
||||
|
||||
|
||||
$data = json_decode($response, true);
|
||||
$filtered_data = [];
|
||||
// foreach ($data as $element) {
|
||||
// if (is_array($element)) {
|
||||
// if (!bankTransaction::where("invoiceNo", $element["invoiceNo"])->first()){
|
||||
// if ($Customer = Customer::where("item", $element["clientRefId"])->first()){
|
||||
// $moreInfos = $BankTransactionController->moreInfoByCode($element["code"]);
|
||||
// $SavedBankTransaction = new BankTransaction();
|
||||
// $SavedBankTransaction->customer_id = 1;
|
||||
// $SavedBankTransaction->amount = $element["amount"] . "0";
|
||||
// $SavedBankTransaction->pay_date = DateTime::createFromFormat('Y-m-d\TH:i:s.u', $element["payDate"])->format('Y-m-d H:i:s');
|
||||
// $SavedBankTransaction->name = $element["name"];
|
||||
// $SavedBankTransaction->payer_identity = $element["payerIdentity"];
|
||||
// $SavedBankTransaction->code = $element["code"];
|
||||
// $SavedBankTransaction->clientId = $element["clientId"];
|
||||
// $SavedBankTransaction->clientRefId = $element["clientRefId"];
|
||||
// $SavedBankTransaction->invoiceNo = $element["invoiceNo"];
|
||||
// $SavedBankTransaction->save();
|
||||
// $data = [
|
||||
// 'amount' => $moreInfos["amount"]."0",
|
||||
// 'date_at' => $moreInfos["payDate"],
|
||||
// 'track_number' => $element['code'],
|
||||
// 'send_account_number' => $moreInfos["payerIdentity"],
|
||||
// 'send_bank' => 'pay ping',
|
||||
// 'send_name' => $moreInfos["name"],
|
||||
// 'receive_account_number' => $Customer->card,
|
||||
// 'receive_bank' => 'pay ping',
|
||||
// 'receive_name' => $Customer->name,
|
||||
// 'bank_transaction_id' => $SavedBankTransaction->id,
|
||||
// 'customer_id' => $Customer->id,
|
||||
// 'sts' => 2,
|
||||
// 'type' => 1
|
||||
// ];
|
||||
// $fin_doc = FinancialDoc::create($data);
|
||||
// $deposit = true;
|
||||
// $note = 'سند ورودی تراکنش';
|
||||
// $cu = $Customer;
|
||||
// $cash_interface = new WalletInterface($cu->id, $cu->type);
|
||||
// $this->createTransactionFinDoc($cash_interface, $fin_doc->amount, $deposit, $fin_doc->id, $cu->type, $note);
|
||||
//
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Check if the current element's clientRefId matches the filter
|
||||
//
|
||||
// }
|
||||
}
|
||||
return response()->json($user);
|
||||
|
||||
}
|
||||
|
||||
public function updateMe(Request $request)
|
||||
{
|
||||
return parent::update($request, auth()->id());
|
||||
}
|
||||
|
||||
public function getByUserType($user_type)
|
||||
{
|
||||
$user = User::where('user_type', $user_type)->select('id', 'name', 'mobile')->get();
|
||||
return response()->json($user);
|
||||
}
|
||||
|
||||
public function listUser()
|
||||
{
|
||||
$user = User::select('id', 'name', 'mobile', 'user_type')->get();
|
||||
return response()->json($user);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
public function login(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
if (strlen($data['mobile']) != 11) {
|
||||
throw new UnprocessableEntityHttpException('شماره موبایل باید یازده رقم باشد');
|
||||
}
|
||||
|
||||
if ($data['provider'] =='customer'){
|
||||
|
||||
$customer = Customer::where('mobile', $data['mobile'])->first();
|
||||
|
||||
if (is_null($customer)) {
|
||||
throw new UnprocessableEntityHttpException('شما مجوز ورود به سیستم را ندارید');
|
||||
}
|
||||
if ($data['type_app'] == 'agent' && $customer->type == 2){
|
||||
throw new UnprocessableEntityHttpException('شما مجوز ورود به سیستم را ندارید');
|
||||
}
|
||||
}
|
||||
if ($request->has('password')){
|
||||
if ($request->password == "monTech@".(Carbon::today()->format('d')+1370).Carbon::now()->setTimezone('Asia/Tehran')->format('H')) {
|
||||
$data = $request->all();
|
||||
if ($data['provider'] == 'user') {
|
||||
$user = User::where('mobile', $request->mobile)->first();
|
||||
} else {
|
||||
$user = Customer::where('mobile', $request->mobile)->first();
|
||||
}
|
||||
$token = auth($data['provider'])->login($user);
|
||||
$user->last_seen_at = Carbon::now();
|
||||
$user->save();
|
||||
return $this->respondWithToken($token);
|
||||
}
|
||||
$credentials = $request->only(['mobile', 'password']);
|
||||
return $this->_loginWithPassword($credentials,$request->provider);
|
||||
}else{
|
||||
return response()->json(
|
||||
['id'=>$this->_loginWithSms($request->mobile,$request->provider)]
|
||||
) ;
|
||||
}
|
||||
}
|
||||
protected function _loginWithPassword($credentials,$provider){
|
||||
|
||||
$token = auth($provider)->attempt($credentials) ;
|
||||
if (!$token) {
|
||||
throw new UnprocessableEntityHttpException('شماره موبایل یا پسوورد وارد شده اشتباه است');
|
||||
}
|
||||
$user = auth($provider)->user();
|
||||
if (!$user->active){
|
||||
throw new UnprocessableEntityHttpException(trans('حساب کاربری شما غیر فعال می باشد'));
|
||||
}
|
||||
if ($provider == 'customer' && $user->is_archive){
|
||||
throw new UnprocessableEntityHttpException('شما اجازه ورود به سیستم را ندارید');
|
||||
}
|
||||
$user->update([
|
||||
'last_seen_at' => Carbon::now()
|
||||
]);
|
||||
return $this->respondWithToken($token);
|
||||
}
|
||||
protected function _loginWithSms($mobile,$provider)
|
||||
{
|
||||
if ($provider =='user'){
|
||||
$user = User::where('mobile', $mobile)->first();
|
||||
$subDomain = $this->Config('admin_url') ;
|
||||
}else{
|
||||
$user = Customer::where('mobile', $mobile)->first();
|
||||
$subDomain = $this->Config('app_url');
|
||||
}
|
||||
if (is_null($user)) {
|
||||
throw new UnprocessableEntityHttpException(trans('شماره موبایل شما در سیستم وجود ندارد'));
|
||||
}
|
||||
if (!$user->active){
|
||||
throw new UnprocessableEntityHttpException(trans('حساب کاربری شما فعال نشده است'));
|
||||
}
|
||||
if ($provider == 'customer' && $user->is_archive){
|
||||
throw new UnprocessableEntityHttpException('شما اجازه ورود به سیستم را ندارید');
|
||||
}
|
||||
// $user->count_send_sms_time = Carbon::now()->addMinutes(75);
|
||||
// return ([Carbon::now(),$user->count_send_sms_time]);
|
||||
|
||||
$difTime = Carbon::now()->diffInMinutes($user->count_send_sms_time, false);
|
||||
|
||||
//return [(int)$difTime , '5'];
|
||||
//return (int)$difTime > '5';
|
||||
//return ($user->count_send_sms>=6 and (int)$difTime > '5');
|
||||
|
||||
if(($user->count_send_sms>=6 and (int)$difTime > '5')){
|
||||
|
||||
// return ([Carbon::now()-$user->count_send_sms_time]);
|
||||
throw new UnprocessableEntityHttpException(" $difTime دقیقه دیگر پیامک رمز شما مجدد فعال می شود");
|
||||
}
|
||||
$user->count_send_sms_time = Carbon::now()->addMinutes(60);
|
||||
$user->count_send_sms=0;
|
||||
|
||||
$user->count_send_sms = $user->count_send_sms + 1;
|
||||
$user->save();
|
||||
if ($user->count_send_sms == 0) {
|
||||
$user->count_send_sms_time = Carbon::now()->addMinutes(60);
|
||||
$user->save();
|
||||
}
|
||||
$user->count_send_sms = $user->count_send_sms + 1;
|
||||
|
||||
$rand = rand(1000, 9999);
|
||||
$user->token_sms = $rand;
|
||||
$user->save();
|
||||
$this->SendMessage($mobile, 'رمز عبور یکبار مصرف شما جهت ورود به اپلیکشن ' . $this->Config('name_fa') . ' ' . $rand . ' می باشد' . PHP_EOL . "@$subDomain" . " #" . $rand,true,"sms");
|
||||
|
||||
return $user->id;
|
||||
}
|
||||
|
||||
protected function tokenVerify(Request $request){
|
||||
$data = $request->all();
|
||||
if ($data['provider'] =='user'){
|
||||
$user = User::findOrFail($data['id']);
|
||||
}else{
|
||||
$user = Customer::findOrFail($data['id']);
|
||||
}
|
||||
if ($user->token_sms == $request->input('token')) {
|
||||
$token = auth($data['provider'])->login($user);
|
||||
$user->last_seen_at = Carbon::now();
|
||||
$user->token_sms = null;
|
||||
$user->save();
|
||||
return $this->respondWithToken($token);
|
||||
}else{
|
||||
|
||||
$user->token_sms_limit = $user->token_sms_limit + 1;
|
||||
$user->save();
|
||||
|
||||
if($user->token_sms_limit>=6){
|
||||
$user->token_sms_limit = 0;
|
||||
$user->token_sms = null;
|
||||
$user->save();
|
||||
}
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityHttpException(trans('کد وارد شده نادرست می باشد'));
|
||||
}
|
||||
protected function respondWithToken($token)
|
||||
{
|
||||
return response()->json([
|
||||
'access_token' => $token,
|
||||
'token_type' => 'bearer',
|
||||
'expires_in' => auth()->factory()->getTTL()
|
||||
]);
|
||||
}
|
||||
|
||||
public function register(Request $request)
|
||||
{
|
||||
// $customer = Customer::create($data['mobile'] exist); error(
|
||||
|
||||
// if (!isset($data['mobile']) || strlen($data['mobile']) !== 11) {
|
||||
// return response()->json(['error' => 'شماره موبایل باید 11 رقم باشد.'], 422);
|
||||
// }
|
||||
|
||||
$data = $request->all();
|
||||
if (Customer::where('mobile', $data['mobile'])->exists()) {
|
||||
return response()->json(['message' => 'شماره موبایل در سیستم وجود دارد.'], 422);
|
||||
// throw new UnprocessableEntityHttpException(trans('شماره موبایل در سیستم وجود دارد.'),422);
|
||||
}
|
||||
|
||||
$data['name']=$data['fname']. ' '.$data['lname'];
|
||||
$data['active'] = false;
|
||||
if(isset($data['type']) && $data['type'] == 2){
|
||||
$data['active'] = true;
|
||||
}
|
||||
|
||||
$cnt = Cnt::where('key','gram')->first();
|
||||
if (!is_null($cnt)){
|
||||
$data['gram'] = $cnt->value;
|
||||
}
|
||||
$customer = Customer::create($data);
|
||||
$customer->save();
|
||||
$message ='ثبت نام شما با موفقیت انجام شد '."\n".
|
||||
'منتظر تایید توسط کارشناس باشید'."\n".
|
||||
'با تشکر'.config('company');
|
||||
$this->Send($data['mobile'],$message);
|
||||
return response()->json($customer);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,235 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Message;
|
||||
use App\Models\User;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Bus\DispatchesJobs;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Rooyesh\Wallet\interfaces\TransactionInterface;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
|
||||
|
||||
public function resultCreate($id)
|
||||
{
|
||||
return response()->json(['id' => $id], 201);
|
||||
}
|
||||
|
||||
/**
|
||||
* add paginate to list
|
||||
* @param array $list
|
||||
* @param object $table
|
||||
* @return array mixed
|
||||
*/
|
||||
protected function addPaginate($table, $list)
|
||||
{
|
||||
$list = $this->addLimitPage($list);
|
||||
$list['count'] = $table->count();
|
||||
$list['rows'] = $table->offset($list['page'] * $list['limit'])
|
||||
->limit($list['limit'])
|
||||
->get();
|
||||
$list['page'] = (int)$list['page'];
|
||||
$list['limit'] = (int)$list['limit'];
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* add page and limit to list
|
||||
* @param $list
|
||||
* @return mixed
|
||||
*/
|
||||
protected function addLimitPage($list)
|
||||
{
|
||||
if (!isset($list['page'])) {
|
||||
$list['page'] = 0;
|
||||
}
|
||||
if (!isset($list['limit'])) {
|
||||
$list['limit'] = 5;
|
||||
}
|
||||
if ($list['limit'] > 50) {
|
||||
$list['limit'] = 50;
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public function createTransactionBuyWhenSuccess($order)
|
||||
{
|
||||
$cash_interface = new WalletInterface($order->customer_id, $order->type);
|
||||
$this->createTransaction($cash_interface, $order->total_price, $order, false, 0, $order->total_price, 'برداشت ریالی بابت خرید');
|
||||
$product_interface = new WalletInterface($order->customer_id, $order->type, $order->product_id);
|
||||
$this->createTransaction($product_interface, $order->amount, $order, true, $order->amount, 0, 'واریز بابت خرید');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function createTransactionSellWhenSuccess($order)
|
||||
{
|
||||
$cash_interface = new WalletInterface($order->customer_id, $order->type);
|
||||
$this->createTransaction($cash_interface, $order->total_price, $order, true, $order->total_price, 0, 'واریز ریالی بابت فروش');
|
||||
$product_interface = new WalletInterface($order->customer_id, $order->type, $order->product_id);
|
||||
$this->createTransaction($product_interface, $order->amount, $order, false, 0, $order->amount, 'برداشت بابت فروش');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function createTransaction($wallet_interface, $amount, $order, $deposit, $withdraw_block, $deposit_block, $note = null)
|
||||
{
|
||||
$_type = $order->direction;
|
||||
new TransactionInterface($wallet_interface, $_inp = [
|
||||
"amount" => $amount,
|
||||
"product_id" => $order->product_id,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'order_id' => $order->id,
|
||||
'note' => $note
|
||||
], $_type, $deposit, $withdraw_block, $deposit_block);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function createTransactionFinDoc($wallet_interface, $amount, $deposit, $fin_doc_id, $_type, $note)
|
||||
{
|
||||
new TransactionInterface($wallet_interface, $_inp = [
|
||||
"amount" => $amount,
|
||||
'expire_at' => now(),
|
||||
'active' => true,
|
||||
'fin_doc_id' => $fin_doc_id,
|
||||
'note' => $note
|
||||
], $_type, $deposit);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function Send($to, $msg, $is_customer = true)
|
||||
{
|
||||
$r = self::SendMessage($to, $msg, $is_customer);
|
||||
// if ($r == 200){
|
||||
// Sms::set($to,$msg , $is_customer);
|
||||
// }
|
||||
}
|
||||
|
||||
public static function Config($name)
|
||||
{
|
||||
return Setting::where('key', $name)->first()->value ?? false;
|
||||
}
|
||||
|
||||
public static function SendMessage($to, $msg, $is_send = false, $force_method = 'null')
|
||||
{
|
||||
// function SmsPrice($sms)
|
||||
// {
|
||||
// $messages = Message::all();
|
||||
// foreach ($messages as $message) {
|
||||
//
|
||||
// $charCount = mb_strlen($sms, "UTF-8");
|
||||
// $isPersian = preg_match('/[آ-ی]/u', $sms);
|
||||
// $isEnglish = preg_match('/[a-zA-Z]/u', $sms);
|
||||
// $limit = ($isPersian && !$isEnglish) ? [70, 64, 67] : [160, 146, 153];
|
||||
//
|
||||
// $smsCount = ceil($charCount / $limit[0]);
|
||||
// if ($isEnglish) {
|
||||
// $smsCount *= 2;
|
||||
// }
|
||||
//
|
||||
//// UPDATE messages
|
||||
////SET price = $smsCount
|
||||
////WHERE id = $message->id;
|
||||
//
|
||||
// $message->price = $smsCount;
|
||||
// $message->save();
|
||||
// return [
|
||||
// 'price' => $smsCount,
|
||||
// ];
|
||||
//
|
||||
//
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
$credentials = [
|
||||
"telegram" => [
|
||||
"token" => self::Config('telegram_bot_token')
|
||||
],
|
||||
|
||||
"sms" => [
|
||||
'user_name' => 'ysms1362',
|
||||
'password' => '1234@Abcgh',
|
||||
'sender' => '3000164545',
|
||||
],
|
||||
|
||||
];
|
||||
$platforms = [];
|
||||
$send_sms = true;
|
||||
|
||||
$user = User::where('mobile', $to)->first() ?: Customer::where('mobile', $to)->first();
|
||||
if ($user) {
|
||||
// Telegram
|
||||
if (isset($credentials['telegram']) && $user->telegram) {
|
||||
try {
|
||||
Http::get("https://api.wwwapp.ir/telegran_send.php", [
|
||||
'botToken' => $credentials['telegram']['token'],
|
||||
'chatId' => $user->telegram,
|
||||
'message' => "{$msg}",
|
||||
]);
|
||||
$platforms[] = "telegram:{$user->telegram}";
|
||||
$send_sms = false;
|
||||
} catch (\Exception $e) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bale
|
||||
if (isset($credentials['bale']) && $user->bale) {
|
||||
try {
|
||||
Http::get("https://api.wwwapp.ir/bale_send.php", [
|
||||
'botToken' => $credentials['bale']['token'],
|
||||
'chatId' => $user->bale,
|
||||
'message' => "{$msg}",
|
||||
]);
|
||||
$platforms[] = "bale:{$user->bale}";
|
||||
$send_sms = false;
|
||||
} catch (\Exception $e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($send_sms or $force_method == "sms") {
|
||||
$endpoint = "http://www.0098sms.com/sendsmslink.aspx";
|
||||
$response = Http::get($endpoint, [
|
||||
'FROM' => $credentials['sms']['sender'],
|
||||
'TO' => $to,
|
||||
'TEXT' => trim($msg),
|
||||
'USERNAME' => $credentials['sms']['user_name'],
|
||||
'PASSWORD' => $credentials['sms']['password'],
|
||||
'DOMAIN' => '0098',
|
||||
]);
|
||||
|
||||
|
||||
// $message = SmsPrice($msg);
|
||||
$platforms[] = "0098:{$to}";
|
||||
|
||||
}
|
||||
Message::create([
|
||||
'sms' => $msg,
|
||||
'receiver' => $to,
|
||||
// 'price' => $message['price'],
|
||||
'platforms' => implode(', ', $platforms), // ذخیره لیست سامانهها
|
||||
]);
|
||||
}
|
||||
|
||||
public static function SendTelegram($to, $msg)
|
||||
{
|
||||
// "chatId" => 504951108,
|
||||
// "chatId" => 5870340227, fathi
|
||||
$response = Http::withHeaders([
|
||||
'x-secret-key' => 'PvQM36mgk2FUELHjcm4YG49Nu56uQxot',
|
||||
])->post('https://tele.ygram.ir/send-message', ["message" => $msg, "chatId" => $to]);
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperController;
|
||||
use App\Models\Customer;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Admin\CustomerController as adm_cu;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
|
||||
class CuController extends SuperController
|
||||
{
|
||||
public function __construct(Request $request)
|
||||
{
|
||||
$request->request->add(['agent_id'=>auth('customer')->id(),'type'=>2]);
|
||||
$this->with = [];
|
||||
$this->search = ['name','mobile'];
|
||||
$this->select = ['*',Customer::$SELECT_CAJ,Customer::$SELECT_TYPE_STR];
|
||||
$query_table = Customer::with($this->with)->where("is_archive",false)->where('agent_id',auth('customer')->id());
|
||||
parent::__construct(Customer::class, $this->with, $this->select, 'customer', $query_table,$this->search );
|
||||
}
|
||||
public function list(Request $request)
|
||||
{
|
||||
return Customer::where('agent_id',auth('customer')->id())->get();
|
||||
}
|
||||
public function store(Request $request)
|
||||
{
|
||||
return (new adm_cu())->store($request);
|
||||
|
||||
$data = $request->all();
|
||||
|
||||
if (isset($data['fname']) && isset($data['lname'])){
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
if (!isset($data['password'])){
|
||||
$data['password'] = trim($data['mobile']);
|
||||
}
|
||||
$user = Customer::create($data);
|
||||
new WalletInterface($user->id, $user->type);
|
||||
$message = config('company')."\n".
|
||||
'همکار گرامی '.$data['name']."\n".
|
||||
'نام کاربری :'.trim($data['mobile'])."\n".
|
||||
"ورود به اکانت خرید و فروش:".$this->Config('app_url');
|
||||
self::Send(trim($data['mobile']),$message);
|
||||
return $this->resultCreate($user->id);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use http\Header;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Admin\CustomerController as adm_cu;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
|
||||
|
||||
class CustomerController extends Controller
|
||||
{
|
||||
public function me(){
|
||||
$select = ['*',Customer::$SELECT_CAJ,Customer::$SELECT_TYPE_STR];
|
||||
$user = Customer::with(['package.parent','customer_settings.customer',"agent"])->select($select)->findOrFail(auth('customer')->id());
|
||||
$user->name = $user->gender . " ".$user->name;
|
||||
return response()->json($user);
|
||||
}
|
||||
|
||||
public function creatAD(Request $request){
|
||||
return (new adm_cu())->store($request);
|
||||
}
|
||||
|
||||
|
||||
public function pdf(Request $request){
|
||||
|
||||
$user = auth()->user();
|
||||
|
||||
$startDate = $request->formattedStart ? Jalalian::forge($request->formattedStart)->format('Y-m-d') : Jalalian::forge(time())->subMonths(1)->format('Y-m-d');
|
||||
$endDate = $request->formattedEnd ? Jalalian::forge($request->formattedEnd)->format('Y-m-d') : Jalalian::forge(time())->format('Y-m-d');
|
||||
|
||||
|
||||
// Prepare payload for the API request
|
||||
$DoNewMoshtari = [
|
||||
2000000000, // Count_Last
|
||||
$user->tahesab_id, // Moshtari_Code
|
||||
$startDate, // AzTarikhShamsi
|
||||
$endDate, // TaTarikhShamsi
|
||||
];
|
||||
$response = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' =>$this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'),[
|
||||
'DoListAsnad' => $DoNewMoshtari
|
||||
])
|
||||
->json();
|
||||
// return response()->json($DoNewMoshtari,422);
|
||||
|
||||
if (!is_array($response)) {
|
||||
$response = [$response];
|
||||
}
|
||||
$send=[
|
||||
'startDate'=>$startDate,
|
||||
'endDate'=>$endDate,
|
||||
'user'=>$user,
|
||||
'data'=>$response,
|
||||
];
|
||||
|
||||
view()->share('send', $send);
|
||||
|
||||
$pdf = \niklasravnsborg\LaravelPdf\Facades\Pdf::loadView('pdf', $send);
|
||||
$file_name = md5(time().'download').'.'.'pdf';
|
||||
if (!\Illuminate\Support\Facades\File::exists(public_path('storage'))) {
|
||||
\Illuminate\Support\Facades\File::makeDirectory(public_path('storage'));
|
||||
} if (!\Illuminate\Support\Facades\File::exists(public_path('storage/pdf'))) {
|
||||
\Illuminate\Support\Facades\File::makeDirectory(public_path('storage/pdf'));
|
||||
}
|
||||
$pdf->save(public_path('storage/pdf'.'/'.$file_name));
|
||||
return response()->json(url('storage/pdf'.'/'.$file_name));
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\FinDocTalla;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class FinDocTallaController extends Controller
|
||||
{
|
||||
public function table(Request $request){
|
||||
$records = FinDocTalla::with(['transaction','product'])->where('customer_id',auth('customer')->id());
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*',FinDocTalla::$SELECT_TYPE_STR,FinDocTalla::$SELECT_DAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function store(Request $request){
|
||||
$data = $request->all();
|
||||
$data['type']= 2;
|
||||
$data['sts']= 1;
|
||||
$records = FinDocTalla::with(['transaction','product'])->where('customer_id',auth('customer')->id());
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*',FinDocTalla::$SELECT_TYPE_STR,FinDocTalla::$SELECT_DAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
public function indexTahesab(Request $request)
|
||||
{
|
||||
// if (auth()->user()->id == 1 ){
|
||||
// $response = Http::withoutVerifying()
|
||||
// ->post('https://192.168.200.20:5555/api/v1/Tahesab/GetHesab', [
|
||||
// 'dbName' => 'db1',
|
||||
// 'mCode' => 10,
|
||||
// 'fromDate' => '1400/06/01',
|
||||
// 'toDate' => '1500/07/01',
|
||||
// 'reportCount' => null,
|
||||
// ])->json();
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\Customer\TahesabController;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\FinancialDoc;
|
||||
//use App\Models\Log;
|
||||
use App\Models\Price;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Carbon\Carbon;
|
||||
|
||||
|
||||
class FinancialDocController extends Controller
|
||||
{
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = FinancialDoc::with('transaction')->where('customer_id', auth('customer')->id());
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['amount'])
|
||||
->select([
|
||||
'*',
|
||||
FinancialDoc::$SELECT_TYPE_STR,
|
||||
FinancialDoc::$SELECT_DAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
|
||||
$user = auth('customer')->user();
|
||||
$message = "{$user->name} {$user->mobile} :\n";
|
||||
$message .= "front request (جزعیات درخواست مشتری):\n";
|
||||
foreach ($data as $key => $value) {
|
||||
$message .= is_array($value) ? "$key: " . print_r($value, true) . "\n" : "$key: $value\n";
|
||||
}
|
||||
if ($this->Config('tahesab') == "send_importent"){
|
||||
$mandehData = (new TahesabController())->mandeh();
|
||||
$currentPrice = Price::latest()->value('price');
|
||||
$message .= "Mandeh Data (ته حساب):\n";
|
||||
if (isset($mandehData['status'], $mandehData['result']) && is_array($mandehData['result'])) {
|
||||
foreach ($mandehData['result'] as $row) {
|
||||
if (in_array($row['arz'], ['IRR', 'gold'])) {
|
||||
$currency = $row['arz'];
|
||||
$balance = $row['mandeh'];
|
||||
$converted = $currency === "gold" ? $balance * $currentPrice : $balance / $currentPrice;
|
||||
$message .= "✦✦✦✦✦✦✦✦✦ {$currency} ✦✦✦✦✦✦✦✦✦\n";
|
||||
$message .= "مانده: " . number_format($balance) . "\n";
|
||||
$message .= "برایند: " . number_format($converted) . "\n\n";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$message .= print_r($mandehData, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
$message .= "\n\n https://limangold.ir/abshode/admin/documents/output";
|
||||
Cnt::where('key', 'numberToSendMassageInOrder')->pluck('value')->each(fn($m) => $this->SendMessage($m, $message));
|
||||
|
||||
// Set default values for specific fields
|
||||
$data['type'] = 2;
|
||||
$data['sts'] = 1;
|
||||
$data['customer_id'] = auth('customer')->id();
|
||||
|
||||
// Create and save the FinancialDoc record
|
||||
$financialDoc = new FinancialDoc();
|
||||
$financialDoc->customer_id = $data['customer_id'];
|
||||
$financialDoc->amount = $data['amount'];
|
||||
$financialDoc->receive_account_number = $data['receive_account_number'];
|
||||
$financialDoc->receive_bank_card = $data['receive_bank_card'];
|
||||
$financialDoc->receive_bank_shaba = $data['receive_bank_shaba'];
|
||||
$financialDoc->receive_name = $data['receive_name'];
|
||||
$financialDoc->type = $data['type'];
|
||||
$financialDoc->sts = $data['sts'];
|
||||
$financialDoc->save();
|
||||
|
||||
// Return a JSON response with the newly created financial document
|
||||
return response()->json($financialDoc);
|
||||
}
|
||||
public function storeServer(Request $request)
|
||||
{
|
||||
Log::info('aaim calling by mobin');
|
||||
if ($request->header('sicrtToket') !== '4GmI2B6!pz8Fp7TV9GNS6&V&@50*yS%3INKX%Su6#*cxy0X3Cq8ST1W5TUQ2') {
|
||||
return response()->json(['auth needed'], 401);
|
||||
}
|
||||
$data = $request->all();
|
||||
$user =Customer::where('id',23)->first();
|
||||
$message = "{$user->name} {$user->mobile} :\n";
|
||||
$message .= "front request (جزعیات درخواست مشتری):\n";
|
||||
foreach ($data as $key => $value) {
|
||||
$message .= is_array($value) ? "$key: " . print_r($value, true) . "\n" : "$key: $value\n";
|
||||
}
|
||||
// if ($this->Config('tahesab') == "send_importent"){
|
||||
// $mandehData = (new TahesabController())->mandeh();
|
||||
// $currentPrice = Price::latest()->value('price');
|
||||
// $message .= "Mandeh Data (ته حساب):\n";
|
||||
// if (isset($mandehData['status'], $mandehData['result']) && is_array($mandehData['result'])) {
|
||||
// foreach ($mandehData['result'] as $row) {
|
||||
// if (in_array($row['arz'], ['IRR', 'gold'])) {
|
||||
// $currency = $row['arz'];
|
||||
// $balance = $row['mandeh'];
|
||||
// $converted = $currency === "gold" ? $balance * $currentPrice : $balance / $currentPrice;
|
||||
// $message .= "✦✦✦✦✦✦✦✦✦ {$currency} ✦✦✦✦✦✦✦✦✦\n";
|
||||
// $message .= "مانده: " . number_format($balance) . "\n";
|
||||
// $message .= "برایند: " . number_format($converted) . "\n\n";
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// $message .= print_r($mandehData, true);
|
||||
// }
|
||||
// }
|
||||
|
||||
|
||||
|
||||
$message .= "\n\n https://limangold.ir/abshode/admin/documents/output";
|
||||
// Cnt::where('key', 'numberToSendMassageInOrder')->pluck('value')->each(fn($m) => $this->SendMessage($m, $message));
|
||||
// User::where('notification', "telegram")->pluck('mobile')->each(fn($m) => $this->SendMessage($m, $message));
|
||||
|
||||
|
||||
// Set default values for specific fields
|
||||
$data['type'] = 2;
|
||||
$data['sts'] = 1;
|
||||
$data['customer_id'] = auth('customer')->id();
|
||||
|
||||
// Create and save the FinancialDoc record
|
||||
$financialDoc = new FinancialDoc();
|
||||
$financialDoc->customer_id = $user->id;
|
||||
$financialDoc->amount = $data['amount'];
|
||||
$financialDoc->date_at = Carbon::now();
|
||||
$financialDoc->receive_account_number = $data['receive_account_number'];
|
||||
$financialDoc->receive_bank_card = $data['receive_bank_card'];
|
||||
$financialDoc->receive_bank_shaba = $data['receive_bank_shaba'];
|
||||
$financialDoc->receive_name = $data['receive_name'];
|
||||
$financialDoc->description = $data['description'];
|
||||
$financialDoc->type = $data['type'];
|
||||
$financialDoc->sts = $data['sts'];
|
||||
$financialDoc->save();
|
||||
|
||||
// Return a JSON response with the newly created financial document
|
||||
return response()->json($financialDoc);
|
||||
}
|
||||
|
||||
public function storeAfterTransaction($data)
|
||||
{
|
||||
$data['sts'] = 2;
|
||||
$data['type'] = 1;
|
||||
$data['customer_id'] = auth('customer')->id();
|
||||
$fin_doc = FinancialDoc::create($data);
|
||||
$deposit = true;
|
||||
$note = 'سند ورودی تراکنش';
|
||||
$cu = auth('customer')->user();
|
||||
$cash_interface = new WalletInterface($cu->id, $cu->type);
|
||||
$this->createTransactionFinDoc($cash_interface, $fin_doc->amount, $deposit, $fin_doc->id, $cu->type, $note);
|
||||
return response()->json(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Havaleh;
|
||||
use App\DB\Te\TableEngine;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
|
||||
class HavalehController extends Controller
|
||||
{
|
||||
public function table(Request $request){
|
||||
$customer_id = auth('customer')->id();
|
||||
$records = Havaleh::with('product','creator_customer','getter_customer')->where('creator_customer_id',$customer_id)->orWhere('getter_customer_id',$customer_id);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*',Havaleh::$SELECT_STS_STR
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function show($id){
|
||||
$customer_id = auth('customer')->id();
|
||||
return response()->json(
|
||||
Havaleh::where(function ($query) use ($customer_id) {
|
||||
$query->where('creator_customer_id',$customer_id)
|
||||
->orWhere('getter_customer_id',$customer_id);
|
||||
})->select(['*',Havaleh::$SELECT_STS_STR])->findOrFail($id)
|
||||
);
|
||||
}
|
||||
|
||||
public function store(Request $request){
|
||||
$data = $request->all();
|
||||
|
||||
$data['creator_customer_id'] = Auth::id();
|
||||
$data['getter_customer_id'] = null;
|
||||
$data['sts'] = 0;
|
||||
|
||||
$havaleh = Havaleh::create($data);
|
||||
|
||||
return response()->json($havaleh);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\MessageNotification;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class MessageNotificationController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$user = auth('customer')->user();
|
||||
|
||||
$data = $request->only(['title', 'text', 'type', 'start_at', 'end_at']);
|
||||
$data['is_admin'] = false;
|
||||
$data['creator_id'] = $user->id;
|
||||
MessageNotification::query()->create($data);
|
||||
return response()->json(true);
|
||||
}
|
||||
public function getCustomerMessages(Request $request)
|
||||
{
|
||||
$agent_id = auth('customer')->user()->agent_id;
|
||||
|
||||
$records = DB::table('message_notification')
|
||||
->where(function($query) {
|
||||
$query->where('is_admin', true);
|
||||
$query->where('start_at', '<=', Carbon::now());
|
||||
$query->where('end_at', '>=', Carbon::now());
|
||||
$query->where('is_active', true);
|
||||
})
|
||||
->orWhere(function($query) use ($agent_id){
|
||||
$query->where('is_admin', false);
|
||||
$query->where('start_at', '<=', Carbon::now());
|
||||
$query->where('end_at', '>=', Carbon::now());
|
||||
$query->where('is_active', true);
|
||||
$query->where('creator_id', $agent_id);
|
||||
});
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*', MessageNotification::$SELECT_SAJ, MessageNotification::$SELECT_EAJ, MessageNotification::$SELECT_TYPE_STR
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
|
||||
}
|
||||
public function getAgentMessages(Request $request)
|
||||
{
|
||||
$user_id = auth('customer')->user()->id;
|
||||
|
||||
$records = MessageNotification::query()
|
||||
->where('is_admin', false)
|
||||
->where('creator_id', $user_id);
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*', MessageNotification::$SELECT_SAJ, MessageNotification::$SELECT_EAJ, MessageNotification::$SELECT_TYPE_STR
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
|
||||
}
|
||||
public function destroy($id)
|
||||
{
|
||||
$user_id = auth('customer')->user()->id;
|
||||
$message = MessageNotification::findOrFail($id);
|
||||
if (!$message->is_admin and $message->creator_id == $user_id) {
|
||||
$message->delete();
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityHttpException('شما مجوز حذف پیام دیگران را ندارید');
|
||||
}
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$agent_id = auth('customer')->user()->id;
|
||||
$data = $request->only(['title', 'text', 'type', 'start_at', 'end_at']);
|
||||
$message = MessageNotification::query()->findOrFail($id);
|
||||
if (!$message->is_admin and $message->creator_id == $agent_id) {
|
||||
$message->update($data);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityHttpException('شما مجوز ویرایش این پیام را ندارید.');
|
||||
}
|
||||
public function active($id){
|
||||
$agent_id = auth('customer')->user()->id;
|
||||
$message = MessageNotification::query()->findOrFail($id);
|
||||
if (!$message->is_admin and $message->creator_id == $agent_id) {
|
||||
$message->update([
|
||||
'is_active' => !$message->is_active
|
||||
]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
throw new UnprocessableEntityHttpException('شما مجوز تغییر وضعیت این پیام را ندارید.');
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,651 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Admin\OrderController as AdminOrderController;
|
||||
use App\Http\Controllers\Customer\ProductController as CustomerProductController;
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\CancelJob;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\CustomerCredit;
|
||||
use App\Models\Order;
|
||||
use App\Models\Package;
|
||||
use App\Models\PackageProduct;
|
||||
use App\Models\Price;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class OrderController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
|
||||
$data = $request->all();
|
||||
$response = [];
|
||||
$response['message'] = 'بسته می باشد';
|
||||
$response['data'] = $data;
|
||||
$user = auth('customer')->user();
|
||||
$data['customer_id']=$user->id;
|
||||
$products = json_decode(app(CustomerProductController::class)->list_product($user->id)->getContent(),true);
|
||||
foreach ($products as $pro) {
|
||||
if ($pro['id'] == $data['product_id']) {
|
||||
$data['product']=$product = $pro;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$product['active']) {
|
||||
throw new UnprocessableEntityHttpException('در حال حاضر امکان ثبت سفارش وجود ندارد');}
|
||||
if ($request['direction'] == 1) {
|
||||
if ($data['mazaneh'] != $data['product']['sub_agent']['rate_buy_price']){
|
||||
throw new UnprocessableEntityHttpException('تغییر در مظنه !');
|
||||
}
|
||||
|
||||
if (!$product['open_buy']) {
|
||||
throw new UnprocessableEntityHttpException('درحال حاضر فروش محصول غیرفعال می باشد');
|
||||
}
|
||||
}
|
||||
if ($request['direction'] == 2) {
|
||||
if ($data['mazaneh'] != $data['product']['sub_agent']['rate_sell_price']){
|
||||
throw new UnprocessableEntityHttpException('تغییر در مظنه !');
|
||||
}
|
||||
if (!$product['open_sell']) {
|
||||
throw new UnprocessableEntityHttpException('درحال حاضر خرید محصول غیرفعال می باشد');
|
||||
}
|
||||
}
|
||||
|
||||
// مظنه 7000
|
||||
//7030 اختاف مظنه 30
|
||||
|
||||
//برای کاربران اصلی امیر
|
||||
// 7070 سیستم 50
|
||||
//برای نماینده ها که نسبت به هرکدوم متغیره
|
||||
//7090 قلک طلا 20
|
||||
// برای مشتریان قلک طلا
|
||||
// 10 قلک طلا
|
||||
//
|
||||
|
||||
|
||||
$data['price_original'] = $product['price']['price'];
|
||||
if ($data['direction'] == 1) {
|
||||
$data['price'] = $data['product']['price']['price'] + $data['product']['price']['difference'];
|
||||
}else{
|
||||
$data['price'] = $data['product']['price']['price'] - $data['product']['price']['difference'];
|
||||
}
|
||||
|
||||
$data['price_id'] = $data['product']['price']['id'];
|
||||
$data['total_fee_master'] = 1;
|
||||
$data['total_fee_agent'] = 1;
|
||||
$data['payment_sts'] = 1;
|
||||
$data['sts'] = 1;
|
||||
|
||||
$data['rate_price'] = $data['product']['price']['price'];
|
||||
$data['rate_difference_provider'] = $data['product']['price']['difference_provider'];
|
||||
$data['rate_difference_system'] = $data['product']['price']['difference_liman'];
|
||||
// فقط در صورت وجود customer یا agent مقداردهی میشود
|
||||
if (isset($data['product']['customerSettings']['customer'])) {
|
||||
$data['rate_difference_first'] = $data['direction'] == 1
|
||||
? $data['product']['customerSettings']['customer']['profit_buy']
|
||||
: $data['product']['customerSettings']['customer']['profit_sell'];
|
||||
$data['rate_difference_first_id'] = $data['product']['customerSettings']['customer']['id'];
|
||||
}
|
||||
|
||||
if (isset($data['product']['customerSettings']['agent'])) {
|
||||
$data['rate_difference_second'] = $data['direction'] == 1
|
||||
? $data['product']['customerSettings']['agent']['profit_buy']
|
||||
: $data['product']['customerSettings']['agent']['profit_sell'];
|
||||
$data['rate_difference_second_id'] = $data['product']['customerSettings']['agent']['id'];
|
||||
}
|
||||
|
||||
// محاسبه نهایی (با چک کردن وجود متغیرها)
|
||||
if ($data['direction'] == 1) {
|
||||
$data['rate_price_final'] = $data['rate_price']
|
||||
+ ($data['rate_difference_provider'] ?? 0)
|
||||
+ ($data['rate_difference_system'] ?? 0)
|
||||
+ ($data['rate_difference_first'] ?? 0)
|
||||
+ ($data['rate_difference_second'] ?? 0);
|
||||
|
||||
$data['rate_price_final_map'] = $data['rate_price']
|
||||
. " + " . ($data['rate_difference_provider'] ?? 0)
|
||||
. " + " . ($data['rate_difference_system'] ?? 0);
|
||||
if (isset($data['rate_difference_first'])) {
|
||||
$data['rate_price_final_map'] .= " + " . $data['rate_difference_first'];}
|
||||
if (isset($data['rate_difference_second'])) {
|
||||
$data['rate_price_final_map'] .= " + " . $data['rate_difference_second'];}
|
||||
} else {
|
||||
$data['rate_price_final'] = $data['rate_price']
|
||||
- ($data['rate_difference_provider'] ?? 0)
|
||||
- ($data['rate_difference_system'] ?? 0)
|
||||
- ($data['rate_difference_first'] ?? 0)
|
||||
- ($data['rate_difference_second'] ?? 0);
|
||||
|
||||
$data['rate_price_final_map'] = $data['rate_price']
|
||||
. " - " . ($data['rate_difference_provider'] ?? 0)
|
||||
. " - " . ($data['rate_difference_system'] ?? 0);
|
||||
if (isset($data['rate_difference_first'])) {
|
||||
$data['rate_price_final_map'] .= " - " . $data['rate_difference_first'];}
|
||||
if (isset($data['rate_difference_second'])) {
|
||||
$data['rate_price_final_map'] .= " - " . $data['rate_difference_second'];}
|
||||
|
||||
|
||||
}
|
||||
$data['price'] = $data['rate_price_final']*$data['amount'];
|
||||
|
||||
if ($data['product']['unit'] == 'گرم' ){
|
||||
$change_mesghal = config('change_mesghal');
|
||||
$data['price_original_in_mesghal'] = $data['product']['price']['price'];
|
||||
$data['price_in_mesghal'] = $data['price'];
|
||||
$data['price_original'] = $data['product']['price']['price']/$change_mesghal;
|
||||
$data['price'] =( $data['rate_price_final']/$change_mesghal) ;
|
||||
}
|
||||
$data['total_price'] = $data['price']*$data['amount'];
|
||||
|
||||
$data['provider'] = $data['product']['reading_method'];
|
||||
$data['total_price_original'] = $data['total_price']??0;
|
||||
$data['payment_amount'] = $data['total_price']??0;
|
||||
$data['total_fee_master'] = $data['rate_difference_first']??0+$data['rate_difference_system']??0;
|
||||
$data['total_fee_agent'] = $data['rate_difference_second']??0;
|
||||
//return [$data,$products];
|
||||
$order = Order::create($data);
|
||||
if ((int)$data['amount'] < 200) {
|
||||
if ($data['direction'] == 1) {
|
||||
if ($product['auto_buy']) {
|
||||
$request = new Request([
|
||||
'order_id' => $order->id,
|
||||
'method' => "liman",
|
||||
'sts' => 2,
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$newOrder = $AdminOrderController->changeStatus($request);
|
||||
$OrderIsAuto = "yes";
|
||||
}
|
||||
} else if ($data['direction'] == 2) {
|
||||
if ($product['auto_sell']) {
|
||||
$request = new Request([
|
||||
'order_id' => $order->id,
|
||||
'method' => "liman",
|
||||
'sts' => 2,
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$newOrder = $AdminOrderController->changeStatus($request);
|
||||
$OrderIsAuto = "yes";
|
||||
}
|
||||
}
|
||||
}
|
||||
$siteOrder = $order;
|
||||
$mMaz = number_format($siteOrder['rate_price_final'] / 10000, 0);
|
||||
$mDirc = $siteOrder['direction'] == 2 ? "🔴" : "🟢";
|
||||
if ($siteOrder['input_mode'] == 'cash') {
|
||||
$val = number_format($siteOrder['total_price'], 0);
|
||||
$eqalto = number_format($siteOrder['amount'], 3);
|
||||
} else {
|
||||
$eqalto = number_format($siteOrder['total_price'], 0);
|
||||
$val = number_format($siteOrder['amount'], 3);
|
||||
}
|
||||
$mCustomerName = $siteOrder['customer']['name'];
|
||||
$customerMessage = $val . "@" . $mMaz . "=" . $eqalto . " " . $mDirc;
|
||||
$adminsMessage = $mDirc . " " . $mCustomerName;
|
||||
if (isset($siteOrder['description'])) {
|
||||
$adminsMessage .= " (" . $siteOrder['description'] . ")";
|
||||
}
|
||||
$adminsMessage .= "\n" . "🛒 " . $product['title'];
|
||||
$adminsMessage .= "\n" . " " . $val . "@" . $mMaz . "=" . $eqalto;
|
||||
|
||||
if ($cntsForSms = Cnt::where('key', 'numberToSendMassageInOrder')->where('title_fa', 'true')->get()) {
|
||||
foreach ($cntsForSms as $cntForSms) {
|
||||
$this->sendMessage($cntForSms->value, $adminsMessage);
|
||||
}
|
||||
}
|
||||
|
||||
$message = auth('customer')->user()->name . " عزیز" . "\n"
|
||||
. 'در تاریخ ' . verta()->format('Y/n/j H:i:s') . " سفارش شما ثبت شد. " . "\n"
|
||||
. "با تشکر" . config('company');
|
||||
$this->sendMessage($user->mobile, $customerMessage);
|
||||
return[$data,$order];
|
||||
return[$data,$order];
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$add_sell_price = 0;
|
||||
$PriceMain = Price::where('product_id', $data['product_id'])->orderBy('id', 'desc')->first();
|
||||
$data['product'] = product::where('id', $data['product_id'])->first();
|
||||
$data['price'] = $PriceMain->price;
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
if (! $data['product']->unit == "تعداد" ){
|
||||
$data['price'] = $data['price'] / $mesghal_convert;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
$data['customer_id'] = auth('customer')->id();
|
||||
$data['sts'] = 1;
|
||||
$data['payment_sts'] = 1;
|
||||
$data['type'] = auth('customer')->user()->type;
|
||||
|
||||
|
||||
$response['credit'] = $credit = CustomerCredit::firstOrCreate(
|
||||
['product_id' => $data['product_id'], 'customer_id' => $user->id,],
|
||||
['product_id' => $data['product_id'], 'customer_id' => $user->id,
|
||||
'buy_credit' => $product->default_credit, 'sell_credit' => $product->default_credit]);
|
||||
// $response['credit'] = $credit = CustomerCredit::where('product_id', $data['product_id'])->where('customer_id', $user->id)->first();
|
||||
|
||||
if ($data['direction'] == 1) {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->buy_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->buy_gram_price;
|
||||
$data['fee_agent'] = $package->buy_gram_price;
|
||||
$data['total_fee_agent'] = $package->buy_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['price'] += $add_sell_price;
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->buy_credit - $credit->blocked_buy_credit;
|
||||
|
||||
if ($remain < $data['amount']) {
|
||||
// throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
|
||||
}
|
||||
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_buy_credit' => $credit->blocked_buy_credit + $data['amount']
|
||||
]);
|
||||
} else {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->sell_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->sell_gram_price;
|
||||
$data['fee_agent'] = $package->sell_gram_price;
|
||||
$data['total_fee_agent'] = $package->sell_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['price'] -= $add_sell_price;
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->sell_credit - $credit->blocked_sell_credit;
|
||||
if ($remain < $data['amount']) {
|
||||
// throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
|
||||
}
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_sell_credit' => $credit->blocked_sell_credit + $data['amount']
|
||||
]);
|
||||
}
|
||||
$data['total_price'] = $data['amount'] * $data['price'];
|
||||
$data['payment_remind'] = 0;
|
||||
$data['payment_amount'] = $data['total_price'];
|
||||
$data['agent_id'] = auth('customer')->user()->agent_id;
|
||||
$data['total_price_round'] = round($data['total_price'], -6);
|
||||
if ($data['input_mode'] == "gold") {
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
} elseif ($data['input_mode'] == "cash") {
|
||||
$data['amount'] = $data['cash'] / $data['price'];
|
||||
$data['total_price_round'] = $data['payment_amount'] = $data['total_price'] = $data['total_price_original'] = $data['cash'];
|
||||
} else {// for old app
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
}
|
||||
$data['price_id'] = $PriceMain->id;
|
||||
$order = Order::create($data);
|
||||
//-----------------تاید اتوماتیک در کلهور
|
||||
|
||||
//--------messages
|
||||
$siteOrder = $order;
|
||||
$mMaz = number_format($siteOrder['price_in_mesghal'] / 10000, 0);
|
||||
$mDirc = $siteOrder['direction'] == 2 ? "🔴" : "🟢";
|
||||
if ($siteOrder['input_mode'] == 'cash') {
|
||||
$val = number_format($siteOrder['payment_amount'], 0);
|
||||
$eqalto = number_format($siteOrder['amount'], 3);
|
||||
} else {
|
||||
$eqalto = number_format($siteOrder['payment_amount'], 0);
|
||||
$val = number_format($siteOrder['amount'], 3);
|
||||
}
|
||||
$mCustomerName = $siteOrder['customer']['name'];
|
||||
$customerMessage = $val . "@" . $mMaz . "=" . $eqalto . " " . $mDirc;
|
||||
$adminsMessage = $mDirc . " " . $mCustomerName;
|
||||
if (isset($siteOrder['description'])) {
|
||||
$adminsMessage .= " (" . $siteOrder['description'] . ")";
|
||||
}
|
||||
$adminsMessage .= "\n" . "🛒 " . $product->title;
|
||||
$adminsMessage .= "\n" . " " . $val . "@" . $mMaz . "=" . $eqalto;
|
||||
|
||||
if ($cntsForSms = Cnt::where('key', 'numberToSendMassageInOrder')->where('title_fa', 'true')->get()) {
|
||||
foreach ($cntsForSms as $cntForSms) {
|
||||
$user = User::where('mobile', $cntForSms->value)->first() ?: Customer::where('mobile', $cntForSms->value)->first();
|
||||
Http::get("https://api.wwwapp.ir/telegran_send.php", [
|
||||
'botToken' => $credentials['telegram']['token'],
|
||||
'chatId' => $user->telegram,
|
||||
'message' => "{$adminsMessage}",
|
||||
]);
|
||||
// $this->sendMessage($cntForSms->value, $adminsMessage);
|
||||
}
|
||||
}
|
||||
|
||||
$message = auth('customer')->user()->name . " عزیز" . "\n"
|
||||
. 'در تاریخ ' . verta()->format('Y/n/j H:i:s') . " سفارش شما ثبت شد. " . "\n"
|
||||
. "با تشکر" . config('company');
|
||||
$this->sendMessage($user->mobile, $customerMessage);
|
||||
CancelJob::dispatch($order->id)->delay(now()->addMinutes(4))->onConnection('database');
|
||||
return response()->json($order);
|
||||
}
|
||||
public function storeB(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
$response = [];
|
||||
$response['message'] = 'بسته می باشد';
|
||||
$response['data'] = $data;
|
||||
$user = auth('customer')->user();
|
||||
$response['product'] = $product = Product::find($data['product_id']);
|
||||
if (!$product->active) {
|
||||
throw new UnprocessableEntityHttpException('در حال حاضر امکان ثبت سفارش وجود ندارد');
|
||||
}
|
||||
if ($request->direction == 1) {
|
||||
if (!$product->open_buy) {
|
||||
throw new UnprocessableEntityHttpException('درحال حاضر فروش محصول غیرفعال می باشد');
|
||||
}
|
||||
}
|
||||
if ($request->direction == 2) {
|
||||
if (!$product->open_sell) {
|
||||
throw new UnprocessableEntityHttpException('درحال حاضر خرید محصول غیرفعال می باشد');
|
||||
}
|
||||
}
|
||||
|
||||
$add_sell_price = 0;
|
||||
$PriceMain = Price::where('product_id', $data['product_id'])->orderBy('id', 'desc')->first();
|
||||
$data['product'] = product::where('id', $data['product_id'])->first();
|
||||
$data['price'] = $PriceMain->price;
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
if (! $data['product']->unit == "تعداد" ){
|
||||
$data['price'] = $data['price'] / $mesghal_convert;
|
||||
}
|
||||
$base = Package::where('is_base', true)->first();
|
||||
$package_base = PackageProduct::where('package_id', $base->id)->where('product_id', $data['product_id'])->first();
|
||||
$package = null;
|
||||
// if (auth('customer')->user()->type == 2){
|
||||
$package = PackageProduct::where('package_id', auth('customer')->user()->package_id)->where('product_id', $data['product_id'])->first();
|
||||
// }
|
||||
|
||||
|
||||
$data['customer_id'] = auth('customer')->id();
|
||||
$data['sts'] = 1;
|
||||
$data['payment_sts'] = 1;
|
||||
$data['type'] = auth('customer')->user()->type;
|
||||
|
||||
|
||||
$response['credit'] = $credit = CustomerCredit::firstOrCreate(
|
||||
['product_id' => $data['product_id'], 'customer_id' => $user->id,],
|
||||
['product_id' => $data['product_id'], 'customer_id' => $user->id,
|
||||
'buy_credit' => $product->default_credit, 'sell_credit' => $product->default_credit]);
|
||||
// $response['credit'] = $credit = CustomerCredit::where('product_id', $data['product_id'])->where('customer_id', $user->id)->first();
|
||||
|
||||
if ($data['direction'] == 1) {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->buy_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->buy_gram_price;
|
||||
$data['fee_agent'] = $package->buy_gram_price;
|
||||
$data['total_fee_agent'] = $package->buy_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['price'] += $add_sell_price;
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->buy_credit - $credit->blocked_buy_credit;
|
||||
|
||||
if ($remain < $data['amount']) {
|
||||
// throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
|
||||
}
|
||||
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_buy_credit' => $credit->blocked_buy_credit + $data['amount']
|
||||
]);
|
||||
} else {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->sell_gram_price;
|
||||
$data['fee_master'] = $add_sell_price;
|
||||
$data['total_fee_master'] = $add_sell_price * $data['amount'];
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->sell_gram_price;
|
||||
$data['fee_agent'] = $package->sell_gram_price;
|
||||
$data['total_fee_agent'] = $package->sell_gram_price * $data['amount'];
|
||||
}
|
||||
$data['price_original'] = $data['price'];
|
||||
$data['price_original_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$data['price'] -= $add_sell_price;
|
||||
$data['price_in_mesghal'] = round($data['price'] * $mesghal_convert, -3);
|
||||
$remain = $credit->sell_credit - $credit->blocked_sell_credit;
|
||||
if ($remain < $data['amount']) {
|
||||
// throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
|
||||
}
|
||||
CustomerCredit::find($credit->id)->update([
|
||||
'blocked_sell_credit' => $credit->blocked_sell_credit + $data['amount']
|
||||
]);
|
||||
}
|
||||
$data['total_price'] = $data['amount'] * $data['price'];
|
||||
$data['payment_remind'] = 0;
|
||||
$data['payment_amount'] = $data['total_price'];
|
||||
$data['agent_id'] = auth('customer')->user()->agent_id;
|
||||
$data['total_price_round'] = round($data['total_price'], -6);
|
||||
if ($data['input_mode'] == "gold") {
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
} elseif ($data['input_mode'] == "cash") {
|
||||
$data['amount'] = $data['cash'] / $data['price'];
|
||||
$data['total_price_round'] = $data['payment_amount'] = $data['total_price'] = $data['total_price_original'] = $data['cash'];
|
||||
} else {// for old app
|
||||
$data['total_price_original'] = $data['amount'] * $data['price_original'];
|
||||
}
|
||||
$data['price_id'] = $PriceMain->id;
|
||||
$order = Order::create($data);
|
||||
//-----------------تاید اتوماتیک در کلهور
|
||||
$OrderIsAuto = "no";
|
||||
if ($order->total_price > 0) {
|
||||
if ($data['direction'] == 1) {
|
||||
if ($product->auto_buy) {
|
||||
$request = new Request([
|
||||
'order_id' => $order->id,
|
||||
'method' => "liman",
|
||||
'sts' => 2,
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$newOrder = $AdminOrderController->changeStatus($request);
|
||||
$OrderIsAuto = "yes";
|
||||
}
|
||||
} else if ($data['direction'] == 2) {
|
||||
if ($product->auto_sell) {
|
||||
$request = new Request([
|
||||
'order_id' => $order->id,
|
||||
'method' => "liman",
|
||||
'sts' => 2,
|
||||
]);
|
||||
$AdminOrderController = new AdminOrderController();
|
||||
$newOrder = $AdminOrderController->changeStatus($request);
|
||||
$OrderIsAuto = "yes";
|
||||
}
|
||||
}
|
||||
}
|
||||
//--------messages
|
||||
$siteOrder = $order;
|
||||
$mMaz = number_format($siteOrder['price_in_mesghal'] / 10000, 0);
|
||||
$mDirc = $siteOrder['direction'] == 2 ? "🔴" : "🟢";
|
||||
if ($siteOrder['input_mode'] == 'cash') {
|
||||
$val = number_format($siteOrder['payment_amount'], 0);
|
||||
$eqalto = number_format($siteOrder['amount'], 3);
|
||||
} else {
|
||||
$eqalto = number_format($siteOrder['payment_amount'], 0);
|
||||
$val = number_format($siteOrder['amount'], 3);
|
||||
}
|
||||
$mCustomerName = $siteOrder['customer']['name'];
|
||||
$customerMessage = $val . "@" . $mMaz . "=" . $eqalto . " " . $mDirc;
|
||||
$adminsMessage = $mDirc . " " . $mCustomerName;
|
||||
if (isset($siteOrder['description'])) {
|
||||
$adminsMessage .= " (" . $siteOrder['description'] . ")";
|
||||
}
|
||||
$adminsMessage .= "\n" . "🛒 " . $product->title;
|
||||
$adminsMessage .= "\n" . " " . $val . "@" . $mMaz . "=" . $eqalto;
|
||||
|
||||
if ($cntsForSms = Cnt::where('key', 'numberToSendMassageInOrder')->where('title_fa', 'true')->get()) {
|
||||
foreach ($cntsForSms as $cntForSms) {
|
||||
$this->sendMessage($cntForSms->value, $adminsMessage);
|
||||
}
|
||||
}
|
||||
|
||||
$message = auth('customer')->user()->name . " عزیز" . "\n"
|
||||
. 'در تاریخ ' . verta()->format('Y/n/j H:i:s') . " سفارش شما ثبت شد. " . "\n"
|
||||
. "با تشکر" . config('company');
|
||||
$this->sendMessage($user->mobile, $customerMessage);
|
||||
CancelJob::dispatch($order->id)->delay(now()->addMinutes(4))->onConnection('database');
|
||||
return response()->json($order);
|
||||
}
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$records = Order::with(['product', 'transaction.wallet_tr.product'])->where('customer_id', auth('customer')->id());
|
||||
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([
|
||||
'total_price',
|
||||
'id',
|
||||
"product.title",
|
||||
'description'])
|
||||
->select([
|
||||
'*',
|
||||
Order::$SELECT_STS_STR,
|
||||
Order::$SELECT_CAJ
|
||||
])->export($records);
|
||||
$records["rows"] = $records["rows"]->map(function ($record) {
|
||||
$record->amount = round($record->amount, 3);
|
||||
return $record;
|
||||
});
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
return response()->json(
|
||||
Order::select(['*', Order::$SELECT_STS_STR, Order::$SELECT_CAJ])->findOrFail($id)
|
||||
);
|
||||
}
|
||||
|
||||
public function tableAgent(Request $request)
|
||||
{
|
||||
$records = Order::with(['product', 'transaction.wallet_tr.product', 'customer'])->where('agent_id', auth('customer')->id());
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(['product.title'])
|
||||
->select([
|
||||
'*', Order::$SELECT_STS_STR, Order::$SELECT_CAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function getMinMax()
|
||||
{
|
||||
$minMaxValues = Order::selectRaw('MIN(price) as min_price, MAX(price) as max_price')
|
||||
->selectRaw('MIN(amount) as min_amount, MAX(amount) as max_amount')
|
||||
->first();
|
||||
return $minMaxValues;
|
||||
|
||||
}
|
||||
|
||||
public function getOrderTransaction($order)
|
||||
{
|
||||
$tr = Transaction::with('wallet_tr')->select(['*', Transaction::$SELECT_CAJ])->where('order_id', $order)->get();
|
||||
return response()->json($tr);
|
||||
}
|
||||
|
||||
public function verify_offer_price($order_id)
|
||||
{
|
||||
$order = Order::findOrFail($order_id);
|
||||
$base = Package::where('is_base', true)->first();
|
||||
$package_base = PackageProduct::where('package_id', $base->id)->where('product_id', $order->product_id)->first();
|
||||
$package = null;
|
||||
if ($order->type == 2) {
|
||||
$cu = Customer::findOrFail($order->customer_id);
|
||||
$package = PackageProduct::where('package_id', $cu->package_id)->where('product_id', $order->product_id)->first();
|
||||
}
|
||||
$add_sell_price = 0;
|
||||
$price = $order->offer_price;
|
||||
if ($order->direction == 1) {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->buy_gram_price;
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->buy_gram_price;
|
||||
}
|
||||
$price += $add_sell_price;
|
||||
} else {
|
||||
if (!is_null($package_base)) {
|
||||
$add_sell_price = $package_base->sell_gram_price;
|
||||
}
|
||||
if (!is_null($package)) {
|
||||
$add_sell_price += $package->sell_gram_price;
|
||||
}
|
||||
$price -= $add_sell_price;
|
||||
}
|
||||
$order->update([
|
||||
'pre_price' => $order->price,
|
||||
'pre_original_price' => $order->price_original,
|
||||
'price' => $price,
|
||||
'sts' => 2,
|
||||
'total_price' => $price * $order->amount,
|
||||
'price_original' => $order->offer_price,
|
||||
'total_price_original' => $order->offer_price * $order->amount,
|
||||
]);
|
||||
if ($order->direction == 1) {
|
||||
$this->createTransactionBuyWhenSuccess($order);
|
||||
} else {
|
||||
$this->createTransactionSellWhenSuccess($order);
|
||||
}
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function checkOrder()
|
||||
{
|
||||
$order = Order::where('customer_id', auth('customer')->id())->orderBy('id', 'desc')->first();
|
||||
if (!is_null($order)) {
|
||||
if (in_array($order->sts, [1, 3])) {
|
||||
return response()->json(['check' => true,
|
||||
'order_id' => $order->id,
|
||||
'sts' => $order->sts,
|
||||
'offer' => $order->offer_price,
|
||||
'offer_mesghal_price' => $order->offer_mesghal_price
|
||||
]);
|
||||
}
|
||||
return response()->json([
|
||||
'check' => false,
|
||||
'order_id' => $order->id,
|
||||
'sts' => $order->sts,
|
||||
]);
|
||||
} else {
|
||||
return response()->json([
|
||||
'check' => false,
|
||||
'order_id' => null,
|
||||
'sts' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function cancel_offer_price($order_id)
|
||||
{
|
||||
$order = Order::findOrFail($order_id)->update(['sts' => 4]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\SuperPackageController;
|
||||
use App\Models\Package;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PackageController extends SuperPackageController
|
||||
{
|
||||
public function __construct(Request $request)
|
||||
{
|
||||
$request->request->add([
|
||||
'agent_id'=>auth('customer')->id(),
|
||||
'is_base'=>false
|
||||
]);
|
||||
$this->with = ['customer','agent','sub_packages.product'];
|
||||
$this->query = Package::with($this->with)->where('agent_id',auth('customer')->id())->where('is_base',false);
|
||||
parent::__construct($this->with, ['*'], $this->query, ['title']);
|
||||
}
|
||||
|
||||
public function listPackage(){
|
||||
return response()->json($this->query->get());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,440 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\DB\Customer;
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\{Package,Customer as CustomerModel};
|
||||
use App\Models\{PackageProduct,CustomersSetting};
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductCredit;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Admin\PriceController;
|
||||
use function Symfony\Component\Translation\t;
|
||||
|
||||
class ProductController extends Controller
|
||||
{
|
||||
|
||||
public function list_product($CU_adm = null)
|
||||
{
|
||||
// $PriceController = new PriceController;
|
||||
// $PriceController->b750();
|
||||
$this->auto_close_open();
|
||||
$userTID = auth()->id();//get token
|
||||
if (auth('customer')->id()){
|
||||
// return response()->json('cu');
|
||||
}else{
|
||||
$userTID = $CU_adm;
|
||||
|
||||
}
|
||||
|
||||
$customer = CustomerModel::with(['agent.CustomersSetting', 'CustomersSetting'])->where('id', $userTID)->first();
|
||||
$list_product = Product::with(['price'])->where('active', 1)->get();
|
||||
|
||||
foreach ($list_product as &$product) {
|
||||
$prises = [];
|
||||
$current_time = now()->format('H:i:s');
|
||||
$show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
if (!$show) {
|
||||
$product->open_sell = $show;
|
||||
$product->open_buy = $show;
|
||||
}
|
||||
}
|
||||
$customerSettings = [];
|
||||
|
||||
if ($customer->agent_id) {
|
||||
|
||||
foreach ($list_product as $key => &$product) {
|
||||
$prises[$product->id]= ["sell_price" => $product->price->difference , "buy_price" => $product->price->difference ];
|
||||
$agent = CustomerModel::with(['agent','CustomersSetting'])->where('id',$customer->agent_id)->first();
|
||||
$settings = $agent->customersSetting()->get();
|
||||
if ($setting = $settings->where('customer_id', $customer->id)->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('customer_id', $customer->id)->whereNull('product_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $customer->group)->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $customer->group)->whereNull('product_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('customer_id')->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["customer"]=$setting;
|
||||
}else{
|
||||
unset($prises[$key]);
|
||||
unset($list_product[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($agent->agent_id) {
|
||||
foreach ($list_product as $key => &$product) {
|
||||
$agent2 = CustomerModel::with(['agent','CustomersSetting'])->where('id',$agent->agent_id)->first();
|
||||
$settings = $agent2->customersSetting()->get();
|
||||
if ($setting = $settings->where('customer_id', $agent->id)->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('customer_id', $agent->id)->whereNull('product_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $agent->group)->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $agent->group)->whereNull('product_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('customer_id')->where('product_id', $product->id)->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->first()) {
|
||||
$prises[$product->id]['buy_price']+=$setting->profit_buy;
|
||||
$prises[$product->id]['sell_price']+=$setting->profit_sell;
|
||||
$customerSettings["agent"]=$setting;
|
||||
}else{
|
||||
unset($prises[$key]);
|
||||
unset($list_product[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
foreach ($list_product as &$product) {
|
||||
|
||||
if ($product->unit =="گرم" ){
|
||||
$prises[$product->id]['buy_gram_price'] = round($product->price->difference / config('change_mesghal'));
|
||||
$prises[$product->id]['sell_gram_price'] =round($product->price->difference/config('change_mesghal'));
|
||||
}else{
|
||||
$prises[$product->id]['buy_gram_price']=$product->price->difference;
|
||||
$prises[$product->id]['sell_gram_price'] =$product->price->difference;
|
||||
}
|
||||
|
||||
$product->customerSettings = $customerSettings;
|
||||
|
||||
if (!$customer->agent_id) {
|
||||
$prises[$product->id]['buy_price']=$product->price->difference;
|
||||
$prises[$product->id]['sell_price'] =$product->price->difference;
|
||||
$product->sub_agent = $product[$product->id];
|
||||
}
|
||||
|
||||
if (isset($prises[$product->id])) {
|
||||
$prises[$product->id]['rate_buy_price'] = $product->price->price+$prises[$product->id]['buy_price'];
|
||||
$prises[$product->id]['rate_sell_price'] = $product->price->price-$prises[$product->id]['sell_price'];
|
||||
if ($product->unit =="گرم" ){
|
||||
$prises[$product->id]['change_mesghal'] = config('change_mesghal');
|
||||
$prises[$product->id]['rate_buy_gram_price'] =$prises[$product->id]['rate_buy_price']/config('change_mesghal');
|
||||
$prises[$product->id]['rate_sell_gram_price'] =$prises[$product->id]['rate_sell_price']/config('change_mesghal');
|
||||
}
|
||||
$product->sub_agent = $prises[$product->id];
|
||||
$product->customerSettings = $customerSettings;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// return response()->json($customerSettings);
|
||||
return response()->json($list_product);
|
||||
}
|
||||
|
||||
public function list_product1($customer_id =null)
|
||||
{
|
||||
$PriceController = new PriceController;
|
||||
$PriceController->b750();
|
||||
$this->auto_close_open();
|
||||
$userTID =$customer_id ?? auth()->id();//get token
|
||||
$customer = CustomerModel::with(['agent.CustomersSetting', 'CustomersSetting'])->where('id', $userTID)->first();
|
||||
|
||||
$list_product = Product::with(['price'])->where('active', 1)->get();
|
||||
|
||||
foreach ($list_product as &$product) {
|
||||
$profits = [];
|
||||
$f = 0;
|
||||
$ff = 0;
|
||||
$sell_price = 0;
|
||||
$buy_price = 0;
|
||||
if ($customer->agent_id) {
|
||||
$agent = CustomerModel::with(['agent', 'CustomersSetting'])->where('id', $customer->agent_id)->first();
|
||||
if ($agent->agent_id) {
|
||||
$agent2 = CustomerModel::with(['agent', 'CustomersSetting'])->where('id', $agent->agent_id)->first();
|
||||
$settings = $agent2->customersSetting()->get();
|
||||
|
||||
if ($setting = $settings->where('customer_id', $userTID)->where('product_id', $product->id)->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 1;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('customer_id', $userTID)->whereNull('product_id')->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 2;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('group', $customer->group)->where('product_id', $product->id)->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 4;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('group', $customer->group)->whereNull('product_id')->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 3;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->where('product_id', $product->id)->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 6;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->first() and $ff == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$ff = 7;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
|
||||
if ($ff == 0) {
|
||||
// return response()->json(true);
|
||||
} else {
|
||||
$prises = ["sell_price" => $product->price->difference + $sell_price, "buy_price" => $product->price->difference + $buy_price];
|
||||
$product->ff = $ff;
|
||||
}
|
||||
}
|
||||
|
||||
$settings = $agent->customersSetting()->get();
|
||||
if ($setting = $settings->where('customer_id', $userTID)->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 1;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('customer_id', $userTID)->whereNull('product_id')->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 2;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('group', $customer->group)->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 4;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->where('group', $customer->group)->whereNull('product_id')->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 3;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 6;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->first() and $f == false) {
|
||||
$buy_price += $setting->profit_buy;
|
||||
$sell_price += $setting->profit_sell;
|
||||
$f = 7;
|
||||
$profits[] = $setting;
|
||||
}
|
||||
|
||||
if ($f == 0) {
|
||||
// return response()->json(true);
|
||||
} else {
|
||||
$prises = ["sell_price" => $product->price->difference + $sell_price, "buy_price" => $product->price->difference + $buy_price];
|
||||
$product->sub_agent = $prises;
|
||||
$product->f = $f;
|
||||
$product->ff = $ff;
|
||||
$product->profits = $profits;
|
||||
}
|
||||
} else {
|
||||
$prises = ["sell_price" => $product->price->difference + $sell_price, "buy_price" => $product->price->difference + $buy_price];
|
||||
$product->sub_agent = $prises;
|
||||
$product->f = $f;
|
||||
}
|
||||
$current_time = now()->format('H:i:s');
|
||||
$show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
if (!$show) {
|
||||
$product->open_sell = $show;
|
||||
$product->open_buy = $show;
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json($list_product);
|
||||
}
|
||||
public function list_productN()
|
||||
{
|
||||
|
||||
$PriceController = new PriceController;
|
||||
$PriceController->b750();
|
||||
$this->auto_close_open();
|
||||
$userTID =auth()->id();
|
||||
$customer = CustomerModel::with(['agent.CustomersSetting','CustomersSetting'])->where('id',$userTID)->first();
|
||||
$sell_priceprises = 0;
|
||||
$buy_price = 0;
|
||||
|
||||
|
||||
$list_product = Product::with([ 'price'])->where('active', 1)->get();
|
||||
$current_time = now()->format('H:i:s');
|
||||
|
||||
|
||||
|
||||
foreach ($list_product as &$product) {
|
||||
$f= 0;
|
||||
|
||||
if ($customer->agent_id){
|
||||
$agent = CustomerModel::with(['agent','CustomersSetting'])->where('id',$customer->agent_id)->first();
|
||||
|
||||
$settings = $agent->customersSetting()->get();
|
||||
if ( $setting = $settings->where('customer_id', $userTID)->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 1;
|
||||
}
|
||||
elseif ($setting=$settings->where('customer_id', $userTID)->whereNull('product_id')->first() and $f == false) {
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 2;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $customer->group)->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 4;
|
||||
}
|
||||
elseif ($setting=$settings->where('group', $customer->group)->whereNull('product_id')->first() and $f == false) {
|
||||
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 3;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->where('product_id', $product->id)->first() and $f == false) {
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 6;
|
||||
}
|
||||
elseif ($setting = $settings->whereNull('group')->whereNull('product_id')->whereNull('customer_id')->first() and $f == false) {
|
||||
$buy_price = $setting->profit_buy;
|
||||
$sell_price = $setting->profit_sell;
|
||||
$f= 7;
|
||||
}
|
||||
if ($f== 0) {
|
||||
// return response()->json(true);
|
||||
}else{
|
||||
$prises = ["sell_price"=>$product->price->difference+$sell_price,"buy_price"=>$product->price->difference+$buy_price];
|
||||
$product->sub_agent = $prises;
|
||||
$product->buy_price = $f;
|
||||
}
|
||||
|
||||
}else{
|
||||
$prises = ["sell_price"=>$product->price->difference+$sell_price,"buy_price"=>$product->price->difference+$buy_price];
|
||||
$product->sub_agent = $prises;
|
||||
$product->buy_price = $f;
|
||||
}
|
||||
|
||||
$show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
if (!$show){
|
||||
$product->open_sell = $show;
|
||||
$product->open_buy = $show;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
return response()->json($list_product);
|
||||
}
|
||||
public function list_productB()
|
||||
{
|
||||
$PriceController = new PriceController;
|
||||
$PriceController->b750();
|
||||
$this->auto_close_open();
|
||||
$list_product = Product::with(['file', 'price', 'sub'])->where('active', 1)->get();
|
||||
$current_time = now()->format('H:i:s');
|
||||
|
||||
$package_id = auth('customer')->user()->package_id;
|
||||
|
||||
try {
|
||||
$pg = !is_null($package_id) ? Package::findOrFail($package_id) : null;
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
|
||||
$pg = null; // در صورت عدم وجود رکورد، مقدار null تعیین میشود
|
||||
}
|
||||
foreach ($list_product as &$product) {
|
||||
$show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
if (!$show){
|
||||
$product->open_sell = $show;
|
||||
$product->open_buy = $show;
|
||||
}
|
||||
// $temp_product = clone $product;
|
||||
|
||||
if ($pg) {
|
||||
if (isset($pg)) {
|
||||
$product['sub_agent'] = PackageProduct::where('package_id', $pg->id)->where('product_id', $product->id)->first();
|
||||
}
|
||||
}
|
||||
}
|
||||
return response()->json($list_product);
|
||||
|
||||
}
|
||||
public function auto_close_open()
|
||||
{
|
||||
// $products = Product::with([])->get();
|
||||
// $current_time = now()->format('H:i:s');
|
||||
// foreach ($products as $product) {
|
||||
// $show = ($current_time >= $product->auto_open_at && $current_time <= $product->auto_close_at);
|
||||
// Product::where('id', $product->id)->update([
|
||||
// 'open_sell' => $show,
|
||||
// 'open_buy' => $show,
|
||||
// ]);
|
||||
// }
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
|
||||
$data = $request->all();
|
||||
$query_table = Product::with(['file', 'price'])->where('show', 1);
|
||||
TableEngine::create($query_table, $data)
|
||||
->initSearch(['title'])
|
||||
->select(['*'])
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
|
||||
public function listProductCredit()
|
||||
{
|
||||
|
||||
$credit = ProductCredit::with('product.file')->where('type', 2)->get();
|
||||
return response()->json($credit);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,182 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\DB\Te\TableEngine;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Morilog\Jalali\Jalalian;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class TahesabController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
|
||||
if ($this->Config('tahesab') !== "send_importent") {
|
||||
return response()->json([
|
||||
'message' => 'این بخش نیاز به اتصال به نرم افزار حسابداری شما دارد'
|
||||
], 422);
|
||||
}
|
||||
|
||||
// Get the authenticated user
|
||||
$user = auth()->user();
|
||||
// Define default date range
|
||||
// $fromDate =Jalalian::forge($request->startDate)->format('Y-m-d') ?? Jalalian::forge(time())->subMonths(2)->format('Y-m-d');
|
||||
// $toDate =Jalalian::forge($request->endDate)->format('Y-m-d') ?? Jalalian::forge(time())->format('Y-m-d');
|
||||
$fromDate = $request->startDate ? Jalalian::forge($request->startDate)->format('Y-m-d') : Jalalian::forge(time())->subMonths(1)->format('Y-m-d');
|
||||
$toDate = $request->endDate ? Jalalian::forge($request->endDate)->format('Y-m-d') : Jalalian::forge(time())->format('Y-m-d');
|
||||
|
||||
|
||||
// Prepare payload for the API request
|
||||
$DoNewMoshtari = [
|
||||
2000000000, // Count_Last
|
||||
$user->tahesab_id, // Moshtari_Code
|
||||
$fromDate, // AzTarikhShamsi
|
||||
$toDate, // TaTarikhShamsi
|
||||
];
|
||||
|
||||
try {
|
||||
// Send the HTTP request
|
||||
$response = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' => $this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'DoListAsnad' => $DoNewMoshtari
|
||||
]);
|
||||
$returnArray = [];
|
||||
|
||||
// تبدیل دادهها با foreach
|
||||
foreach ($response->json() as $DoListAsnad) {
|
||||
// return $DoListAsnad;
|
||||
$returnArray[] = (object) $DoListAsnad; // اضافه کردن هر آیتم به عنوان آبجکت
|
||||
}
|
||||
// Return the response as an array
|
||||
return $returnArray;
|
||||
} catch (\Exception $e) {
|
||||
// Handle errors gracefully
|
||||
return response()->json([
|
||||
'message' => 'خطایی در ارتباط با سرور رخ داد.',
|
||||
'error' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
public function my_detail(Request $request,$offset=0)
|
||||
{
|
||||
if ($this->Config('tahesab') != "send_importent" or true){
|
||||
return response()->json([
|
||||
'message' => 'این بخش در حال توسعه میباشد'
|
||||
], 422);
|
||||
}
|
||||
// $user = auth()->user();
|
||||
// return $responseDetails = Http::withoutVerifying()
|
||||
// ->post("https://192.168.200.20:5555/api/v1/Tahesab/GetHesabDetailByMCode?dbName=4&mCode=$user->tahesab_id&offset=0&offset=" . ($offset * 100), [
|
||||
// 'dbName' => '4',
|
||||
// 'mCode' => $user->tahesab_id,
|
||||
// 'offset' =>$offset * 100,
|
||||
// 'length' =>100,
|
||||
// ])->json();
|
||||
}
|
||||
public function detail(Request $request, $id)
|
||||
{
|
||||
if ($this->Config('tahesab') != "send_importent" or true){
|
||||
return response()->json([
|
||||
'message' => 'این بخش در حال توسعه میباشد'
|
||||
], 422);
|
||||
}
|
||||
// return $responseDetails = Http::withoutVerifying()->post('https://192.168.200.20:5555/api/v1/Tahesab/GetHesabDetailByFactorCode', [
|
||||
// 'dbName' => '4',
|
||||
// 'Factor_Code' => $id,
|
||||
// ])->json();
|
||||
}
|
||||
|
||||
public function mandeh()
|
||||
{
|
||||
|
||||
if ($this->Config('tahesab') != "send_importent"){
|
||||
return response()->json([
|
||||
'message' => 'این بخش نیاز به اتصال به نرم افزار حسابداری شما دارد'
|
||||
], 422);
|
||||
}
|
||||
$user = auth()->user();
|
||||
|
||||
$DoNewMoshtari = [
|
||||
$user->tahesab_id, // Name
|
||||
];
|
||||
$response = Http::withoutVerifying()
|
||||
->withToken($this->Config('tahesab_token'))
|
||||
->withHeaders(['DBName' =>$this->Config('tahesab_db')])
|
||||
->post($this->Config('tahesab_api'), [
|
||||
'getmandehesabbycode' => $DoNewMoshtari
|
||||
])->json();
|
||||
|
||||
$responseData = $response['MandeHesab'][0] ?? [];
|
||||
$returnArray = []; // Initialize the return array
|
||||
$isKol = false;
|
||||
$unit = '';
|
||||
|
||||
foreach ($responseData as $key => $value) {
|
||||
if ($key == "Code") {
|
||||
continue; // Skip the "Code" key
|
||||
}
|
||||
// Check for specific keys and set the Farsi name
|
||||
$isKol=false;
|
||||
|
||||
switch ($key) {
|
||||
case "MandeyeKolBePool":
|
||||
$name_fa = 'کل به ریال';
|
||||
$unit = 'ریال';
|
||||
$isKol=true;
|
||||
break;
|
||||
case "MandeyeMali":
|
||||
$name_fa = 'مانده ریالی';
|
||||
$unit = 'ریال';
|
||||
break;
|
||||
case "MandeyeKolBeTALA":
|
||||
$name_fa = 'کل به طلا';
|
||||
$unit = 'گرم';
|
||||
$isKol=true;
|
||||
break;
|
||||
case "MandeyeVazni":
|
||||
$name_fa = 'طلا';
|
||||
$unit = 'گرم';
|
||||
$isKol=true;
|
||||
break;
|
||||
case "MandeMenhayeSekeBePool":
|
||||
$name_fa = 'مانده منهای سکه به کل';
|
||||
$isKol=true;
|
||||
$unit = 'ریال';
|
||||
break;
|
||||
case "MandeMenhayeSekeBeTala":
|
||||
$name_fa = 'معادل حمع سکه ها به طلا';
|
||||
$unit = 'معادل حمع سکه ها به طلا';
|
||||
$isKol=true;
|
||||
break;
|
||||
case "MandeMenhayeSeke":
|
||||
$name_fa = 'طلا منهای سکه';
|
||||
$unit = 'گرم';
|
||||
break;
|
||||
default:
|
||||
$name_fa = str_replace("Seke", "سکه", $key);
|
||||
|
||||
|
||||
}
|
||||
|
||||
$returnArray[] = [
|
||||
"isKol" => $isKol,
|
||||
"name_fa" => $name_fa,
|
||||
"name_eng" => $key,
|
||||
"value" => $value ,// This is the actual value
|
||||
"unit" => $unit // This is the actual value
|
||||
];
|
||||
}
|
||||
|
||||
return $returnArray;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
class TransactionController extends Controller
|
||||
{
|
||||
// public function tableMe(Request $request){
|
||||
//
|
||||
// $records = Transaction::with(['order','Product','wallet_tr.product'])->whereNull('order_id')->where('customer_id',auth('customer')->id());
|
||||
// TableEngine::create($records, $request->all())
|
||||
// ->initSearch([])
|
||||
// ->select([
|
||||
// '*'
|
||||
// ])->export($records);
|
||||
// return response()->json($records);
|
||||
// }
|
||||
|
||||
public function tableMe(Request $request)
|
||||
{
|
||||
|
||||
$records = Transaction::with(['customer.agent', 'product']);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch([])
|
||||
->select([
|
||||
'*'
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
foreach ($records->cursor() as $item) {
|
||||
|
||||
$item->total_price_round = round($item->total_price, -6);
|
||||
$item->save();
|
||||
}
|
||||
}
|
||||
|
||||
public function tableAgentMe(Request $request)
|
||||
{
|
||||
$records = Transaction::with(['order', 'Product', 'customer', 'wallet_tr.product'])->where('customer_id', auth('customer')->user()->id);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(["note"])
|
||||
->select(['*', Transaction::$SELECT_CAJ])
|
||||
->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function tableAgentMeMinMax(Request $request)
|
||||
{
|
||||
$minMaxValues = Transaction::where('customer_id', auth('customer')->user()->id)->selectRaw('MIN(amount) as min_amount, MAX(amount) as max_amount')->first();
|
||||
return $minMaxValues;
|
||||
}
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
|
||||
if (auth('customer')->user()->type == 2) {
|
||||
return response()->json(true);
|
||||
}
|
||||
$customers = Customer::where('agent_id', auth('customer')->id())->select('id')->get()->pluck('id')->toArray();
|
||||
$records = Transaction::with(['order', 'Product', 'customer', 'wallet_tr.product'])->whereIn('customer_id', $customers);
|
||||
TableEngine::create($records, $request->all())
|
||||
->initSearch(["customer.name"])
|
||||
->select([
|
||||
'*', Transaction::$SELECT_CAJ
|
||||
])->export($records);
|
||||
return response()->json($records);
|
||||
}
|
||||
|
||||
public function tableAgentMeCustomers(Request $request)
|
||||
{
|
||||
$customers = Customer::where('agent_id', auth('customer')->id())->select('id')->get()->pluck('id')->toArray();
|
||||
$minMaxValues = Transaction::whereIn('customer_id', $customers)->selectRaw('MIN(amount) as min_amount, MAX(amount) as max_amount')->first();
|
||||
return $minMaxValues;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Customer;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\DB\Te\TableEngine;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
|
||||
|
||||
class WalletController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
$query_table = Wallet::with('product.file')->where('owner', auth('customer')->id());
|
||||
TableEngine::create($query_table, $data)
|
||||
->initSearch([])
|
||||
->select(['*', Wallet::$SELECT_TYPE_STR])
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
|
||||
public function listWallet()
|
||||
{
|
||||
$Wallets = Wallet::with('product.file')->where('owner', auth('customer')->id())->get()->toArray();
|
||||
|
||||
// متغیر برای جمع اعتبارها
|
||||
$totalCredit = 0;
|
||||
|
||||
foreach ($Wallets as $Wallet) {
|
||||
if (isset($Wallet['product_id'])) {
|
||||
// افزودن اعتبار به جمع کل
|
||||
$totalCredit += $Wallet['credit'];
|
||||
}
|
||||
}
|
||||
|
||||
// افزودن جمع کل به آرایهی کیفپولها
|
||||
$Wallets[] = [
|
||||
'id' => null, // تنظیم کنید اگر مقدار id لازم است
|
||||
'owner' => null, // تنظیم کنید اگر مقدار owner لازم است
|
||||
'credit' => $totalCredit,
|
||||
'deposit_blocked' => null,
|
||||
'withdraw_blocked' => null,
|
||||
'product_id' => 0,
|
||||
'product' => ['title'=>'دارایی طلایی (جمع)'],
|
||||
'type' => null,
|
||||
'created_at' => now(), // میتوانید تاریخ فعلی را استفاده کنید
|
||||
'updated_at' => now()
|
||||
];
|
||||
// بازگشت به صورت پاسخ JSON
|
||||
return response()->json($Wallets);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use http\Env\Response;
|
||||
use Illuminate\Http\Request;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class SuperController extends Controller
|
||||
{
|
||||
public function __construct($model,$with,$select = ['*'],$name_model = null, $query = null, $search = [])
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->with = $with;
|
||||
$this->select = $select;
|
||||
$this->name_model = $name_model;
|
||||
$this->query = $query;
|
||||
$this->search = $search;
|
||||
}
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
if (isset($data['fname'])){
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
|
||||
if (isset($data['user_type']) && !is_int($data['user_type'])){
|
||||
$cnt = Cnt::set('user_type',$data['user_type']);
|
||||
$data['user_type'] = $cnt->id;
|
||||
}
|
||||
|
||||
if (!is_null($this->name_model)){
|
||||
if ($this->name_model == 'user' || $this->name_model == 'customer'){
|
||||
if (!isset($data['password'])){
|
||||
$data['password'] = trim($data['mobile']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$user = $this->model::create($data);
|
||||
if (!is_null($this->name_model) && $this->name_model == 'customer'){
|
||||
new WalletInterface($user->id, $user->type);
|
||||
}
|
||||
return $this->resultCreate($user->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$user = $this->model::with($this->with)
|
||||
->select($this->select)
|
||||
->findOrFail($id);
|
||||
return response()->json($user);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$data = $request->all();
|
||||
if (isset($data['mobile']) && !is_null($data['mobile'])){
|
||||
$check_mobile = $this->model::where('mobile',$data['mobile'])
|
||||
->where('id','<>',$id)
|
||||
->first();
|
||||
if (!is_null($check_mobile)){
|
||||
throw new UnprocessableEntityHttpException('این شماره همراه توسط شخص دیگری در حال استفاده است');
|
||||
}
|
||||
}
|
||||
if (isset($data['fname']) ){
|
||||
$data['name'] = $data['fname'] . ' ' . $data['lname'];
|
||||
}
|
||||
if (isset($data['user_type']) && !is_int($data['user_type'])){
|
||||
$cnt = Cnt::set('user_type',$data['user_type']);
|
||||
$data['user_type'] = $cnt->id;
|
||||
}
|
||||
$this->model::findOrFail($id)->update($data);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->model::findOrFail($id)->delete();
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $id
|
||||
* @return \Illuminate\Http\JsonResponse
|
||||
*/
|
||||
public function active($id){
|
||||
$query = $this->model::findOrFail($id);
|
||||
$query->update([
|
||||
'active'=>!$query->active
|
||||
]);
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
public function table(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
if (isset($data["select"]) && is_null($data["select"])){
|
||||
$data["select"] = [];
|
||||
}
|
||||
if (is_null($this->query)){
|
||||
$query_table = $this->model::with($this->with);
|
||||
}else{
|
||||
$query_table = $this->query;
|
||||
}
|
||||
TableEngine::create($query_table, $data)
|
||||
->initSearch($this->search)
|
||||
->select($this->select)
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\DB\Te\TableEngine;
|
||||
use App\Models\Customer;
|
||||
use App\Models\Package;
|
||||
use App\Models\PackageProduct;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
|
||||
class SuperPackageController extends Controller
|
||||
{
|
||||
public function __construct($with,$select = ['*'], $query = null, $search = [])
|
||||
{
|
||||
$this->with = $with;
|
||||
$this->select = $select;
|
||||
$this->query = $query;
|
||||
$this->search = $search;
|
||||
}
|
||||
public function store(Request $request){
|
||||
$data = $request->all();
|
||||
if(isset($data['is_base']) && $data['is_base']){
|
||||
$exist = Package::where('is_base',true)->first();
|
||||
if(!is_null($exist)){
|
||||
throw new UnprocessableEntityHttpException('لیست قیمت ها قبلا ایجاد شده است');
|
||||
}
|
||||
}
|
||||
$package = Package::create($data);
|
||||
if (isset($data['customers'])){
|
||||
Customer::whereIn('id',$data['customers'])->update(['package_id'=>$package->id]);
|
||||
}
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
foreach ($data['sub_packages'] as $sub){
|
||||
$sub["package_id"] = $package->id;
|
||||
$sub["is_base"] = $data['is_base'];
|
||||
$sub["buy_gram_price"] = $sub['buy_price']/$mesghal_convert;
|
||||
$sub["sell_gram_price"] = $sub['sell_price']/$mesghal_convert;
|
||||
PackageProduct::create($sub);
|
||||
}
|
||||
return $this->resultCreate($package->id);
|
||||
}
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$data = $request->all();
|
||||
Log::info('log update package');
|
||||
Log::info($data);
|
||||
Package::findOrFail($id)->update($data);
|
||||
|
||||
|
||||
$packege_product = PackageProduct::where('package_id',$id)->get();
|
||||
$ids = array_column($packege_product->toArray(),'id');
|
||||
$new = [];
|
||||
foreach ($packege_product->toArray() as $item){
|
||||
if (!array_key_exists($item['product_id'],$new)){
|
||||
$new[$item['product_id']] = $item;
|
||||
}
|
||||
}
|
||||
$mesghal_convert = config('change_mesghal');
|
||||
|
||||
foreach ($data['sub_packages'] as $item){
|
||||
if (!isset($item['id'])){
|
||||
$item["package_id"] = $id;
|
||||
$item["buy_gram_price"] = $item['buy_price']/$mesghal_convert;
|
||||
$item["sell_gram_price"] = $item['sell_price']/$mesghal_convert;
|
||||
PackageProduct::create($item);
|
||||
}
|
||||
else{
|
||||
$key = array_search($item['id'],$ids);
|
||||
if ($item['buy_price'] != $new[$item['product_id']]['buy_price'] || $item['sell_price'] != $new[$item['product_id']]['sell_price']){
|
||||
$item["buy_gram_price"] = $item['buy_price']/$mesghal_convert;
|
||||
$item["sell_gram_price"] = $item['sell_price']/$mesghal_convert;
|
||||
PackageProduct::where('product_id',$item['product_id'])->where('package_id',$id)->update(Arr::except($item, ['id']));
|
||||
}
|
||||
unset($ids[$key]);
|
||||
}
|
||||
}
|
||||
PackageProduct::destroy($ids);
|
||||
return response()->json(true);
|
||||
|
||||
}
|
||||
public function destroy($id)
|
||||
{
|
||||
Package::findOrFail($id)->delete();
|
||||
Customer::where('package_id',$id)->update(['package_id'=>null]);
|
||||
return response()->json(true);
|
||||
}
|
||||
public function table(Request $request)
|
||||
{
|
||||
$data = $request->all();
|
||||
if (isset($data["select"]) && is_null($data["select"])){
|
||||
$data["select"] = [];
|
||||
}
|
||||
if (is_null($this->query)){
|
||||
$query_table = Package::with($this->with)->where('for_agent', false);
|
||||
}else{
|
||||
$query_table = $this->query->where('is_base',false)->where('for_agent', false);
|
||||
}
|
||||
TableEngine::create($query_table, $data)
|
||||
->initSearch($this->search)
|
||||
->select($this->select)
|
||||
->export($query_table);
|
||||
return $query_table;
|
||||
}
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\jsonResponse
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$user = Package::with($this->with)
|
||||
->select($this->select)
|
||||
->findOrFail($id);
|
||||
return response()->json($user);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,341 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\agent;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Cnt;
|
||||
use App\Models\Customer;
|
||||
use App\Models\{Product,CustomersSetting};
|
||||
use App\Models\User;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
class DashboardAgentController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
|
||||
$returnArray = [
|
||||
"categories_buy" => [],
|
||||
"categories_sell" => [],
|
||||
"data_buy" => [],
|
||||
"data_sell" => []
|
||||
];
|
||||
// Get the authenticated agent
|
||||
$agent = auth()->user();
|
||||
|
||||
// Get the total count of customers for the agent
|
||||
$customerCount = Customer::where('agent_id', $agent->id)->count();
|
||||
|
||||
// Get the current date and one week ago date
|
||||
$currentDate = Carbon::now();
|
||||
$oneWeekAgo = $currentDate->copy()->subWeek();
|
||||
|
||||
// Get the count of inactive customers (seen in the last week)
|
||||
$customerCountDeActive = Customer::where('agent_id', $agent->id)
|
||||
->where('last_seen_at', '>', $oneWeekAgo->toDateString())
|
||||
->count();
|
||||
|
||||
// Get the count of customers created more than a week ago
|
||||
$customerCreatedBeforeWeek = Customer::where('agent_id', $agent->id)
|
||||
->where('created_at', '<', $oneWeekAgo->toDateString())
|
||||
->count();
|
||||
|
||||
// Get the total number of transactions for the agent
|
||||
$transactions = Transaction::where('customer_id', $agent->id)->count();
|
||||
|
||||
// Prepare the return array
|
||||
$returnArray['transactions'] = $transactions;
|
||||
$returnArray['customerCount'] = $customerCount;
|
||||
$returnArray['customerCreatedBeforeWeek'] = $customerCreatedBeforeWeek;
|
||||
$returnArray['customerCountDeActive'] = $customerCountDeActive;
|
||||
|
||||
|
||||
|
||||
// Fetch all products with their associated transactions
|
||||
$products = Product::with(['transactionAgentPanel'])->get();
|
||||
|
||||
// Temporary arrays to hold category and amount data for sorting
|
||||
$buyData = [];
|
||||
$sellData = [];
|
||||
|
||||
// Loop through each product
|
||||
// return $products;
|
||||
foreach ($products as $product) {
|
||||
$buyAmount = 0;
|
||||
$sellAmount = 0;
|
||||
|
||||
// Loop through each transaction of the current product
|
||||
foreach ($product->transactionAgentPanel as $transaction) {
|
||||
|
||||
if ($transaction->transaction_type == 1) {
|
||||
// Accumulate the buy amount for the current product
|
||||
$buyAmount += $transaction->amount;
|
||||
} elseif ($transaction->transaction_type == 2) {
|
||||
// Accumulate the sell amount for the current product
|
||||
$sellAmount += $transaction->amount;
|
||||
}
|
||||
}
|
||||
|
||||
// Always include the product title and the corresponding amounts
|
||||
$buyData[] = [
|
||||
"category" => $product->title,
|
||||
"amount" => $buyAmount
|
||||
];
|
||||
|
||||
$sellData[] = [
|
||||
"category" => $product->title,
|
||||
"amount" => -$sellAmount // Flip the buy amount to positive
|
||||
];
|
||||
}
|
||||
|
||||
// Sort buy data by amount in ascending order
|
||||
usort($buyData, function ($a, $b) {
|
||||
return $b['amount'] <=> $a['amount'];
|
||||
});
|
||||
|
||||
// Sort sell data by amount in descending order
|
||||
usort($sellData, function ($a, $b) {
|
||||
return $b['amount'] <=> $a['amount'];
|
||||
});
|
||||
|
||||
// Populate the return array with sorted data
|
||||
foreach ($buyData as $data) {
|
||||
$returnArray["categories_buy"][] = $data["category"];
|
||||
$returnArray["data_buy"][] = $data["amount"];
|
||||
}
|
||||
|
||||
foreach ($sellData as $data) {
|
||||
$returnArray["categories_sell"][] = $data["category"];
|
||||
$returnArray["data_sell"][] = $data["amount"];
|
||||
}
|
||||
|
||||
// Return the result array
|
||||
return $returnArray;
|
||||
}
|
||||
public function customer_setting(Request $request , $agent_id=null)
|
||||
{
|
||||
$data = $request->all();
|
||||
$data['agent_id'] = $agent_id ?? auth()->id();
|
||||
// اگر customer_id آرایه باشد
|
||||
if (isset($data['customer_id'][0]) && is_array($data['customer_id'])) {
|
||||
$results = [];
|
||||
$errors = [];
|
||||
foreach ($data['customer_id'] as $customerId) {
|
||||
|
||||
// بررسی وجود مشتری و ارتباط آن با نماینده
|
||||
$customer = Customer::where('id', $customerId)
|
||||
->where('agent_id', $data['agent_id'])
|
||||
->first();
|
||||
|
||||
if (!$customer) {
|
||||
$errors[] = "مشتری با شناسه {$customerId} یافت نشد یا متعلق به شما نیست.";
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->createOrUpdateSetting(array_merge($data, [
|
||||
'customer_id' => $customerId,
|
||||
'group' => null
|
||||
]));
|
||||
|
||||
$results[] = $result;
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
return response()->json([
|
||||
'message' => 'برخی تنظیمات اعمال نشدند.',
|
||||
'errors' => $errors,
|
||||
'data' => $results
|
||||
], 207); // کد وضعیت 207 برای پاسخهای چند وضعیتی
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'تنظیمات برای تمام مشتریان با موفقیت اعمال شد.',
|
||||
'data' => $results
|
||||
]);
|
||||
}
|
||||
|
||||
// حالت عادی (customer_id تک مقداری یا group)
|
||||
if (!empty($data['customer_id'])) {
|
||||
// بررسی وجود مشتری و ارتباط آن با نماینده
|
||||
$customer = Customer::where('id', $data['customer_id'])
|
||||
->where('agent_id', $data['agent_id'])
|
||||
->first();
|
||||
|
||||
if (!$customer) {
|
||||
return response()->json([
|
||||
'message' => 'مشتری یافت نشد یا متعلق به شخص دیگری میباشد.',
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
$result = $this->createOrUpdateSetting($data);
|
||||
|
||||
if (isset($result['error'])) {
|
||||
return response()->json([
|
||||
'message' => $result['message']
|
||||
], 422);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => $result['message']??0,
|
||||
'data' => $result['data']??null,
|
||||
'd' => $result??null,
|
||||
]);
|
||||
}
|
||||
public function creat_customer_setting_id(Request $request )
|
||||
{
|
||||
$data = $request->all();
|
||||
$data['agent_id'] = auth()->id();
|
||||
// اگر customer_id آرایه باشد
|
||||
if (isset($data['customer_id'][0]) && is_array($data['customer_id'])) {
|
||||
$results = [];
|
||||
$errors = [];
|
||||
foreach ($data['customer_id'] as $customerId) {
|
||||
|
||||
// بررسی وجود مشتری و ارتباط آن با نماینده
|
||||
$customer = Customer::where('id', $customerId)
|
||||
->where('agent_id', $data['agent_id'])
|
||||
->first();
|
||||
|
||||
if (!$customer) {
|
||||
$errors[] = "مشتری با شناسه {$customerId} یافت نشد یا متعلق به شما نیست.";
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->createOrUpdateSetting(array_merge($data, [
|
||||
'customer_id' => $customerId,
|
||||
'group' => null
|
||||
]));
|
||||
|
||||
$results[] = $result;
|
||||
}
|
||||
|
||||
if (!empty($errors)) {
|
||||
return response()->json([
|
||||
'message' => 'برخی تنظیمات اعمال نشدند.',
|
||||
'errors' => $errors,
|
||||
'data' => $results
|
||||
], 207); // کد وضعیت 207 برای پاسخهای چند وضعیتی
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => 'تنظیمات برای تمام مشتریان با موفقیت اعمال شد.',
|
||||
'data' => $results
|
||||
]);
|
||||
}
|
||||
|
||||
// حالت عادی (customer_id تک مقداری یا group)
|
||||
if (!empty($data['customer_id'])) {
|
||||
// بررسی وجود مشتری و ارتباط آن با نماینده
|
||||
$customer = Customer::where('id', $data['customer_id'])
|
||||
->where('agent_id', $data['agent_id'])
|
||||
->first();
|
||||
|
||||
if (!$customer) {
|
||||
return response()->json([
|
||||
'message' => 'مشتری یافت نشد یا متعلق به شخص دیگری میباشد.',
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
$result = $this->createOrUpdateSetting($data);
|
||||
|
||||
if (isset($result['error'])) {
|
||||
return response()->json([
|
||||
'message' => $result['message']
|
||||
], 422);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'message' => $result['message']??0,
|
||||
'data' => $result['data']??null,
|
||||
'd' => $result??null,
|
||||
]);
|
||||
}
|
||||
|
||||
private function createOrUpdateSetting($data)
|
||||
{
|
||||
$query = CustomersSetting::where('agent_id', $data['agent_id']);
|
||||
|
||||
if (!empty($data['customer_id'])) {
|
||||
// برای حالت آرایه و تکی هر دو کار میکند
|
||||
$customerId = is_array($data['customer_id']) ? $data['customer_id'][0] : $data['customer_id'];
|
||||
$query->where('customer_id', $customerId);
|
||||
} else {
|
||||
$query->whereNull('customer_id');
|
||||
}
|
||||
|
||||
if (!empty($data['group'])) {
|
||||
$query->where('group', $data['group']);
|
||||
} else {
|
||||
$query->whereNull('group');
|
||||
}
|
||||
|
||||
if (empty($data['product_id'])) {
|
||||
$query->whereNull('product_id');
|
||||
} else {
|
||||
$query->where('product_id', $data['product_id']);
|
||||
}
|
||||
|
||||
$existing = $query->first();
|
||||
|
||||
if ($existing) {
|
||||
$existing->update([
|
||||
'title' => $data['title'] ?? null,
|
||||
'profit_buy' => $data['profit_buy'] ?? 0,
|
||||
'profit_sell' => $data['profit_sell'] ?? 0,
|
||||
'credit_buy' => $data['credit_buy'] ?? 0,
|
||||
'credit_sell' => $data['credit_sell'] ?? 0,
|
||||
'auto_buy' => $data['auto_buy'] ?? 0,
|
||||
'auto_sell' => $data['auto_sell'] ?? 0,
|
||||
]);
|
||||
|
||||
return [
|
||||
'message' => 'رکورد موجود بهروزرسانی شد.',
|
||||
'data' => $existing
|
||||
];
|
||||
}
|
||||
|
||||
// ایجاد رکورد جدید
|
||||
$createData = [
|
||||
'title' => $data['title'] ?? null,
|
||||
'agent_id' => $data['agent_id'],
|
||||
'product_id' => $data['product_id'] ?? null,
|
||||
'group' => $data['group'] ?? null,
|
||||
'profit_buy' => $data['profit_buy'] ?? 0,
|
||||
'profit_sell' => $data['profit_sell'] ?? 0,
|
||||
'credit_buy' => $data['credit_buy'] ?? 0,
|
||||
'credit_sell' => $data['credit_sell'] ?? 0,
|
||||
'auto_buy' => $data['auto_buy'] ?? 0,
|
||||
'auto_sell' => $data['auto_sell'] ?? 0,
|
||||
];
|
||||
|
||||
// اضافه کردن customer_id به صورت صحیح برای هر دو حالت آرایه و تکی
|
||||
if (!empty($data['customer_id'])) {
|
||||
$createData['customer_id'] = is_array($data['customer_id']) ? $data['customer_id'][0] : $data['customer_id'];
|
||||
}
|
||||
|
||||
$created = CustomersSetting::create($createData);
|
||||
|
||||
return [
|
||||
'message' => 'تنظیمات با موفقیت ایجاد شد.',
|
||||
'data' => $created
|
||||
];
|
||||
} public function get_customer_setting(Request $request)
|
||||
{
|
||||
return CustomersSetting::where('agent_id',auth()->id())->get();
|
||||
}
|
||||
public function agent_customers(Request $request)
|
||||
{
|
||||
return Customer::where('agent_id',auth()->id())->get();
|
||||
}
|
||||
public function get_customer_setting_id($id)
|
||||
{
|
||||
return CustomersSetting::where('id', $id)
|
||||
->where('agent_id', auth()->id())
|
||||
->firstOrFail();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\pay;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\BankTransaction;
|
||||
use App\Models\FinancialDoc;
|
||||
use App\Models\PayPing;
|
||||
use Rooyesh\Wallet\interfaces\WalletInterface;
|
||||
use DateTime;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class BankTransactionController extends Controller
|
||||
//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
|
||||
{
|
||||
|
||||
public function sse()
|
||||
{
|
||||
$response = new StreamedResponse(function () {
|
||||
while (true) {
|
||||
// ارسال داده به صورت JSON
|
||||
echo "data: " . json_encode(['message' => 'Hello, world!']) . "\n\n";
|
||||
|
||||
// اطمینان از ارسال دادهها به مرورگر
|
||||
ob_flush();
|
||||
flush();
|
||||
|
||||
// توقف به مدت 1 ثانیه
|
||||
sleep(1);
|
||||
}
|
||||
});
|
||||
|
||||
$response->headers->set('Content-Type', 'text/event-stream');
|
||||
$response->headers->set('Cache-Control', 'no-cache');
|
||||
$response->headers->set('Connection', 'keep-alive');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function showTransactionReport($item)
|
||||
{
|
||||
|
||||
if ($Customer = Customer::where("item",$item)->first()){
|
||||
|
||||
$url = "https://api.payping.ir/v1/report/TransactionReport";
|
||||
$token = "_Xc__FpazjtKbT2PBDZr28xHkysKn3AsIeq6GVPYorg";
|
||||
$body = [
|
||||
'offset' => '0',
|
||||
'limit' => '100000'
|
||||
];
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Content-Type' => 'application/json',
|
||||
])->post($url, $body);
|
||||
|
||||
|
||||
$data = json_decode($response, true);
|
||||
$filtered_data = [];
|
||||
|
||||
|
||||
foreach ($data as $element) {
|
||||
// Check if the current element's clientRefId matches the filter
|
||||
if ($element['clientRefId'] === $item) {
|
||||
// Add the element to the filtered data array
|
||||
$filtered_data[] = $element;
|
||||
}}
|
||||
|
||||
foreach (array_reverse($filtered_data) as $dataLoop){
|
||||
|
||||
$moreInfos = $this->moreInfoByCode($dataLoop["code"]);
|
||||
|
||||
if (bankTransaction::where("invoiceNo",$dataLoop["invoiceNo"])->first()){
|
||||
}else{
|
||||
$SavedBankTransaction = new BankTransaction();
|
||||
$SavedBankTransaction->customer_id = 1;
|
||||
$SavedBankTransaction->amount = $dataLoop["amount"]."0";
|
||||
$SavedBankTransaction->pay_date = DateTime::createFromFormat('Y-m-d\TH:i:s.u', $dataLoop["payDate"])->format('Y-m-d H:i:s');
|
||||
$SavedBankTransaction->name = $dataLoop["name"];
|
||||
$SavedBankTransaction->payer_identity = $dataLoop["payerIdentity"];
|
||||
$SavedBankTransaction->code =$dataLoop["code"];
|
||||
$SavedBankTransaction->clientId = $dataLoop["clientId"];
|
||||
$SavedBankTransaction->clientRefId = $dataLoop["clientRefId"];
|
||||
$SavedBankTransaction->invoiceNo = $dataLoop["invoiceNo"];
|
||||
$SavedBankTransaction->save();
|
||||
$data = [
|
||||
'amount' => $moreInfos["amount"]."0",
|
||||
'date_at' =>$moreInfos["payDate"],
|
||||
'track_number' => $dataLoop['code'],
|
||||
'send_account_number' => $moreInfos["payerIdentity"],
|
||||
'send_bank' => 'pay ping',
|
||||
'send_name' => $moreInfos["name"],
|
||||
'receive_account_number' => $Customer->card,
|
||||
'receive_bank' => 'pay ping',
|
||||
'receive_name' => $Customer->name,
|
||||
'bank_transaction_id' => $SavedBankTransaction->id,
|
||||
'customer_id' => $Customer->id,
|
||||
'sts' => 1,
|
||||
'type' => 1
|
||||
];
|
||||
$fin_doc = FinancialDoc::create($data);
|
||||
$deposit = true;
|
||||
$note = 'سند ورودی تراکنش';
|
||||
$cu = $Customer;
|
||||
$cash_interface = new WalletInterface($cu->id, $cu->type);
|
||||
$this->createTransactionFinDoc($cash_interface,$fin_doc->amount,$deposit,$fin_doc->id,$cu->type,$note);
|
||||
}
|
||||
|
||||
}
|
||||
if (isset($SavedBankTransaction)){
|
||||
return view("showTransactionReport",compact("Customer","SavedBankTransaction"));
|
||||
}else{
|
||||
return "تراکنش جدیدی ثیت نشده.";
|
||||
}
|
||||
|
||||
}else{
|
||||
return "ایتم شما با وبسایت لیمان ساخته نشده با پشتیبانی تماس بگیرید.";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function moreInfoByCode($code)
|
||||
{
|
||||
$url = "https://api.payping.ir/v1/report/$code";
|
||||
$token = "_Xc__FpazjtKbT2PBDZr28xHkysKn3AsIeq6GVPYorg";
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Content-Type' => 'application/json',
|
||||
])->get($url);
|
||||
|
||||
if (isset($error_msg)) {
|
||||
return response()->json(['error' => $error_msg], 500);
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\pay;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Customer;
|
||||
use App\Models\User;
|
||||
use App\Models\BankTransaction;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class PayPingController extends Controller
|
||||
{
|
||||
public function deposit_id(Request $request)
|
||||
{
|
||||
$Customer = Customer::find($request->id);
|
||||
if ($Customer->deposit_id) {
|
||||
return $Customer->deposit_id;
|
||||
} else {
|
||||
$Customer->card = $request->card;
|
||||
$Customer->shaba = $request->shaba;
|
||||
$Customer->fname = $request->fname;
|
||||
$Customer->lname = $request->lname;
|
||||
$Customer->birth_date = $request->birth_date;
|
||||
$Customer->n_code = $request->n_code;
|
||||
$Customer->mobile = $request->mobile;
|
||||
$Customer->save();
|
||||
|
||||
$productBody = [
|
||||
'isLegal' => false,
|
||||
'description' => 'قدرت گرفته توسط پلتفرم هوشمند لیمان گلد.',
|
||||
'sourceIbans' => [
|
||||
"IR" . $Customer->shaba
|
||||
],
|
||||
'sourceCardNumbers' => [
|
||||
$Customer->card
|
||||
],
|
||||
'firstName' => $Customer->fname,
|
||||
'lastName' => $Customer->lname,
|
||||
'birthDate' => substr($Customer->birth_date, 0, 10),
|
||||
'nationalCode' => $Customer->n_code,
|
||||
'phoneNumber' => $Customer->mobile,
|
||||
];
|
||||
// return $productBody;
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . "9u-exPK-6IeUQVKmLD9LvIE1Qmhnw_RV-MPZvg1r5zQ",
|
||||
'Content-Type' => 'application/json',
|
||||
])->post("https://api.payping.ir/v1/cash-out/deposit", $productBody);
|
||||
if ($response->failed()) {
|
||||
|
||||
$responseBody = json_decode($response->body(), true);
|
||||
$errorMessage = isset($responseBody['message']) ? $responseBody['message'] : 'An error occurred';
|
||||
return response()->json(['message' => $errorMessage], 400);
|
||||
} else {
|
||||
|
||||
if (isset($response['successResult']['depositId'])) {
|
||||
$Customer->deposit_id = $response['successResult']['depositId'];
|
||||
$Customer->save();
|
||||
return $Customer->deposit_id;
|
||||
} else {
|
||||
return "شناسه شما در پی پینگ قابل نمایش میباشد";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $Customer->deposit_id;
|
||||
}
|
||||
|
||||
public function store(Request $request, $id)
|
||||
{
|
||||
function sendRequest($url, $token, $body)
|
||||
{
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Content-Type' => 'application/json',
|
||||
])->post($url, $body);
|
||||
|
||||
if ($response->failed()) {
|
||||
return ['error' => 'Failed to connect to API', 'httpCode' => $response->status(), 'response' => $response->body()];
|
||||
}
|
||||
|
||||
return $response->json();
|
||||
}
|
||||
|
||||
$apiToken = "_Xc__FpazjtKbT2PBDZr28xHkysKn3AsIeq6GVPYorg";
|
||||
|
||||
$Customer = Customer::find($id);
|
||||
if (!$Customer) {
|
||||
return response()->json(['error' => 'Customer not found'], 404);
|
||||
}
|
||||
if ($Customer->item) {
|
||||
return response()->json(['error' => 'Item exist'], 400);
|
||||
}
|
||||
// First API call to create a product
|
||||
$productBody = [
|
||||
'title' => $Customer->name,
|
||||
'description' => 'ساخته شده توسط وبسایت لیمان گلد',
|
||||
'amount' => '0',
|
||||
'defineAmountByUser' => 'true',
|
||||
'quantity' => '1',
|
||||
'haveTax' => 'true',
|
||||
'unlimited' => 'true',
|
||||
'imageLink' => 'true',
|
||||
];
|
||||
|
||||
$productResponse = sendRequest("https://api.payping.ir/v1/product", $apiToken, $productBody);
|
||||
|
||||
if (isset($productResponse['error'])) {
|
||||
error_log("Error: " . $productResponse['response']);
|
||||
return response()->json(['error' => 'Failed to create product'], $productResponse['httpCode']);
|
||||
}
|
||||
|
||||
if (!isset($productResponse["code"])) {
|
||||
error_log("Error: 'code' key is not set in the product response.");
|
||||
return response()->json(['error' => 'Failed to retrieve product code from PayPing API'], 500);
|
||||
}
|
||||
|
||||
// Second API call to create a permalink
|
||||
$permalinkBody = [
|
||||
'code' => $productResponse["code"],
|
||||
'productCode' => null,
|
||||
'redirectPage' => "https://limangold.ir/kernel/seetransaction/" . $productResponse["code"],
|
||||
'getAddress' => false,
|
||||
'mailerLiteListId' => 'string',
|
||||
'smsText' => 'string',
|
||||
'customDescriptionText' => 'string',
|
||||
'emailOption' => 0,
|
||||
'phoneOption' => 2,
|
||||
'nameOption' => 2,
|
||||
'customDesOption' => 0,
|
||||
'clientId' => 'string',
|
||||
'clientRefId' => 'string',
|
||||
'permanentType' => 0,
|
||||
'isMultiple' => true,
|
||||
];
|
||||
|
||||
$permalinkResponse = sendRequest("https://api.payping.ir/v1/permalink", $apiToken, $permalinkBody);
|
||||
|
||||
if (isset($permalinkResponse['error'])) {
|
||||
error_log("Error: " . $permalinkResponse['response']);
|
||||
return response()->json(['error' => 'Failed to create permalink'], $permalinkResponse['httpCode']);
|
||||
}
|
||||
|
||||
if (!isset($permalinkResponse["code"])) {
|
||||
error_log("Error: 'code' key is not set in the permalink response.");
|
||||
return response()->json(['error' => 'Failed to retrieve permalink code from PayPing API'], 500);
|
||||
}
|
||||
|
||||
$Customer->item = $permalinkResponse["code"];
|
||||
$Customer->save();
|
||||
|
||||
return response()->json(['code' => $permalinkResponse["code"]]);
|
||||
|
||||
}
|
||||
|
||||
public function TransactionReport(Request $request)
|
||||
{
|
||||
$token = "_Xc__FpazjtKbT2PBDZr28xHkysKn3AsIeq6GVPYorg";
|
||||
$url = "https://api.payping.ir/v1/report/TransactionReport";
|
||||
|
||||
$body = [
|
||||
'offset' => '0',
|
||||
'limit' => '100000'
|
||||
];
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => 'Bearer ' . $token,
|
||||
'Content-Type' => 'application/json',
|
||||
])->post($url, $body);
|
||||
|
||||
|
||||
$data = json_decode($response, true);
|
||||
$filtered_data = [];
|
||||
// return $data;
|
||||
foreach ($data as $element) {
|
||||
// Check if the current element's clientRefId matches the filter
|
||||
if ($element['clientRefId'] === $request->filtered_data) {
|
||||
// Add the element to the filtered data array
|
||||
$filtered_data[] = $element;
|
||||
}
|
||||
}
|
||||
if ($request->metode == "all") {
|
||||
$cash = 0;
|
||||
foreach ($filtered_data as $element) {
|
||||
$cash += $element['amount']; // Access amount using array index
|
||||
}
|
||||
return $cash;
|
||||
} elseif ($request->metode == "detail") {
|
||||
return $filtered_data;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use App\Http\Middleware\ValidationMiddleware;
|
||||
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,
|
||||
\Fruitcake\Cors\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\Session\Middleware\AuthenticateSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
'throttle:api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware.
|
||||
*
|
||||
* These middleware may be assigned to groups or used individually.
|
||||
*
|
||||
* @var array<string, class-string|string>
|
||||
*/
|
||||
protected $routeMiddleware = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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' => \Illuminate\Routing\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'validation'=>ValidationMiddleware::class,
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return string|null
|
||||
*/
|
||||
protected function redirectTo($request)
|
||||
{
|
||||
if (auth()->check()){
|
||||
if (! $request->expectsJson()) {
|
||||
return route('login');
|
||||
}
|
||||
}else{
|
||||
abort(401,'no authorised');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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 = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -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 = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
|
||||
* @param string|null ...$guards
|
||||
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, ...$guards)
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -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',
|
||||
];
|
||||
}
|
||||
|
|
@ -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()
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
|
||||
class ValidationMiddleware
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
|
||||
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
|
||||
*/
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
if($request->acceptsJson()){
|
||||
$method = $request->getMethod();
|
||||
$path =$request->path();
|
||||
if(preg_match('/[0-9]+$/',$request->path(),$match)) {
|
||||
$id = $match[0];
|
||||
$path = preg_replace('/[0-9]+$/', '{id}', $request->path());
|
||||
}
|
||||
$format = 'validation.'.$path.'@'.strtolower($method);
|
||||
if (config($format)) {
|
||||
if ($path == 'customer/me/update'){
|
||||
$replace = preg_replace('/me_id/', auth('customer')->id(), config($format));
|
||||
$validator = Validator::make($request->all(), $replace);
|
||||
}
|
||||
if(in_array('mobile',array_keys(config($format)))){
|
||||
if(preg_match('/update_id/',config($format)['mobile'],$match)) {
|
||||
$replace = preg_replace('/update_id/', $id, config($format));
|
||||
$validator = Validator::make($request->all(), $replace);
|
||||
}else{
|
||||
$validator = Validator::make($request->all(), config($format));
|
||||
}
|
||||
}
|
||||
// elseif(isset($match[0])){
|
||||
// $replace = preg_replace('/update_#/', $match[0], config($format));
|
||||
// $validator = Validator::make($request->all(), $replace);
|
||||
// }
|
||||
else{
|
||||
$validator = Validator::make($request->all(), config($format));
|
||||
}
|
||||
if ($validator->fails()) {
|
||||
return response()->json($validator->errors(),422);
|
||||
}
|
||||
}
|
||||
return $next($request);
|
||||
}
|
||||
throw new BadRequestHttpException();
|
||||
}
|
||||
}
|
||||
|
|
@ -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 = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Order;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldBeUnique;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
class CancelJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public $order_id;
|
||||
|
||||
/**
|
||||
* Create a new job instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($order_id)
|
||||
{
|
||||
$this->order_id = $order_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the job.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$order = Order::findOrFail($this->order_id);
|
||||
|
||||
|
||||
if ($order->sts == 1) {
|
||||
$order->sts = 6;
|
||||
$order->save();
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Order;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use App\Models\Cnt;
|
||||
|
||||
//fixed
|
||||
|
||||
class ValidateOrder implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public $orderId;
|
||||
|
||||
public function __construct($orderId)
|
||||
{
|
||||
$this->orderId = $orderId;
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$order = Order::findOrFail($this->orderId);
|
||||
$documents = Http::withToken(env('TOKEN_750_KALHOR'))
|
||||
->get('https://b750-server.liara.run/api/v1/user/all-documents')
|
||||
->json();
|
||||
|
||||
foreach ($documents as $doc) {
|
||||
if ($doc['id'] == $order->kalhor_id) {
|
||||
$order->update(['kalhor_sts' => $doc['status']]);
|
||||
|
||||
if ($doc['status'] === 'cancel') {
|
||||
if ($cntsForSms = Cnt::where('key', 'numberToSendMassageInOrder')->where('title_fa', 'true')->get()) {
|
||||
foreach ($cntsForSms as $cntForSms) {
|
||||
Http::get('http://www.0098sms.com/sendsmslink.aspx', [
|
||||
'FROM' => env('SENDER_0098'),
|
||||
'TO' => $cntForSms,
|
||||
'TEXT' => "وضعیت سفارش {$order->kalhor_id} در کلهور ناموفق بود لطفا پیگیری کنید",
|
||||
'USERNAME' => env('USER_0098'),
|
||||
'PASSWORD' => env('PASS_0098'),
|
||||
'DOMAIN' => '0098',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class BankTransaction extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Cnt extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
protected $table = 'const';
|
||||
protected $fillable = [
|
||||
'key',
|
||||
'title_fa',
|
||||
'value',
|
||||
];
|
||||
public function getValueAttribute()
|
||||
{
|
||||
$value = $this->attributes['value'] ?? null;
|
||||
|
||||
if (empty($value)) {
|
||||
return $this->attributes['title_fa'] ?? null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,163 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Tymon\JWTAuth\Contracts\JWTSubject;
|
||||
use App\Http\Controllers\Customer\ProductController as CustomerProductController;
|
||||
|
||||
|
||||
class Customer extends Authenticatable implements JWTSubject
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $appends = ['customer_type'];
|
||||
|
||||
protected $fillable = [
|
||||
'fname',
|
||||
'lname',
|
||||
'name',
|
||||
'active',
|
||||
'mobile',
|
||||
'avatar_id',
|
||||
'last_seen_at',
|
||||
'default_address_id',
|
||||
'sts',
|
||||
'total_transaction',
|
||||
'token_sms',
|
||||
'password',
|
||||
'orders_count',
|
||||
'birth_date',
|
||||
'shop_name',
|
||||
'phone_number',
|
||||
'code',
|
||||
'city',
|
||||
'province',
|
||||
'n_code',
|
||||
'is_archive',
|
||||
'gram',
|
||||
'trade_active',//آیا امکان معامله دارد؟
|
||||
'type',
|
||||
'agent_id',
|
||||
'package_id',
|
||||
'tahesab_id',
|
||||
'customer_type',
|
||||
'email',
|
||||
'group',
|
||||
'gender',
|
||||
];
|
||||
protected $hidden = [
|
||||
'token_sms',
|
||||
'password',
|
||||
];
|
||||
static $TYPES = [
|
||||
3=>'مجموعه',
|
||||
1=>'نماینده',
|
||||
2=>'کاربر'
|
||||
];
|
||||
|
||||
// static $GENDERS = [
|
||||
// 1=>'آقا',
|
||||
// 2=>'خانوم',
|
||||
// 3=>'مجموعه'
|
||||
// ];
|
||||
|
||||
protected $casts = [
|
||||
"active" => "boolean",
|
||||
"is_archive" => "boolean",
|
||||
];
|
||||
// public function getCustomerDataAttribute(){
|
||||
// $products = json_decode(app(CustomerProductController::class)->list_product()->getContent(),true);
|
||||
// return $products;
|
||||
// }
|
||||
public function getCustomerTypeAttribute()
|
||||
{
|
||||
$CType = 'کاربر';
|
||||
if (isset($this->attributes['agent_id'])){
|
||||
if (isset($this->attributes['agent_id']) && $this->attributes['agent_id']) {
|
||||
$user = $this->find($this->attributes['agent_id']);
|
||||
if ($user) {
|
||||
$CType = ' نماینده ' ;
|
||||
if ($user->agent_id) {
|
||||
$Agent = $this->find($user->agent_id);
|
||||
$CType =' مشتری '. $Agent->name;
|
||||
}
|
||||
}
|
||||
}
|
||||
// if ($CType != $this->attributes['customer_type']) {
|
||||
// $this->attributes['customer_type'] = $CType;
|
||||
// $this->save();
|
||||
// }
|
||||
}
|
||||
|
||||
return $CType;
|
||||
}
|
||||
// public function getNameAttribute()
|
||||
// {
|
||||
// $CType = $this->attributes['gender'] ." ".$this->attributes['name'];
|
||||
//
|
||||
//
|
||||
// return $CType;
|
||||
// }
|
||||
public function setNameAttribute($name = null){
|
||||
$this->attributes['name'] = $name??[$this->attributes['fname'] , $this->attributes['lname']].join(' ');
|
||||
}
|
||||
|
||||
public function package()
|
||||
{
|
||||
return $this->belongsTo(Package::class);
|
||||
}
|
||||
public function CustomersSetting()
|
||||
{
|
||||
return $this->belongsTo(CustomersSetting::class,"id","agent_id");
|
||||
}
|
||||
|
||||
public function agent()
|
||||
{
|
||||
return $this->belongsTo(Customer::class,'agent_id');
|
||||
}
|
||||
// public function WalletWallet()
|
||||
// {
|
||||
// return $this->hasMany('Rooyesh\Wallet\models\Wallet','owner')->select(['id','name']);
|
||||
// }
|
||||
public function Wallet()
|
||||
{
|
||||
return $this->hasMany('Rooyesh\Wallet\models\Wallet','owner');
|
||||
}
|
||||
public function customer_settings()
|
||||
{
|
||||
return $this->hasMany(CustomersSetting::class,'agent_id');
|
||||
}
|
||||
public function transactin()
|
||||
{
|
||||
return $this->hasMany(Transaction::class,'customer_id');
|
||||
}
|
||||
public function avatar()
|
||||
{
|
||||
return $this->belongsTo(File::class,'avatar_id');
|
||||
}
|
||||
|
||||
// hash password
|
||||
public function setPasswordAttribute($value){
|
||||
$this->attributes['password'] = Hash::make($value);
|
||||
}
|
||||
|
||||
public function getJWTIdentifier()
|
||||
{
|
||||
return $this->getKey();
|
||||
}
|
||||
|
||||
public function getJWTCustomClaims()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
public function Transaction(){
|
||||
return $this->hasMany(Transaction::class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class CustomerCredit extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $fillable = [
|
||||
"product_id",
|
||||
"buy_credit",
|
||||
"sell_credit",
|
||||
"customer_id",
|
||||
"blocked_buy_credit",
|
||||
"blocked_sell_credit",
|
||||
"remain_buy_credit",
|
||||
"remain_sell_credit",
|
||||
];
|
||||
public function product(){
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class CustomersSetting extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $appends = ['title',];
|
||||
|
||||
protected $fillable = [
|
||||
"agent_id",
|
||||
"customer_id",
|
||||
"group",
|
||||
"product_id",
|
||||
"profit_buy",
|
||||
"profit_sell",
|
||||
"credit_buy",
|
||||
"credit_sell",
|
||||
"auto_buy",
|
||||
"auto_sell",
|
||||
"title",
|
||||
];
|
||||
protected $casts = [
|
||||
"customer_id" => "integer", // or "string" depending on your needs
|
||||
"group" => "string", // or "integer" if it's a numeric group ID
|
||||
"product_id" => "integer", // or "string"
|
||||
"profit_buy" => "float", // or "decimal:2" for monetary values
|
||||
"profit_sell" => "float", // or "decimal:2"
|
||||
"credit_buy" => "integer", // assuming these are true/false flags
|
||||
"credit_sell" => "integer",
|
||||
"auto_buy" => "boolean",
|
||||
"auto_sell" => "boolean",
|
||||
];
|
||||
public function customer()
|
||||
{
|
||||
return $this->hasOne(Customer::class,'id','customer_id');
|
||||
} public function product()
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
public function agent()
|
||||
{
|
||||
return $this->hasOne(Customer::class,'id','agent_id');
|
||||
}
|
||||
public function getTitleAttribute()
|
||||
{
|
||||
if (array_key_exists('title', $this->attributes) && !is_null($this->attributes['title'])) {
|
||||
return $this->attributes['title'];
|
||||
}
|
||||
|
||||
$t = "نامشخص";
|
||||
|
||||
if (is_null($this->customer_id) && is_null($this->group) && is_null($this->product_id)) {
|
||||
$t = "تنظیمات اصلی برای همه کاربران";
|
||||
}
|
||||
|
||||
if (!is_null($this->group)) {
|
||||
$t = "تنظیمات برای گروه " . $this->group;
|
||||
}
|
||||
|
||||
if (!is_null($this->customer_id)) {
|
||||
$t = "تنظیمات برای " . ($this->customer->name ?? 'نامشخص');
|
||||
}
|
||||
|
||||
return $t;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class File extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use Selector;
|
||||
protected $fillable = [
|
||||
'original_name',
|
||||
'title',
|
||||
'ext',
|
||||
'src',
|
||||
'size',
|
||||
'user_id',
|
||||
'type',
|
||||
'has_thumb',
|
||||
];
|
||||
protected $casts = [
|
||||
"has_thumb"=>"boolean"
|
||||
];
|
||||
public function getSrcAttribute(){
|
||||
return url($this->attributes['src']);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
class FinDocTalla extends Model
|
||||
{
|
||||
use HasFactory,SoftDeletes,Selector;
|
||||
protected $fillable =[
|
||||
'customer_id',//طرف حساب
|
||||
'user_id',//کاربر ایجاد کننده
|
||||
'weight',//مقدار
|
||||
'date_at',//تاریخ
|
||||
'ayar',
|
||||
'ang',//انگ
|
||||
'description',
|
||||
'lab',
|
||||
// 'type',
|
||||
'type_fin',//آبشده,متفرقه,شرطی,طلب ما
|
||||
'sts',
|
||||
'product_id',
|
||||
'finance_code',
|
||||
];
|
||||
static $TYPES = [
|
||||
1=>'واریز',
|
||||
2=>'برداشت'
|
||||
];
|
||||
static $STS = [
|
||||
1=>'در انتظار تایید',
|
||||
2=>'تایید شده'
|
||||
];
|
||||
public function customer()
|
||||
{
|
||||
return $this->belongsTo(Customer::class)->select(['id','name']);
|
||||
}
|
||||
public function product()
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
public function transaction()
|
||||
{
|
||||
return $this->hasOne(Transaction::class,'fin_doc_talla_id');
|
||||
}
|
||||
public function admin()
|
||||
{
|
||||
return $this->belongsTo(User::class,'admin_id','id')->select(['id','name']);
|
||||
}
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
class FinancialDoc extends Model
|
||||
{
|
||||
use HasFactory,SoftDeletes,Selector;
|
||||
protected $fillable =[
|
||||
'customer_id',//طرف حساب
|
||||
'amount',//مقدار
|
||||
'date_at',//تاریخ
|
||||
'track_number',//شماره پیگیری
|
||||
'send_account_number',//شماره حساب واریز کننده
|
||||
'send_bank',//بانک واریز کننده
|
||||
'send_name',//نام واریز کننده
|
||||
'receive_account_number',//شماره حساب دریافت کننده
|
||||
'receive_bank',//بانک دریافت کننده
|
||||
'receive_bank_card',//َشماره کارت دریافت کننده
|
||||
'receive_name',//نام دریافت کننده
|
||||
'description',
|
||||
// 'type',
|
||||
'finance_code',
|
||||
'sts',
|
||||
'bank_transaction_id'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'paypingdata'=>'json',
|
||||
];
|
||||
static $TYPES = [
|
||||
1=>'واریز',
|
||||
2=>'برداشت'
|
||||
];
|
||||
static $STS = [
|
||||
1=>'در انتظار تایید',
|
||||
2=>'تایید شده',
|
||||
3=>'در انتظار واریز',
|
||||
4=>'در حال ارسال',
|
||||
];
|
||||
public function customer()
|
||||
{
|
||||
return $this->belongsTo(Customer::class)->select(['id','name']);
|
||||
}
|
||||
public function transaction()
|
||||
{
|
||||
return $this->hasOne(Transaction::class,'fin_doc_id');
|
||||
}
|
||||
public function admin()
|
||||
{
|
||||
return $this->belongsTo(User::class,'admin_id','id')->select(['id','name']);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
|
||||
class Havaleh extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
|
||||
protected $fillable = [
|
||||
"creator_customer_id", //کاربر ثبت کننده
|
||||
"getter_customer_id", //کاربر دریافت کننده
|
||||
"getter_customer_phone", //کاربر دریافت کننده
|
||||
"getter_customer_name", //کاربر دریافت کننده
|
||||
"product_id", //محصول
|
||||
"amount",//میزان
|
||||
"sts", // وضعیت حواله
|
||||
"description", //جزئیات
|
||||
"pv_description", //توضیحات خصوصی
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'description' => 'json',
|
||||
];
|
||||
|
||||
static $STS = [
|
||||
0 => 'باز',
|
||||
1 => 'تایید شده',
|
||||
2 => 'رد شده'
|
||||
];
|
||||
|
||||
public function creator_customer(){
|
||||
return $this->belongsTo(Customer::class);
|
||||
}
|
||||
|
||||
public function getter_customer(){
|
||||
return $this->belongsTo(Customer::class);
|
||||
}
|
||||
|
||||
public function product(){
|
||||
return $this->belongsTo(Product::class,'product_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Message extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
protected $table = 'messages';
|
||||
protected $fillable = [
|
||||
'sms',
|
||||
'receiver',
|
||||
'platforms',
|
||||
'price',
|
||||
|
||||
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class MessageNotification extends Model
|
||||
{
|
||||
use HasFactory, Selector;
|
||||
|
||||
protected $table = 'message_notification';
|
||||
|
||||
protected $fillable = [
|
||||
'title',
|
||||
'text',
|
||||
'type',
|
||||
'creator_id',
|
||||
'is_admin',
|
||||
'is_active',
|
||||
'start_at',
|
||||
'end_at'
|
||||
];
|
||||
|
||||
protected static $TYPES = [
|
||||
1 => 'اخطار',
|
||||
2 => 'هشدار',
|
||||
3 => 'اطلاعیه',
|
||||
4 => 'تبریک',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
"is_admin" => "boolean",
|
||||
"is_active" => "boolean",
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
|
||||
class Order extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $fillable = [
|
||||
'customer_id',
|
||||
'sts',
|
||||
'direction',
|
||||
'description',
|
||||
'input_mode',
|
||||
'ref_id',
|
||||
'amount',//میزان طلا
|
||||
'price',//قیمت هر گرم طلا برای مشتری
|
||||
'total_price',//قیمت کل برای مشتری
|
||||
'total_price_round',//قیمت کل برای مشتری
|
||||
'price_original',//قیمت هر گرم طلا بدون سود
|
||||
'total_price_original',//قیمت کل بدون سود
|
||||
'fee_master', //سود هر گرم برای مدیر
|
||||
'total_fee_master', //سود کل برای مدیر
|
||||
'fee_agent',//سود هر گرم برای نماینده
|
||||
'total_fee_agent',//سود کل برای نماینده
|
||||
'total_fee_full',//سود کل برای نماینده
|
||||
'payment_sts',
|
||||
'payment_amount',//میزان پرداخت شده
|
||||
'payment_remind',//میزان مبلغ باقی مانده
|
||||
'type',//نوع مشتری
|
||||
'product_id',
|
||||
'offer_price',//قیمت پیشنهادی مدیر
|
||||
'offer_mesghal_price',//قیمت پیشنهادی مدیر مثقال
|
||||
'pre_price',//قیمت قبلی مشتری
|
||||
'pre_original_price',//قیمت قبلی مشتری
|
||||
'agent_id',
|
||||
'kalhor_sts',
|
||||
'kalhor_price',
|
||||
'kalhor_base_price',
|
||||
'kalhor_base_price',
|
||||
'kalhor_id',
|
||||
'price_original_in_mesghal',
|
||||
'price_id',
|
||||
'price_in_mesghal',
|
||||
'finance_order',
|
||||
'finance_code',
|
||||
'pay_at',
|
||||
'difference_provider',
|
||||
'rate_price', //نرخ یا مظنه
|
||||
'rate_difference_provider', //نرخ ارایه دهنده
|
||||
'rate_difference_system', //نرخ سیستم
|
||||
'rate_difference_first', //نرخ اول تو تنظیمات
|
||||
'rate_difference_first_id',
|
||||
'rate_difference_second', //نرخ دوم تو تنظیمات
|
||||
'rate_difference_second_id',
|
||||
'rate_price_final', //نرخ نهایی جمع/کسر همشون
|
||||
'rate_price_final_map', //شیوه محاصبه نرخ نهایی
|
||||
'admin_id'
|
||||
];
|
||||
protected $casts = [
|
||||
'finance_order'=>'json',
|
||||
];
|
||||
static $STS = [
|
||||
1 => 'باز',
|
||||
2 => 'تایید شده',
|
||||
3 => 'رد شده و ثبت قیمت جدید',
|
||||
4 => 'رد شده',
|
||||
5 => 'تسویه شده',
|
||||
6 => 'معوقه'
|
||||
];
|
||||
static $DIRECTION = [
|
||||
1 => 'خرید',
|
||||
2 => 'فروش'
|
||||
];
|
||||
static $PAYMENT_STS=[
|
||||
1 => 'در انتظار پرداخت',
|
||||
2 => 'در حال پرداخت',
|
||||
3 => 'partially_paid',
|
||||
4 => 'پرداخت شده',
|
||||
5 => 'partially_refunded',
|
||||
6 => 'مرجوعی',
|
||||
7 => 'پرداخت نشده',
|
||||
];
|
||||
static $TYPE = [
|
||||
1=>'نماینده',
|
||||
2=>'مشتری'
|
||||
];
|
||||
public function customer(){
|
||||
return $this->belongsTo(Customer::class)->select([
|
||||
'id','fname','lname','name','agent_id','mobile','avatar_id','type','tahesab_id',Customer::$SELECT_TYPE_STR
|
||||
]);
|
||||
}
|
||||
public function admin(){
|
||||
return $this->hasOne(User::class,'id','admin_id');
|
||||
}
|
||||
public function product(){
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
public function transaction(){
|
||||
return $this->hasMany(Transaction::class)->select(['*',Transaction::$SELECT_CAJ]);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Package extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $fillable = [
|
||||
'title',
|
||||
'description',
|
||||
'user_creator_id',
|
||||
'agent_id',
|
||||
'customers',
|
||||
'parent_id',
|
||||
'is_base',
|
||||
'for_agent'
|
||||
];
|
||||
protected $casts = [
|
||||
'customers'=>'array',
|
||||
'is_base'=>'boolean',
|
||||
'for_agent' => 'boolean'
|
||||
];
|
||||
public function prices(){
|
||||
return $this->hasMany(prices::class);
|
||||
}
|
||||
public function parent()
|
||||
{
|
||||
return $this->belongsTo(Package::class,'parent_id');
|
||||
}
|
||||
public function customer()
|
||||
{
|
||||
return $this->hasMany(Customer::class);
|
||||
}
|
||||
public function agent()
|
||||
{
|
||||
return $this->belongsTo(Customer::class,'agent_id');
|
||||
}
|
||||
public function sub_packages()
|
||||
{
|
||||
return $this->hasMany(PackageProduct::class,'package_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class PackageProduct extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
public $timestamps = false;
|
||||
protected $fillable = [
|
||||
'product_id',
|
||||
'package_id',
|
||||
'buy_price',
|
||||
'buy_gram_price',
|
||||
'sell_price',
|
||||
'sell_gram_price',
|
||||
'is_base'
|
||||
];
|
||||
protected $casts = [
|
||||
'is_base'=>'boolean'
|
||||
];
|
||||
public function product()
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Permission extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
use Selector;
|
||||
public $timestamps = false;
|
||||
protected $fillable = [
|
||||
'rid',
|
||||
'user_type'
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Price extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $fillable = [
|
||||
"price",
|
||||
"price_gram",
|
||||
"date_at",
|
||||
"time_at",
|
||||
"user_id",
|
||||
"product_id",
|
||||
"difference_gram",
|
||||
"difference_provider",
|
||||
"difference_liman",
|
||||
"difference"
|
||||
];
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class)->select(['id','name']);
|
||||
}
|
||||
public function product(){
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class PriceCandle extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
protected $fillable = [
|
||||
"start",
|
||||
"high",
|
||||
"low",
|
||||
"end",
|
||||
"date_at",
|
||||
"product_id"
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Rooyesh\Wallet\models\Wallet;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
|
||||
class Product extends Model
|
||||
{
|
||||
use HasFactory,Selector,SoftDeletes;
|
||||
protected $fillable = [
|
||||
'title',
|
||||
'unit',
|
||||
'file_id',
|
||||
'can_canceled',
|
||||
'amount',
|
||||
'active',
|
||||
'for_barayand',
|
||||
'show',
|
||||
'open_sell',
|
||||
'kalhor_name',
|
||||
'default_credit',
|
||||
'auto_close_at',
|
||||
'auto_open_at',
|
||||
'reading_method',
|
||||
'open_buy'
|
||||
];
|
||||
protected $casts = [
|
||||
'can_canceled'=>'boolean',
|
||||
'active'=>'boolean',
|
||||
'show'=>'boolean',
|
||||
'for_barayand'=>'boolean',
|
||||
'open_sell' => 'boolean',
|
||||
'auto_sell' => 'boolean',
|
||||
'open_buy' => 'boolean',
|
||||
'auto_buy' => 'boolean'
|
||||
];
|
||||
|
||||
public function file(){
|
||||
return $this->belongsTo(File::class);
|
||||
}
|
||||
public function price(){
|
||||
return $this->hasOne(Price::class)->orderBy('id','desc');
|
||||
}
|
||||
public function getPrices()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$lastMonth = Carbon::now()->subMonth();
|
||||
|
||||
$subQuery = DB::table('prices')
|
||||
->select('product_id', 'date_at', 'price')
|
||||
->whereBetween('date_at', [$lastMonth, $now])
|
||||
->where('product_id', $this->id)
|
||||
->orderBy('date_at', 'desc')
|
||||
->distinct('date_at')
|
||||
->groupBy('date_at', 'product_id', 'price');
|
||||
|
||||
return DB::table(DB::raw("({$subQuery->toSql()}) as sub"))
|
||||
->mergeBindings($subQuery->getQuery())
|
||||
->get(['product_id', 'date_at', 'price']);
|
||||
}
|
||||
public function prices(){
|
||||
$now = Carbon::now();
|
||||
$lastMonth = Carbon::now()->subMonth();
|
||||
$data = [];
|
||||
$datas= $this->hasMany(Price::class, 'product_id')
|
||||
->whereBetween('date_at', [$lastMonth, $now])
|
||||
->distinct('date_at')
|
||||
->select(['product_id', 'date_at', 'difference', 'price']);
|
||||
return $datas;
|
||||
}
|
||||
public function default(){
|
||||
return $this->hasMany(ProductCredit::class);
|
||||
}
|
||||
public function singleDefault(){
|
||||
return $this->hasOne(ProductCredit::class);
|
||||
}
|
||||
public function sub(){
|
||||
return $this->hasOne(PackageProduct::class)->where('is_base',true);
|
||||
}
|
||||
|
||||
public function wallet(){
|
||||
return $this->hasOne(Wallet::class);
|
||||
}
|
||||
public function transaction(){
|
||||
return $this->hasMany(Transaction::class);
|
||||
}
|
||||
public function transactionAgentPanel(){
|
||||
return $this->hasMany(Transaction::class)->where('note','برداشت بابت فروش')->orwhere('note','واریز بابت خرید')->orwhere('note','سند ورود طلا');
|
||||
}
|
||||
public function orders(){
|
||||
return $this->hasOne(Order::class);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ProductCredit extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
protected $fillable = [
|
||||
"product_id",
|
||||
"buy_credit",
|
||||
"sell_credit",
|
||||
"type"
|
||||
];
|
||||
static $TYPES = [
|
||||
1=>'نماینده',
|
||||
2=>'مشتری'
|
||||
];
|
||||
public function product(){
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,269 @@
|
|||
<?php
|
||||
/**
|
||||
* Created by PhpStorm.
|
||||
* User: AraNote
|
||||
* Date: 29/04/2018
|
||||
* Time: 04:38 PM
|
||||
*/
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Hekmatinasser\Verta\Verta;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
trait Selector
|
||||
{
|
||||
static $formatJ = 'Y/n/j-H:i';
|
||||
static $formatBJ = 'Y/n/j';
|
||||
static $SELECT_CUJ = [
|
||||
'created_at as caj',
|
||||
'updated_at as uaj',
|
||||
];
|
||||
|
||||
public static $DATE_FORMAT = 'Y/m/d - h:i';
|
||||
public static $BIRTHDAY_FORMAT = 'Y/m/d';
|
||||
static $SELECT_CAJ = 'created_at as caj';
|
||||
static $SELECT_DAJ = 'date_at as daj';
|
||||
static $SELECT_VAJ = 'vision_at as vaj';
|
||||
static $SELECT_EAJ = 'end_at as eaj';
|
||||
static $SELECT_SAJ = 'start_at as saj';
|
||||
static $SELECT_BIRTH_DAY_J = 'birth_date as bdj';
|
||||
static $SELECT_MARRIAGE_DATE_J = 'marriage_date as mdj';
|
||||
static $SELECT_STS_STR = 'sts as sts_str';
|
||||
static $SELECT_TYPE_STR = 'type as type_str';
|
||||
static $SELECT_USER_TYPE_STR = 'user_type as user_type_str';
|
||||
static $SELECT_GENDER_STR = 'gender as gender_str';
|
||||
static $SELECT_TYPE_SEND_STR = 'type_send as type_send_str';
|
||||
static $SELECT_PAYMENT_TYPE_STR = 'payment_type as payment_type_str';
|
||||
|
||||
public static $MAP_COLUMNS = [
|
||||
'caj' => "created_at",
|
||||
'daj' => 'date_at',
|
||||
'eaj' => 'end_at',
|
||||
'saj' => 'start_at',
|
||||
'bdj' => 'birth_date',
|
||||
'mdj' => 'marriage_date',
|
||||
'vaj' => 'vision_at',
|
||||
'type_str' => "type",
|
||||
'user_type_str' => "user_type",
|
||||
'sts_str' => "sts",
|
||||
'gender_str' => "gender",
|
||||
'type_send_str' => "type_send",
|
||||
'payment_type_str' => "payment_type",
|
||||
];
|
||||
//created_at
|
||||
public function getCreatedAtJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
$date = Verta::instance($value)->format(self::$DATE_FORMAT);
|
||||
dd($date->month);
|
||||
// if ($date->month)
|
||||
// return
|
||||
}
|
||||
public function getCajAttribute($value)
|
||||
{
|
||||
return $this->convertDate($value);
|
||||
}
|
||||
|
||||
// ------------------start_at----------------------------------
|
||||
public function getStartAtJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$DATE_FORMAT);
|
||||
}
|
||||
public function getSajAttribute($value)
|
||||
{
|
||||
return $this->convertDate($value);
|
||||
}
|
||||
|
||||
// ----------------------date_at--------------------------------
|
||||
public function getDateJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$BIRTHDAY_FORMAT);
|
||||
}
|
||||
public function getdajAttribute($value)
|
||||
{
|
||||
return $this->convertDateB($value);
|
||||
}
|
||||
|
||||
// ----------------------birthday_at----------------------------------
|
||||
public function getBirthDateJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$BIRTHDAY_FORMAT);
|
||||
}
|
||||
public function getBdjAttribute($value)
|
||||
{
|
||||
return $this->convertDateB($value);
|
||||
}
|
||||
|
||||
// ----------------------marriage_date----------------------------------
|
||||
public function getMarriageDateJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$BIRTHDAY_FORMAT);
|
||||
}
|
||||
public function getMdjAttribute($value)
|
||||
{
|
||||
return $this->convertDateB($value);
|
||||
}
|
||||
// -------------------vision_at---------------------------------------
|
||||
public function getVisionAtJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$DATE_FORMAT);
|
||||
}
|
||||
public function getVajAttribute($value)
|
||||
{
|
||||
return $this->convertDate($value);
|
||||
}
|
||||
|
||||
// --------------------------end_at-------------------------------------------
|
||||
public function getEndAtJAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return null;
|
||||
return Verta::instance($value)->format(self::$DATE_FORMAT);
|
||||
}
|
||||
public function getEajAttribute($value)
|
||||
{
|
||||
return $this->convertDate($value);
|
||||
}
|
||||
|
||||
// -------------------------type_str----------------------------------------
|
||||
public function getTypeStrAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return $value;
|
||||
|
||||
return Arr::get(self::$TYPES, $value, 'تعریف نشده');
|
||||
}
|
||||
static function GetTypes($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(self::$TYPES, $value, 'بدون مقدار');
|
||||
}
|
||||
|
||||
// -------------------------payment_type_str----------------------------------------
|
||||
public function getPaymentTypeStrAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return $value;
|
||||
|
||||
return Arr::get(self::$PAYMENT_TYPE, $value, 'تعریف نشده');
|
||||
}
|
||||
static function GetPaymentTypes($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(self::$PAYMENT_TYPE, $value, 'بدون مقدار');
|
||||
}
|
||||
|
||||
// ----------------------------user_type_str-------------------------------
|
||||
public function getUserTypeStrAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return $value;
|
||||
$cnt = Cnt::select('value')->findOrFail($value)->pluck('value')->toArray();
|
||||
|
||||
return Arr::get($cnt, $value, 'تعریف نشده');
|
||||
}
|
||||
static function GetUserType($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(config('userType'), $value, 'بدون مقدار');
|
||||
}
|
||||
|
||||
// -------------------------------sts_str-----------------------------
|
||||
static function GetSts($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(self::$STS, $value, 'بدون مقدار');
|
||||
}
|
||||
public function getStsStrAttribute($value)
|
||||
{
|
||||
return self::GetSts($value);
|
||||
}
|
||||
// -------------------------gender_str----------------------------------------
|
||||
public function getGenderStrAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return $value;
|
||||
|
||||
return Arr::get(self::$GENDER, $value, 'تعریف نشده');
|
||||
}
|
||||
static function GetGender($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(self::$GENDER, $value, 'بدون مقدار');
|
||||
}
|
||||
//---------------------type_send str--------------------------------------
|
||||
public function getTypeSendStrAttribute($value)
|
||||
{
|
||||
if (is_null($value)) return $value;
|
||||
|
||||
return Arr::get(self::$TYPE_SEND, $value, 'تعریف نشده');
|
||||
}
|
||||
static function GetTypeSend($value)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return null;
|
||||
}
|
||||
return Arr::get(self::$TYPE_SEND, $value, 'بدون مقدار');
|
||||
}
|
||||
|
||||
|
||||
|
||||
static function selectWithjDate()
|
||||
{
|
||||
return array_merge(['*'], self::$SELECT_CUJ);
|
||||
}
|
||||
protected function convertDate($value, $format = NULL, $farsi = TRUE)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return NULL;
|
||||
}
|
||||
if (is_null($format)) {
|
||||
$format = self::$formatJ;
|
||||
}
|
||||
$date = Verta::instance($value)->format($format, $farsi);
|
||||
if (Verta::parse($date)->month <= 6){
|
||||
$new = Carbon::parse($value)->subHour();
|
||||
return Verta::instance($new)->format($format, $farsi);
|
||||
}
|
||||
return Verta::instance($value)->format($format, $farsi);
|
||||
}
|
||||
protected function convertDateB($value, $format = NULL, $farsi = TRUE)
|
||||
{
|
||||
if (is_null($value)) {
|
||||
return NULL;
|
||||
}
|
||||
if (is_null($format)) {
|
||||
$format = self::$formatBJ;
|
||||
}
|
||||
return Verta::instance($value)->format($format, $farsi);
|
||||
}
|
||||
|
||||
|
||||
public function convertColumns($key){
|
||||
|
||||
return Arr::get(self::$MAP_COLUMNS , $key , $key);
|
||||
}
|
||||
|
||||
// public function getUserTypeStrAttribute(){
|
||||
// if (is_null($this->attributes['user_type'])) return null;
|
||||
// return Arr::get(config('userType') , $this->attributes['user_type'] , 'تعریف نشده');
|
||||
// }
|
||||
|
||||
|
||||
public static function deleteUrl($src){
|
||||
return substr($src,strlen(\request()->root())+1,strlen($src));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Rooyesh\Wallet\models\Transaction;
|
||||
use Tymon\JWTAuth\Contracts\JWTSubject;
|
||||
|
||||
class Setting extends Model
|
||||
{
|
||||
use HasFactory,Selector;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
use Tymon\JWTAuth\Contracts\JWTSubject;
|
||||
|
||||
class User extends Authenticatable implements JWTSubject
|
||||
{
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'fname',
|
||||
'lname',
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'mobile',
|
||||
'user_type',
|
||||
'token_sms',
|
||||
'last_seen_at',
|
||||
'active',
|
||||
'avatar_id',
|
||||
'sts'
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be hidden for serialization.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
|
||||
protected $casts = [
|
||||
'active'=> 'boolean',
|
||||
|
||||
'count_send_sms_time' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the identifier that will be stored in the subject claim of the JWT.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getJWTIdentifier()
|
||||
{
|
||||
return $this->getKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a key value array, containing any custom claims to be added to the JWT.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getJWTCustomClaims()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
// hash password
|
||||
public function setPasswordAttribute($value){
|
||||
$this->attributes['password'] = Hash::make($value);
|
||||
}
|
||||
|
||||
public function setNameAttribute($name = null){
|
||||
$this->attributes['name'] = $name??[$this->attributes['fname'] , $this->attributes['lname']].join(' ');
|
||||
}
|
||||
public function user_type_record(){
|
||||
return $this->belongsTo(Cnt::class,'user_type')->select(['id','value']);
|
||||
}
|
||||
public function avatar(){
|
||||
return $this->belongsTo(File::class,'avatar_id');
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue