This commit is contained in:
gholak tala
2026-01-24 14:03:11 +00:00
parent 7dcd83715a
commit eb26afbcb3
224 changed files with 32652 additions and 0 deletions
Executable
+10
View File
@@ -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
Executable
+15
View File
@@ -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
Executable
+28
View File
@@ -0,0 +1,28 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php82” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php82___lsphp .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
Executable
+14
View File
@@ -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
Executable
+42
View File
@@ -0,0 +1,42 @@
# Use the official PHP image with Apache
FROM php:8.1-apache
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
unzip \
libpng-dev \
libjpeg-dev \
libfreetype6-dev \
zlib1g-dev \
libzip-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install gd \
&& docker-php-ext-install pdo_mysql \
&& docker-php-ext-install zip
# Enable Apache mod_rewrite
RUN a2enmod rewrite
# Set working directory
WORKDIR /var/www/html
# Copy existing application directory contents
COPY . /var/www/html
# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Install PHP dependencies
RUN composer install --no-dev --optimize-autoloader
# Set permissions
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
# Expose port 80
EXPOSE 80
# Start Apache server
CMD ["apache2-foreground"]
Executable
+9
View File
@@ -0,0 +1,9 @@
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Http\Controllers\Admin\PriceController;
use App\Models\Cnt;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class Price extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'price:price';
/**
* 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()
{
$service = Http::
withHeaders([
'accept' => 'application/json',
'Authorization' => 'Bearer ohxsrbjagqvbt0glaygt'
])->get('https://studio.persianapi.com/index.php/web-service/common/gold-currency-coin?format=json&limit=30&page=1')
->json();
$list = [];
if(isset($service['result'])){
foreach ($service['result'] as $item){
if ($item['key']== 137120 || $item['key']==137119) {
$list[] = $item;
if ($item['key']== 137120){
(new PriceController())->store(new Request(["price"=>$item['price']]));
}
}
}
Cnt::where('key','price')->update(['value_json'=>$list]);
}
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Console;
use App\Console\Commands\Price;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Price::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
+4
View File
@@ -0,0 +1,4 @@
[10-Jun-2024 08:45:45 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Console\Kernel' not found in /home/montechi/public_html/server_app/app/Console/Kernel.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Console/Kernel.php on line 9
+59
View File
@@ -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;
}
}
+303
View File
@@ -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());
}
}
+63
View File
@@ -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();
}
}
}
+40
View File
@@ -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;
}
}
+71
View File
@@ -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;
}
}
+217
View File
@@ -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/' . $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');
}
}
+160
View File
@@ -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;
}
}
+15
View File
@@ -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;
}
+1
View File
@@ -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}
+64
View File
@@ -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;
}
}
+4
View File
@@ -0,0 +1,4 @@
[10-Jun-2024 12:44:03 UTC] PHP Fatal error: Uncaught Error: Interface 'Maatwebsite\Excel\Concerns\FromCollection' not found in /home/montechi/public_html/server_app/app/DB/Te/ExcelCollection.php:13
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/DB/Te/ExcelCollection.php on line 13
+17
View File
@@ -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'
]
];
+61
View File
@@ -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>
+34
View File
@@ -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']
]
];
+66
View File
@@ -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>
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
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) {
//
});
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\BankAccount;
use App\Models\Customer;
use Illuminate\Http\Request;
class BankAccountController extends SuperController
{
public function __construct()
{
$name_model = 'user';
$search=["cart_number","customer.name"];
parent::__construct(BankAccount::class, ['customer'], ['*',BankAccount::$SELECT_STS_STR],$name_model,null,$search);
}
public function changeSts(Request $request){
$data = $request->all();
$accoun = BankAccount::findOrFail($data['id']);
$accoun->sts = $data['sts'];
$accoun->save();
if ($accoun->sts == 2) {
$customer = Customer::find($accoun->customer_id);
$this->SendMessage($customer->mobile, 'کارت بانکی شما در ' . $this->Config('name_fa') . ' تایید شد');
}
return response()->json(true);
}
}
+22
View File
@@ -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')->first();
return response()->json($cnt);
}
}
+257
View File
@@ -0,0 +1,257 @@
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\SuperController;
use App\Models\Customer;
use App\Models\TransactionsAdmin;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class CustomerController extends SuperController
{
public function __construct()
{
$this->with = [];
$this->select = ['*'];
$search=['name','mobile'];
$this->query = Customer::with($this->with,'wallet')->where('is_archive',false)->where('type',1);
// $this->query = Customer::where('is_archive',false)->get();
parent::__construct(Customer::class, $this->with, $this->select, 'customer', $this->query, $search);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse
*/
public function listUser(){
$user = Customer::with(['wallet'])->select('id','name','mobile','type')->get();
return response()->json($user);
}
public function updateAdmin(Request $request , $id)
{
$data = $request->all();
if (isset($data['mobile']) && !is_null($data['mobile'])){
$check_mobile = Customer::where('mobile',$data['mobile'])
->where('id','<>',$id)
->first();
if (!is_null($check_mobile)){
throw new UnprocessableEntityHttpException('این شماره همراه توسط شخص دیگری در حال استفاده است');
}
}
if (isset($data['gold'])){
$user = Customer::find($id);
if ($user) {
$user->gold = $data['gold'];
$user->save();
$user["g"]=true;
}
}
$user["u"] = Customer::findOrFail($id)->update($data);
return response()->json($user);
}
public function referrals(Request $request,$customer_id)
{
$customer_referral_id = Customer::where("id",$customer_id)->first()->referral_id;
$query_table = Customer::where("referral_to_id",$customer_referral_id);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['*',Customer::$SELECT_TYPE_STR])
->export($query_table);
return response()->json($query_table);
}
public function funds(Request $request,$customer_id)
{
$query_table = Wallet::with(['fund'])->where('owner', $customer_id); // Adjust columns as per your schema
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['id', 'owner', 'cash', 'gold','fund_id','created_at', 'updated_at'])
->export($query_table);
return response()->json($query_table);
}
public function archive($id){
$query = Customer::findOrFail($id);
$query->update([
'is_archive'=>!$query->is_archive
]);
return response()->json(true);
}
public function tableWallets(Request $request){
$query_table = Customer::with(['wallet','referral'])->where("is_archive",false)/*->where('type',1)*/;
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select(['*',Customer::$SELECT_TYPE_STR])
->export($query_table);
return response()->json($query_table);
}
public function archiveTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",true)/*->where('type',1)*/;
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
/**
* @param $id
* @return \Illuminate\Http\JsonResponse
*/
public function active($id){
$query = Customer::findOrFail($id);
$active = !$query->active;
$query->update([
'active'=>!$query->active
]);
if ($active){
$message ='اکانت شما توسط کارشناس سیستم تایید شد '."\n".
'با رفتن به لینک زیر وارد حساب کاربری خود شوید'."\n".
$this->Config('app_url')."\n".
'با تشکر'.$this->Config('name_fa');
}
else{
$message ='اکانت شما توسط کارشناس سیستم غیر فعال شد '."\n".
'با کارشناسان ما تماس بگیرید'."\n".
'با تشکر'.$this->Config('name_fa');
}
$this->Send($query->mobile,$message);
return response()->json(true);
}
public function changeTradeActive($id){
$query = Customer::findOrFail($id);
$query->update([
'trade_active'=>!$query->trade_active
]);
return response()->json(true);
}
// single customer-------------------
public function singleArchiveTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",true)->where('type',2);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
public function singleCustomerTable(Request $request)
{
$query_table = Customer::with($this->with)->where("is_archive",false)->where('type',2);
TableEngine::create($query_table, $request)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return response()->json($query_table);
}
public function MakeValidByAdmin(Request $request,$id)
{
$customer = Customer::with('referral')->where('id', $id)->first();
if ($customer->is_legal == 2 or $customer->is_legal == 3){
return response()->json(true);
}
$customer->is_legal = 2;
$customer->save();
if ($this->Config('has_page_earn_money') == true && Customer::where('referral_to_id', $customer->referral->referral_id)->where('is_legal', "!=",0)->count() < 4) {
$gift_for_inviter = 0.002;
$gift_for_invited = 0.003;
$Withdraw = Withdraw::create([
'user_id' => $customer->id,
'customer_id' => $customer->referral->id,
"cash" => 0,
"gold" => $gift_for_invited,
'sts' => 5,
]);
$wallet_interface = new WalletInterface($customer->referral->id, 2);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => 0,
"gold"=> $gift_for_invited,
'expire_at'=>now(),
'active'=>true,
'withdraw_id' =>$Withdraw->id,
'start_at'=>now(),
], 8, true,false);
$transaction = Transaction::where('customer_id', $customer->referral->id)->latest()->first();
TransactionsAdmin::create([
'customer_id' => $customer->id,
'customer_to_id' => $customer->referral->id,
'user_id' => $customer->id,
'wallet' => null, // یا مقدار مناسب دیگری
'transaction_id' => $transaction->id ,
'cash' => 0,
'note' => 'پاداش بابت معرفی',
'type' => 1, // یا مقدار مناسب دیگری
'gold' => $gift_for_invited,
'balance_cash' => 0, // یا مقدار مناسب دیگری
'withdraw_id' => $Withdraw->id,
]);
$Withdraw = Withdraw::create([
'user_id' => $customer->id,
'customer_id' => $customer->id,
"cash" => 0,
"gold" => $gift_for_inviter,
'sts' => 5,
]);
$wallet_interface = new WalletInterface($customer->id, 2);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => 0,
"gold"=> $gift_for_inviter,
'expire_at'=>now(),
'active'=>true,
'withdraw_id' =>$Withdraw->id,
'start_at'=>now(),
], 8, true,false);
$transaction = Transaction::where('customer_id', $customer->id)->latest()->first();
TransactionsAdmin::create([
'customer_id' => $customer->id,
'customer_to_id' => $customer->id,
'user_id' => $customer->id,
'wallet' => null, // یا مقدار مناسب دیگری
'transaction_id' => $transaction->id ,
'cash' => 0,
'note' => 'پاداش بابت معرفی',
'type' => 1, // یا مقدار مناسب دیگری
'gold' => $gift_for_inviter,
'balance_cash' => 0, // یا مقدار مناسب دیگری
'withdraw_id' => $Withdraw->id,
]);
}
$companyName = $this->Config('name_fa');
$companyurl = $this->Config('app_url');
$message ='حساب کاربری شما توسط کارشناس سیستم تایید شد '."\n".
'با رفتن به لینک زیر وارد حساب کاربری خود شوید'."\n".
$this->Config('app_url')."\n".
'با تشکر'.$this->Config('name_fa');
$this->Send($customer->mobile, $message);
$referrer = $customer->referral;
// if ($referrer) {
// if (Customer::where('referral_to_id', $referrer->referral_id)->get()->count()<=$referrer->add_user_limit) {
// $referrerWallet = Wallet::where('owner',$customer->referral->id)->first();
// $message = "سلام {$referrer->name} عزیز،\n\n{$gift_for_invite} گرم طلا بابت معرفی {$customer->name} به حساب شما واریز شد.\nموجودی فعلی: {$referrerWallet->gold} گرم.\n\nاطلاعات بیشتر: $companyurl\n\nبا احترام،\n$companyName";
// $this->Send($referrer->mobile, $message);
// }
// }
return response()->json(true);
}
}
+306
View File
@@ -0,0 +1,306 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Cnt;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Price;
use App\Models\TransactionsAdmin;
use App\Models\Withdraw;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Rooyesh\Wallet\models\Wallet;
class DashboardController extends Controller
{
public function dashboardMaster(){
$tallaPrice = Price::latest()->first();
// $talla->update_date = Verta::instance(Carbon::parse($talla->updated_at))->format('Y/n/j-H:i');
$new_customer_major = Customer::where('type',1)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$new_customer_single = Customer::where('type',2)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$all_customer_major = Customer::where('type',1)->count();
$all_customer_single = Customer::where('type',2)->count();
$archive_customer_major = Customer::where('type',1)->where('is_archive',true)->count();
$archive_customer_single = Customer::where('type',2)->where('is_archive',true)->count();
$all_gold = Order::where('direction',2)->where('type',1)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$all_gold_single = Order::where('direction',2)->where('type',2)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$await_list = Order::where('direction',1)->where('sts',1)->get();
$best_customer_major=Order::with('customer')->where('type',1)->where('sts',2)->select('customer_id',DB::raw('sum(amount) as amount'))
->groupBy('customer_id')->limit(10)->get();
$best_customer_single=Wallet::with('customer')->whereNull('fund_id')->where('owner_type',2)->orderBy('gold','desc')->limit(10)->get();
// GT
$GT_all_customers = Customer::where('type',2)->where('is_archive',false)->count();
$GT_no_login_customers = Customer::where('type',2)->where('is_archive',false)->where('last_seen_at',null)->count();
$GT_no_valid_customers = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->count();
$GT_no_valid_customers_data = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->get(['id','name','mobile']);
$GT_active_customers = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->count();
$GT_active_customers_data = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->get(['id','name','mobile']);
$transactions_admins = TransactionsAdmin::with(['withdraw','order',"user",'customerTo','customer'])->get();
return response()->json([
'GT_all_customers'=>$GT_all_customers,
'GT_no_login_customers'=>$GT_no_login_customers,
'GT_no_valid_customers'=>$GT_no_valid_customers,
'GT_no_valid_customers_data'=>$GT_no_valid_customers_data,
'GT_active_customers'=>$GT_active_customers,
'GT_active_customers_data'=>$GT_active_customers_data,
'GT_deActive_customers'=>$GT_all_customers-$GT_active_customers,
'GT_transactions_admins'=>$transactions_admins,
'price'=>$tallaPrice->price,
'new_customer_major'=>$new_customer_major,
'new_customer_single'=>$new_customer_single,
'all_customer_major'=>$all_customer_major,
'all_customer_single'=>$all_customer_single,
'archive_customer_major'=>$archive_customer_major,
'archive_customer_single'=>$archive_customer_single,
'all_gold'=>$all_gold,
'all_gold_single'=>$all_gold_single,
'await_order'=>$await_list,
'best_customer'=>$best_customer_major,
'best_customer_single'=>$best_customer_single,
]);
}
public function getBalance(Request $request)
{
$startDate = Carbon::parse($request->startDate)->startOfDay();
$endDate = Carbon::parse($request->endDate)->endOfDay();
$response=[];
$response["liman"]=[];
$response["kalhor"]=[];
$response["pay_at_update"] = Order::whereNull('pay_at')->update(['pay_at' => DB::raw('created_at')]);
//liman
$response["liman"]["orders"] = Order::with(['transactions.product'])->where('customer_id', '!=', 4)->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"] = Cache::remember("kalhor_orders_" . md5($startDate . $endDate), 900, function () use ($startDate, $endDate) {
// $body = [
// 'FromDate' => Jalalian::forge($startDate)->format('Y/m/d'),
// 'ItemId' => 0,
// 'OrderIndex' => 0,
// 'ToDate' => Jalalian::forge($endDate)->format('Y/m/d'),
// ];
//
// return Http::withHeaders(config('kalhor.headers'))
// ->withCookies(config('kalhor.cookies'), 'b750.ir')
// ->post('https://b750.ir/Deal/DealsList', $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'] == "فروش" or $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' =>Jalalian::fromFormat('Y/m/d', explode('_', $data['ModifiedDateStr'])[0])->toCarbon()->format('Y-m-d') . ' ' . explode('_', $data['ModifiedDateStr'])[1],
'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;*/
$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['income_money'] = Withdraw::whereNotNull('zify_code')->where('sts',2)->whereBetween('updated_at', [$startDate, $endDate])->sum('cash');
return $response;
}
public function finance(Request $request)
{
$startDate = $request->startDate ? Carbon::parse($request->startDate)->startOfDay() : Carbon::now()->subDays(30)->startOfDay();
$endDate = $request->endDate ? Carbon::parse($request->endDate)->endOfDay() : Carbon::now()->endOfDay();
// Fetch orders and transactions within the date range
$ords = Order::whereBetween('created_at', [$startDate, $endDate])->get();
$TransactionsAdmin = TransactionsAdmin::whereBetween('created_at', [$startDate, $endDate])->get();
// Initialize response data
$response = [
"fullPriceM1" => 0,
"fullPriceM2" => 0,
"fullPriceSood" => 0,
"fullPriceKarmozd" => 0,
"orderCount" => $ords->count(),
"Gifts" => 0,
"GiftsPrise" => 0,
"sumAll" => 0
];
// Calculate total gold gifts from transactions
foreach ($TransactionsAdmin as $TransactionAdmin) {
$response['Gifts'] += $TransactionAdmin->gold;
}
$response['Gifts'] = number_format($response['Gifts'], 3);
// Calculate total price of gold gifts
$response['GiftsPrise'] = floor($response['Gifts'] * Price::latest()->first()->price);
// Calculate order-related sums
foreach ($ords as $ord) {
$response['fullPriceM1'] += abs($ord->total_price_original - $ord->payment_amount);
$response['fullPriceM2'] += $ord->service_charge_price + $ord->total_fee;
$response['fullPriceSood'] += $ord->total_fee;
$response['fullPriceKarmozd'] += $ord->service_charge_price;
}
$response['sumAll'] = $response['fullPriceM1']-$response['GiftsPrise'];
return $response;
}
public function sumSellToCustomerMajor(Request $request){
$data = $request->all();
$order = Order::where('direction',1)
->where('sts',2)
->whereDate('created_at','>=',Carbon::parse($data['start_at']))
->whereDate('created_at','<=',Carbon::parse($data['end_at']))
->where('type',1)
->sum('amount');
return response()->json($order);
}
public function sumSellToCustomerSingle(Request $request){
$data = $request->all();
$order = Order::where('direction',1)
->where('sts',2)
->whereDate('created_at','>=',Carbon::parse($data['start_at']))
->whereDate('created_at','<=',Carbon::parse($data['end_at']))
->where('type',2)
->sum('amount');
return response()->json($order);
}
public function flow(Request $request){
$data = $request->all();
if ($data['type'] == 'week'){
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subWeek())
->select(['direction',DB::raw('Date(created_at) as date'),DB::raw('sum(amount) as total')])
->groupBy(['date','direction'])
->get();
}
elseif ($data['type'] == 'month'){
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subMonth())
->select(['direction',DB::raw('Date(created_at) as date'),DB::raw('sum(amount) as total')])
->groupBy(['date','direction'])
->get();
}
if (in_array($data['type'],['week','month'])){
$send = [];
foreach ($query as $i){
if(in_array($i['date'],array_keys($send))){
$send[$i['date']][$i['direction']] = $i['total'];
}else{
$send[$i['date']]['date'] =$i['date'];
$send[$i['date']][$i['direction']] = $i['total'];
}
}
}
else{
$query=Order::where('sts',2)
->whereDate('created_at','<=',now())
->whereDate('created_at','>=',now()->subYear())
->select(['direction',DB::raw('MONTH(created_at) as month'),DB::raw('sum(amount) as total')])
->groupBy(['month','direction'])
->get();
for ($i=0;$i<count($query);$i++){
$query[$i]['month_fa'] = Verta::instance( $query[$i]['month'])->format('%B');
}
}
return response()->json(array_values($send));
}
}
+234
View File
@@ -0,0 +1,234 @@
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Models\Customer;
use App\Models\Message;
use App\Models\Order;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class MassageController extends Controller
{
public function send_message(Request $request)
{
// یافتن مشتریان با شماره‌های داده شده
$customers = Customer::whereIn('mobile', $request->numbers)->get();
foreach ($customers as $customer) {
// جایگزین کردن نام در پیام
$message = str_replace('%name%', $customer->name, $request->message);
// ارسال پیامک
$this->send($customer->mobile, $message);
}
return response()->json(true);
}
public function getFunctionDescriptions()
{
return response()->json([
[
'function' => 'getAllCustomers',
'name' => 'همه کاربران',
],
[
'function' => 'getNoLoginCustomers',
'name' => 'کاربران وارد نشده',
],
[
'function' => 'getNoValidCustomers',
'name' => 'کاربران احراز نشده',
],
[
'function' => 'getActiveCustomers',
'name' => 'کاربران فعال',
],
]);
}
public function getCustomerList(Request $request)
{
$customers = [];
foreach ($request->functions as $action) {
if ($action === 'getAllCustomers') {
$customers = array_merge($customers, $this->getAllCustomers());
}
if ($action === 'getNoLoginCustomers') {
$customers = array_merge($customers, $this->getNoLoginCustomers());
}
if ($action === 'getNoValidCustomers') {
$customers = array_merge($customers, $this->getNoValidCustomers());
}
if ($action === 'getActiveCustomers') {
$customers = array_merge($customers, $this->getActiveCustomers());
}
}
// حذف شماره‌های تکراری
$uniqueCustomers = $this->removeDuplicateNumbers($customers);
return response()->json(['customers' => $uniqueCustomers]);
}
public function getCustomerListTable(Request $request)
{
$customers = [];
foreach ($request->functions as $action) {
if ($action === 'getAllCustomers') {
$customers = array_merge($customers, $this->getAllCustomers());
}
if ($action === 'getNoLoginCustomers') {
$customers = array_merge($customers, $this->getNoLoginCustomers());
}
if ($action === 'getNoValidCustomers') {
$customers = array_merge($customers, $this->getNoValidCustomers());
}
if ($action === 'getActiveCustomers') {
$customers = array_merge($customers, $this->getActiveCustomers());
}
}
// Remove duplicate numbers
$uniqueCustomers = $this->removeDuplicateNumbers($customers);
$uniqueCustomersCollection = collect($uniqueCustomers);
$records = Customer::whereIn('id', $uniqueCustomersCollection->pluck('id'));
// Initialize TableEngine
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'id','mobile', 'name'
])
->export($records);
return response()->json($records);
}
private function getAllCustomers()
{
return Customer::where('type', 2)
->where('is_archive', false)
->get(['id', 'name', 'mobile'])
->toArray();
}
private function getNoLoginCustomers()
{
return Customer::where('type', 2)
->where('is_archive', false)
->whereNull('last_seen_at')
->get(['id', 'name', 'mobile'])
->toArray();
}
private function getNoValidCustomers()
{
return Customer::where('type', 2)
->where('is_archive', false)
->where('is_legal', 0)
->get(['id', 'name', 'mobile'])
->toArray();
}
private function getActiveCustomers()
{
return Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function ($query) {
$query->select('owner')
->from('wallets');
})
->get(['id', 'name', 'mobile'])
->toArray();
}
private function removeDuplicateNumbers(array $customers)
{
$uniqueCustomers = [];
$seenNumbers = [];
foreach ($customers as $customer) {
if (!in_array($customer['mobile'], $seenNumbers)) {
$seenNumbers[] = $customer['mobile'];
$uniqueCustomers[] = $customer;
}
}
return $uniqueCustomers;
}
public function messagesTable(Request $request)
{
$records = Message::with(['person']);
$table = TableEngine::create($records, $request->all())
->initSearch([])
->select([
'id', 'sms', 'receiver','created_at',
]);
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);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
class OrderController extends Controller
{
public function table(Request $request){
$records = Order::with(['customer','transactions']);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Order::$SELECT_STS_STR
])->export($records);
return response()->json($records);
}
public function singleOrderTable(Request $request){
$records = Order::with(['customer'])->where('type',2);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Order::$SELECT_STS_STR
])->export($records);
return response()->json($records);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Models\Price;
use App\Models\PriceCandle;
use Illuminate\Http\Request;
class PriceController extends Controller
{
public function store(Request $request){
Price::create([
"price"=>$request->price ,
"date_at"=>date("Y-m-d"),
"time_at"=>now()->format("H:m:s"),
"user_id"=>auth('user')->id()
]);
$candle = PriceCandle::whereDate('date_at',date("Y-m-d"))->first();
if (!is_null($candle)){
$candle->end = $request->price;
if ($request->price < $candle->low){
$candle->low = $request->price;
}
elseif ($request->price > $candle->high){
$candle->high = $request->price;
}
$candle->save();
}else{
PriceCandle::create([
"start"=>$request->price,
"end"=>$request->price,
"high"=>$request->price,
"low"=>$request->price,
"date_at"=>date("Y-m-d")
]);
}
return response()->json(true);
}
public function priceData(Request $request){
$prise = Price::with('order');
TableEngine::create($prise, $request)
->initSearch(['price'])
->select(['*'])
->export($prise);
return response()->json($prise);
}
public function table(Request $request){
$records = Price::with(['user']);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*'
])->export($records);
return response()->json($records);
}
}
+246
View File
@@ -0,0 +1,246 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\Product;
use App\DB\Te\TableEngine;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Illuminate\Support\Facades\Http;
use \App\Http\Controllers\Customer\FundController;
use App\Http\Controllers\Site\ReportController ;
class ProductController extends SuperController
{
public function __construct()
{
$this->with = ['file', 'price', 'default', 'sub'];
$this->with = [];
parent::__construct(Product::class, $this->with, ['*'], null, null, ['title']);
}
public function tableProduct(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);
//*******کداضافه شده
// ->where('active', '<=', now()) // فیلتر محصولات فعال
// ->get();
//*********
}else{
$query_table = $this->query;
// $query_table = $query_table->where('active', '<=', now());
}
TableEngine::create($query_table, $data)
->initSearch($this->search)
->select($this->select)
->export($query_table);
$query_table['auto_open_at'] = Product::selectRaw(
'SEC_TO_TIME(AVG(TIME_TO_SEC(TIME(auto_open_at)))) as avg_time'
)->value('avg_time'); $query_table['auto_close_at'] = Product::selectRaw(
'SEC_TO_TIME(AVG(TIME_TO_SEC(TIME(auto_close_at)))) as avg_time'
)->value('avg_time');
// $query_table['11'] = $avgDuration;
// $query_table['11'] = Product::avg('auto_open_at');
// $query_table['112'] = Product::avg('auto_close_at');
return $query_table;
}
public function editProducts(Request $request)
{
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.']);
}
return response()->json(['error' => 'auto_open_at and auto_close_at must be set'], 400);
}
public function store(Request $request)
{
$data = $request->all();
$product = Product::create($data);
return $this->resultCreate($product->id);
}
public function update(Request $request, $id)
{
// return 1;
$data = $request->all();
if (isset($data["price"])){
$data["reading_method"] = null;
}
if (isset($data["auto_close_at"]) and isset($data["auto_close_at"])){
if ($data["auto_close_at"] == $data["auto_open_at"]){
unset($data["auto_open_at"]);
unset($data["auto_close_at"]);
}
}
// return $data['price'];
// if(!isset($data['default'])){
// throw new UnprocessableEntityHttpException('مقادیر اعتبارات را وارد کنید');
// }
// $data['auto_open_at'] = Carbon::parse($data['auto_open_at'])->format('Y-m-d H:i:s');
// $data['auto_close_at'] = Carbon::parse($data['auto_close_at'])->format('Y-m-d H:i:s');
// Product::find($id)->update($data);
Product::find($id)->update($data);
return response()->json(true);
}
public function destroy($id)
{
Product::findOrFail($id)->delete();
return response()->json(true);
}
public function listProduct()
{
// $this->getPrice();
$this->auto_close_open();
$product = Product::with([])->where('active', 1)->get();
return response()->json($product);
}
public function getPrice()
{
// $RPrices = Http::get('https://pricing.liman.gold/pricingApi', [])->json();
// $RPrices = Http::get('https://pricing.liman.gold/pricingApi', [])->json();
$RPrices =Http::timeout(40)->get('http://212.23.201.173:8381/price_list', [])->json();
$products = Product::with([])->whereNotNull('reading_method')->get();
foreach ($products as $product) {
foreach ($RPrices as $RPrice) {
if ($product->reading_method == $RPrice['name']) {
$p = Product::where('id', $product->id)->update([
'price' => $RPrice['price'],
'price_profit' => $RPrice['profit'],
]);
if($product->bubble== 1){
$ReportController = new ReportController();
$liquidGold= $ReportController->lastPrice();
$p = Product::find($product->id);
$p->amount = $RPrice['price'] / $liquidGold['price'];
$p->save();
}
}
}
}
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 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);
$product->$field = !$product->$field;
$product->save();
if (!$product->open_buy and !$product->open_sell) {
$product->show = false;
$product->active = false;
} else {
$product->show = true;
$product->active = true;
}
$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);
}
public function updatePrice(Request $request){
}
}
+220
View File
@@ -0,0 +1,220 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\Tahesab;
use App\Models\Customer;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Hekmatinasser\Verta\Verta;
class TahesabController extends Controller
{
public function store()
{
$customer = auth()->user();
if (!$customer) {
throw new UnprocessableEntityHttpException("Auth needed");
}
$customer = Customer::where('id', $customer->id)->first();
if ($customer && ($customer->moshtari_code !== null)) {
return "customer exists";
}
try {
$response = Http::withoutVerifying()->timeout(10)->withHeaders([
'DBName' => $this->Config('tahesab_db'),
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->Config('tahesab_token'),
])->post('https://185.252.86.194:8081', [
"DoNewMoshtari" => [
$customer->name,
$this->Config('name_fa'),
$customer->mobile,
"",
$customer->n_code ?? "",
$customer->birth_date ?? "", // !== null ? jalalian::fromCarbon(Carbon::parse($customer->birth_date))->format('Y/m/d') : null,
"",
"",
-1,
0 // tala
]
]);
} catch (\Exception $e) {
return $e->getMessage();
}
if (empty($response['OK'])) {
return "tahesab api error!!!";
}
$customer->moshtari_code = $response['OK'];
$customer->save();
return true;
}
public function storeTrade($input = null)
{
if ($input instanceof \Illuminate\Http\Request) {
$data = $input->all();
} elseif (is_array($input)) {
$data = $input;
} else {
$data = request()->all();
}
// return ($data);
if (!isset($data['customer_id']) || !isset($data['product']['amount'])) {
return request()->expectsJson()
? response()->json(['error' => 'Data missing: customer_id or value'], 422)
: false;
}
// $customer = auth()->user();
// if (!$customer) {
// throw new UnprocessableEntityHttpException("Auth needed");
// }
$customer = Customer::where('id', $data['customer_id'])->first();
if ($customer && ($customer->moshtari_code === null)) {
$this->store();
}
$date = Verta::instance(Carbon::parse($data['pay_at']))->format('Y-m-d');
[$year, $month, $day] = explode('-', $date);
$amount = $data['amount'];
$tahesab = Tahesab::create([
"customer_id" => $customer->id,
"desc" => $data['direction'] == 1 ? "خرید آبشده" : "فروش آبشده",
"amount" => $amount,
"date" => $data['pay_at'],
"type" => $data['product']['metal_id'] == 1 ? "طلا" : "نقره",
"created_at" => Carbon::now(),
]);
try {
$response = Http::withoutVerifying()->timeout(10)->withHeaders([
'DBName' => $this->Config('tahesab_db'),
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->Config('tahesab_token'),
])->post('https://185.252.86.194:8081', [
"DoNewSanadBuySaleGOLD" => [
1,//Sabte_Kol_Or_Movaghat_1_0
(int)$customer->moshtari_code, //Moshtari_Code
-1, //Factor_Number
1, //Radif_Number
(int)$year, //Shamsi_Year
(int)$month, //Shamsi_Month
(int)$day, //Shamsi_Day
(float)$amount, //Vazn
$data['product']['metal_id'] == 1 ? 750 : "", //Ayar
0,
"",
$data['direction'] == 1 ? 0 : 1, //BuyOrSale_0_1
(int)$data['price'], //Mazaneh
1, //MazanehIsMesghalOrGeram_0_1
1, //IsMotefaregheOrAbshode_0_1
(int)$data['total_price_original'], //MablaghKol
$data['direction'] == 1 ? "خرید آبشده" : "فروش آبشده",
"Code_Factor",
"", //HavalehBe_Mcode
"", //MultiRadif
$data['product']['metal_id'] == 1 ? 0 : 2, //Jens_Felez
(string)Verta::instance($data['pay_at']),
]
]);
} catch (Exception $e) {
return $e->getMessage();
}
if ($response['OK']) {
$tahesab->sh_factor = $response['Sh_factor'];
$tahesab->tahesab_id = $response['OK'];
$tahesab->factor_number = $response['Factor_Number'];
$tahesab->tah_id = $response['ID'];
$tahesab->res = $response;
$tahesab->data = $data;
$tahesab->save();
return $data;
}
return false;
}
// directon: 0 = daryaft az moshtari
// directon: 1 = pardakht be moshtari
public function wallet($input = null)
{
if ($input instanceof \Illuminate\Http\Request) {
$data = $input->all();
} elseif (is_array($input)) {
$data = $input;
} else {
$data = request()->all();
}
if (!isset($data['customer_id']) || !isset($data['value'])) {
return request()->expectsJson()
? response()->json(['error' => 'Data missing: customer_id or value'], 422)
: false;
}
// $customer = auth()->user();
// if (!$customer) {
// throw new UnprocessableEntityHttpException("Auth needed");
// }
$customer = Customer::where('id', $data['customer_id'])->first();
if (!$customer || ($customer->moshtari_code === null)) {
$this->store();
}
$tahesab = Tahesab::create([
"customer_id" => $customer->id,
"desc" => $data['direction'] == 0 ? "شارژ حساب" : "برداشت از حساب",
"amount" => $data['value'],
"date" => Carbon::now(),
"created_at" => Carbon::now(),
]);
try {
$response = Http::withoutVerifying()->timeout(10)->withHeaders([
'DBName' => $this->Config('tahesab_db'),
'Content-Type' => 'application/json',
'Authorization' => "Bearer " . $this->Config('tahesab_token'),
])->post('https://185.252.86.194:8081', [
"DoNewSanadVKHBank" => [
1,//Sabte_Kol_Or_Movaghat_1_0
$customer->moshtari_code,//Moshtari_Code
-1,//Factor_Number
1,//Radif_Number
1404,//Shamsi_Year
10,//Shamsi_Month
18,//Shamsi_Day
$data['direction'],//IsDayaftAzMoshtariOrPardakhtBeMoshtari_0_1
(int)$data['value'],//Mablagh
$data['direction'] == 0 ? "شارژ حساب" : "برداشت از حساب",//Sharh
"test",
"$tahesab->id",//Code_Rahgiri
-1,//Factor_Code
-1,
//MultiRadif
]
]);
} catch (\Exception $e) {
return $e->getMessage();
}
if ($response['OK']) {
$tahesab->sh_factor = $response['Sh_factor'];
$tahesab->tahesab_id = $response['OK'];
$tahesab->save();
return $data;
}
return false;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends SuperController
{
public function __construct(Request $request)
{
$model = User::class;
// $with=['avatar','user_type_record'];
$with=[];
$select = ['*'];
$name_model = 'user';
$search=['name','mobile'];
$request->request->add(['active'=>1]);
parent::__construct($model, $with, $select, $name_model,null,$search);
}
public function me(){
$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;
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);
}
}
+349
View File
@@ -0,0 +1,349 @@
<?php
namespace App\Http\Controllers\Admin;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Price;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use App\Http\Controllers\Admin\TahesabController;
class WalletController extends Controller
{
public function charge2(Request $request)
{
$data = $request->all();
$customer = Customer::findOrFail($data['customer_id']);
$deposit = false;
if ($data['value'] > 0) {
$deposit = true;
}
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
if (is_null($wallet) && !$deposit) {
throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
}
if (!is_null($wallet) && $wallet->cash < abs($data['value']) && !$deposit) {
throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
}
$wallet_interface = new WalletInterface($data['customer_id'], $customer->type);
$orders = Order::where('customer_id', $data['customer_id'])->where('sts', 1)->get();
$gold_block = 0;
if (count($orders) > 0) {
$value = $data['value'];
foreach ($orders as $order) {
if ($value < $order->payment_remind) {
$order->payment_amount += $value;
$order->payment_remind -= $value;
$order->save();
break;
} else {
$value -= $order->payment_remind;
$order->payment_amount = $order->total_price;
$order->payment_remind = 0;
$order->sts = 2;
$gold_block -= $order->amount;
$order->save();
}
}
}
$user = auth()->user();
$customer = Customer::findOrFail($data["customer_id"]);
$Withdraw = Withdraw::create([
'user_id' => $user->id,
'customer_id' => $customer->id,
"cash" => $data['value'],
'sts' => 4,
]);
new TransactionInterface($wallet_interface, $_inp = [
'cash' => $data['value'],
'expire_at' => now(),
'withdraw_id' => $Withdraw->id,
'active' => true
], 3, false, true, $gold_block);
$message = 'کیف پول شما به مبلغ ' . $data['value'] . " ریال در تاریخ " . verta()->format('Y/n/j H:i:s') . " شارژ شد " . "\n"
. $this->Config('name_fa');
$this->Send($customer->mobile, $message);
return response()->json(true);
}
public function charge(Request $request)
{
$data = $request->all();
$customer = Customer::findOrFail($data['customer_id']);
$deposit = false;
if ($data['value'] > 0) {
$deposit = true;
}
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
if (is_null($wallet) && !$deposit) {
throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
}
if (!is_null($wallet) && $wallet->cash < abs($data['value']) && !$deposit) {
throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
}
$wallet_interface = new WalletInterface($data['customer_id'], $customer->type);
$orders = Order::where('customer_id', $data['customer_id'])->where('sts', 1)->get();
$gold_block = 0;
$user = auth()->user();
$customer = Customer::findOrFail($data["customer_id"]);
$Withdraw = Withdraw::create([
'user_id' => $user->id,
'customer_id' => $customer->id,
"cash" => $data['value'],
"note" => $data['note'],
'sts' => 4,
]);
new TransactionInterface($wallet_interface, $_inp = [
'gold' => 0,
'cash' => $data['value'],
'expire_at' => now(),
"note" => $data['note'],
'withdraw_id' => $Withdraw->id,
'active' => true
], 7, true, $deposit, $gold_block);
$data['direction'] = 0;
// $tahesab = new TahesabController();
// $tahesab->wallet($data);
$message = 'کیف پول شما به اندازه ' . number_format($data['value']) . " ریال در تاریخ " . verta()->format('Y/n/j H:i:s') . " اصلاح شد بابت" . "\n"
. $data['note']
. " "
. $this->Config('name_fa');
$this->Send($customer->mobile, $message);
return response()->json(true);
}
public function charge_gold(Request $request)
{
$data = $request->all();
$customer = Customer::findOrFail($data['customer_id']);
$deposit = false;
if ($data['value'] > 0) {
$deposit = true;
}
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
// if (is_null($wallet) && !$deposit) {
// throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
// }
// if (!is_null($wallet) && $wallet->cash < abs($data['value']) && !$deposit) {
// throw new UnprocessableEntityHttpException('مقدار موجودی کمتر از درخواست شماست');
// }
$wallet_interface = new WalletInterface($data['customer_id'], $customer->type);
$gold_block = 0;
$user = auth()->user();
$customer = Customer::findOrFail($data["customer_id"]);
$Withdraw = Withdraw::create([
'user_id' => $user->id,
'customer_id' => $customer->id,
"gold" => $data['value'],
"note" => $data['note'],
'sts' => 4,
]);
new TransactionInterface($wallet_interface, $_inp = [
'cash' => 0,
'gold' => $data['value'],
'expire_at' => now(),
"note" => $data['note'],
'withdraw_id' => $Withdraw->id,
'active' => true
], 7, $deposit, false, $gold_block);
$message = 'کیف پول شما به اندازه ' . $data['value'] . " گرم در تاریخ " . verta()->format('Y/n/j H:i:s') . " شارژ شد بابت" . "\n"
. $data['note']
. $this->Config('name_fa');
$this->Send($customer->mobile, $message);
return response()->json(true);
}
public function index(Request $request)
{
$records = Transaction::with(['customer'])->whereNull('fund_id');
TableEngine::create($records, $request->all())
->initSearch(['order_id', 'customer.name'])
->select([
'*', Transaction::$SELECT_CAJ, Transaction::$SELECT_TYPE_STR, Transaction::$SELECT_SAJ, Transaction::$SELECT_EAJ
])->export($records);
// foreach ($records['rows'] as &$record) {
// if (empty($record->title) or $record->title == "تعریف نشده"){
// $record->title = $record->type_str ;
// $record->unit = "گرم";
// if (isset($record->wallet)) {
// $wallet = Wallet::with('product')->where('id',$record->wallet)->first();
// if (isset($wallet->product)) {
// if ($record->gold > 0){
// $record->title = " خرید " ;
//
// }else{
// $record->title = " فروش " ;
//
// }
// $record->title .= $wallet->product->title ;
// $record->unit = "عدد";
//
// }
// }
// $record->save();
// }
//
// }
return response()->json($records);
}
public function updateTransaction(Request $request)
{
$message = 'تراکنش تغیری نکرده.';
$transaction = Transaction::find($request->id);
$product = Product::find($transaction->product_id);
if (!$transaction) return response()->json(['error' => 'تراکنش یافت نشد.'], 404);
$difference = $request->input('number') - $transaction->number;
if (abs($difference) < 0.0001) {
return response()->json(['message' => $message], 422);
}
$transaction->number = $request->input('number');
$wallet_interface = new WalletInterface($transaction->customer_id, 2);
if ($wallet_interface->wallet->gold < $difference ) {
if (!(isset($request->force) && $request->force === true)){
return response()->json(['message' => "کاربر مورد نظر موجودی ندارد. موجودی فعلی: " . $wallet_interface->wallet->gold . " مقدار مورد نیاز: " . $difference,'type'=>406],422);
}
}
$isDiposit = $difference > 0 ? 0 : 1;
new TransactionInterface($wallet_interface, [
"title" => "اصلاح سند " . $transaction->withdraw_id,
"note" => $product->title,
"product_id" => $product->id,
"number" => 0,
"gold" => $difference,
'expire_at' => now(),
'active' => true,
'withdraw_id' => $transaction->withdraw_id,
'start_at' => now(),
], 51, $isDiposit, false);
$transaction->save();
$message = 'تراکنش با موفقیت به‌روزرسانی شد.';
return response()->json([
'message' => $message,
'transaction' => $transaction,
// 'previous_amount' => $previousAmount,
// 'new_amount' => $newAmount,
'difference' => $difference,
'wallet' => $wallet_interface->wallet,
]);
}
public function indexWallet(Request $request)
{
// محاسبه‌ی مجموع gold و cash به ازای هر owner
$records = Wallet::with('customer');
// ایجاد جدول با استفاده از TableEngine
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select(['*'])
->export($records);
// محاسبه‌ی قیمت آخرین قیمت و مجموع کلی مقادیر gold و cash
$lastPrice = Price::latest()->first()->price;
$walletQuery = Wallet::where('owner', '!=', 4)->where('product_id', null);
$sums = [
"gold" => round($walletQuery->sum('gold'), 2),
"goldToCash" => round($walletQuery->sum('gold') * $lastPrice, 2),
"cash" => round($walletQuery->sum('cash'), 2),
"cashToGold" => round($walletQuery->sum('cash') / $lastPrice, 2),
];
// $sums = [
// "gold" => round(Wallet::whereNot('owner', 4)->sum('gold'), 2),
// "goldToCash" => round(Wallet::sum('gold') * $lastPrice, 2),
// "cash" => round(Wallet::sum('cash'), 2),
// "cashToGold" => round(Wallet::sum('cash') / $lastPrice, 2),
// "on" => $lastPrice,
// ];
// افزودن sums به records
$records['sums'] = $sums;
return response()->json($records);
}
public function indexWithdraw(Request $request)
{
$records = Withdraw::with(['customer', 'bank_account', 'Address', "Transaction"]);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*', Withdraw::$SELECT_STS_STR, Withdraw::$SELECT_DAJ
])->export($records);
return response()->json($records);
}
public function updateWithdraw(Request $request, $id)
{
// پیدا کردن رکورد Withdraw با استفاده از شناسه
$withdraw = Withdraw::find($id);
// بررسی وجود رکورد
if (!$withdraw) {
return response()->json(['error' => 'Withdraw not found'], 404);
}
$withdraw->sts = $request->sts;
$withdraw->save();
return response()->json(['message' => 'Withdraw updated successfully', 'withdraw' => $withdraw]);
}
public function getWithdraw(Request $request, $id)
{
// پیدا کردن رکورد Withdraw با استفاده از شناسه
return $withdraw = Withdraw::with(['customer', 'bank_account', 'Address', "Transaction"])->find($id);
// بررسی وجود رکورد
if (!$withdraw) {
return response()->json(['error' => 'Withdraw not found'], 404);
}
$withdraw->sts = $request->sts;
$withdraw->save();
return response()->json(['message' => 'Withdraw updated successfully', 'withdraw' => $withdraw]);
}
public function completeWithdraw(Request $request)
{
$data = $request->all();
$data['user_id'] = auth('user')->id();
$data['sts'] = 2;
$data['date_at'] = now();
Withdraw::findOrFail($data['id'])->update($data);
$withdraw = Withdraw::findOrFail($data['id']);
$withdraw->update($data);
// $tahesab = new TahesabController();
// $tahesab->wallet([
// 'customer_id' => $withdraw->customer_id,
// 'value' => $withdraw->cash,
// 'direction' => 1,
// 'note' => 'برداشت از کیف پول شماره ' . $withdraw->id,
// ]);
return response()->json(true);
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\Cnt;
use App\Models\Customer;
use App\Models\TahesabCustomer;
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)
{
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('error.no_active'));
}
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('شما اجازه ورود به سیستم را ندارید');
}
$rand = rand(1000, 9999);
$user->token_sms = $rand;
$user->save();
// $this->SendMessage($mobile, 'رمز عبور یکبار مصرف شما جهت ورود به اپلیکشن ' . $this->Config('name_fa') . ' ' . $rand . ' می باشد' . PHP_EOL . "@$subDomain" . " #" . $rand,true ,"sms");
$this->SendMessage($mobile, 'رمز عبور یکبار مصرف شما جهت ورود به اپلیکشن ' . $this->Config('name_fa') . ' ' . $rand . ' می باشد' . PHP_EOL . "@samin.gold" . " #" . $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);
}
throw new UnprocessableEntityHttpException(trans('error.wrong_code'));
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL()
]);
}
public function register(Request $request)
{
$data = $request->all();
$data['type'] = 2;
if (isset($data['referral_id'])) {
$data['referral_to_id'] = $data['referral_id'];
}
$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;
}
// Generate unique referral ID
do {
$uniqueId = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 4);
} while (Customer::where('referral_id', $uniqueId)->exists());
$data['referral_id'] = $uniqueId;
// Handle referrer
if (isset($data['referral_to_id'])) {
$referrer = Customer::where('referral_id', $data['referral_to_id'])->first();
if ($referrer) {
// $messageRef = "{$data['name']} با کد معرف شما ثبت نام کرد.\nدر صورت احراز او پاداش می‌گیرید.\n" . $this->Config('name_fa');
// $this->Send($referrer->mobile, $messageRef);
$AdminMessage = "با معرفی {$referrer->name}، کاربر {$data['name']} در اپ {$this->Config('name_fa')} ثبت نام کرده و منتظر تایید شماست.";
User::where('send_sms', 1)->get()->each(function ($admin) use ($AdminMessage, $data,) {
$this->send($admin->mobile, $AdminMessage);
});
} else {
return response()->json(["message" => "کد نامعتبره"], 422);
}
} else {
if ($this->Config('referral_id') == "required") {
return response()->json(["message" => "کد معرف اجباریست"], 422);
}
}
$data['active'] = false;
// Create customer
$customer = Customer::create($data);
$message = "{$data['name']} عزیز، اکانت شما در پلتفرم {$this->Config('name_fa')} ایجاد شد.\nنام کاربری: {$data['mobile']}\n\nورود به نرم افزار:\n{$this->Config('app_url')}";
$this->Send($data['mobile'], $message);
return response()->json($customer);
}
}
+161
View File
@@ -0,0 +1,161 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Customer;
use App\Models\Setting;
use App\Models\Message;
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;
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 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 SendMessage($to, $msg ,$is_send = false,$force_method ='null')
{
$config = config('message', false);
$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) {
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',
]);
$platforms[] = "0098:{$to}";
}
// 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' => "جناب {$user->name} {$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' => "جناب {$user->name} {$msg}",
]);
$platforms[] = "bale:{$user->bale}";
$send_sms = false;
} catch (\Exception $e) {
}
}
}
Message::create([
'sms' => $msg,
'receiver' => $to,
'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, "botToken" => 'Paramisgold_bot']);
return $response->json();
}
public static function Config($name)
{
return Setting::where('key',$name)->first()->value ?? false;
//
// return $settings = collect(Setting::all())
// ->mapWithKeys(function ($s) {
// return [$s['key'] => $s['value']];
// })->firstWhere('key', $name)['value'] ?? false;
// return $settingValue = $settings->firstWhere('key', $name)['value'] ?? false;
//
// if (!$settingValue) {
// $subs = collect(Http::withToken('')->get('https://pm.gholaktala.ir/config/'.strtr($_SERVER['SERVER_NAME'], '.', '_'))->json()['subs'])
// ->firstWhere('name', $name)['value'] ?? false;
//
// return $subs;
// }
//
// return $settingValue;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\Address;
use Illuminate\Http\Request;
class AddressController extends SuperController
{
public function __construct(Request $request)
{
$request->request->add(['customer_id'=>auth('customer')->id()]);
$address = Address::where('customer_id',auth('customer')->id());
parent::__construct(Address::class, [], ['*'],null,$address);
}
}
+267
View File
@@ -0,0 +1,267 @@
<?php
namespace App\Http\Controllers\Customer;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Admin\CustomerController as adm_cu;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Customer;
use App\Models\User;
use App\Models\TransactionsAdmin;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Wallet;
use Rooyesh\Wallet\models\Transaction;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
//use App\Models\Price;
//use Carbon\Carbon;
//use Illuminate\Support\Facades\Http;
class CustomerController extends Controller
{
public function me()
{
$user = Customer::findOrFail(auth('customer')->id());
$wallet = Wallet::where('owner', $user->id)
->where('owner_type', $user->type)
->whereNull('fund_id')
->first() ?? new Wallet();
$wallet->gold_ab = round(Wallet::where('owner', $user->id)->where('product_id', null)->sum('gold'), 2);
$wallet->wp = Wallet::with('product')->where('owner', $user->id)->get();
foreach ($wallet->wp as $row){
if ($row->product_id != null){
$wallet->treasure +=$row->product->amount*$row->gold;
}
$wallet->treasure_sum =$user->gold+$wallet->treasure;
}
$wallet->gold_sum = $wallet->treasure_sum+$wallet->gold_ab;
$user->wallets = Wallet::with(['product'])->where('owner', $user->id)->get() ?? new Wallet();
$count_gold =0;
$count_cash =0;
$count_product =0;
foreach ($user->wallets as $walletSingle) {
if ($walletSingle->product_id) {
if (!($walletSingle->product->group_type == "سکه")){
(float)$count_gold += $walletSingle->product->amount*$walletSingle->gold;
}
$count_cash += $walletSingle->product->price*$walletSingle->gold;
$count_product += $walletSingle->gold;
} else {
(float)$count_gold += $walletSingle->gold;
(float)$count_cash += $walletSingle->cash;
$wallet->count_cash_wallet = $walletSingle->cash;
$wallet->count_gold_wallet = $walletSingle->gold;
}
}
$wallet->count_cash_wallets = $count_cash-$wallet->count_cash_wallet;
$wallet->count_gold_wallets = $count_gold-$wallet->count_gold_wallet;
$wallet->count_gold = $count_gold;
$wallet->count_cash = $count_cash;
$wallet->count_product = $count_product;
$user->wallet = $wallet;
$user->pwallet = Wallet::with("product")->where('owner', $user->id)
->where('owner_type', $user->type) // Ensures the wallet's owner type matches the user's type
->whereNotNull('product_id') // Filters wallets that have a non-null product_id
->get() ?? new Wallet(); // If no wallet is found, assigns a new Wallet instance to the attribute
return response()->json($user);
}
public function updateMe(Request $request)
{
try {
$customer = Customer::findOrFail(auth('customer')->id());
$updateData = $request->except(['referral_id', 'referral_to_id']);
if (isset($request->fname) && isset($request->lname)) {
$updateData['name'] = "$request->fname $request->lname";
}
if ($request->has('credential_id')) {
$updateData['credential_id'] = $request->credential_id;
}
$customer->update($updateData);
if (!$customer->is_legal) {
$response = Http::withHeaders([
'Authorization' => 'Bearer mob83EBzqU7GWBmnc-6gXIp6r2G57P_94',
'Content-Type' => 'application/json',
])->post('http://185.97.116.24:20205/check_user', [
'number' => $customer->mobile,
'national' => $customer->n_code,
'host' => $_SERVER['HTTP_HOST'],
]);
if (isset($response['matched']) and $response['matched'] == true) {
$customer->is_legal = 1;
$customer->save();
if ($this->Config('has_page_earn_money') == true) {
$gift_for_inviter = 0.002;
$gift_for_invited = 0.003;
$companyName = $this->Config('name_fa');
$companyurl = $this->Config('app_url');
$referrer = $customer->referral;
if (Customer::where('referral_to_id', $referrer->referral_id)->get()->count() <= $referrer->add_user_limit) {
$Withdraw = Withdraw::create([
'user_id' => $customer->id,
'customer_id' => $customer->referral->id,
"cash" => 0,
"gold" => $gift_for_invited,
'sts' => 5,
]);
$wallet_interface = new WalletInterface($customer->referral->id, 2);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => 0,
"gold" => $gift_for_invited,
'expire_at' => now(),
'active' => true,
'title' => 'پاداش بابت معرفی',
'withdraw_id' => $Withdraw->id,
'start_at' => now(),
], 8, true, false);
$transaction = Transaction::where('customer_id', $customer->referral->id)->latest()->first();
TransactionsAdmin::create([
'customer_id' => $customer->id,
'customer_to_id' => $customer->referral->id,
'user_id' => $customer->id,
'wallet' => null, // یا مقدار مناسب دیگری
'transaction_id' => $transaction->id,
'cash' => 0,
'note' => 'پاداش بابت معرفی',
'type' => 1, // یا مقدار مناسب دیگری
'gold' => $gift_for_invited,
'balance_cash' => 0, // یا مقدار مناسب دیگری
'withdraw_id' => $Withdraw->id,
]);
$referrerWallet = Wallet::where('owner', $customer->referral->id)->first();
$message = "سلام {$referrer->name} عزیز،\n\n{$gift_for_invited} گرم طلا بابت معرفی {$customer->name} به حساب شما واریز شد.\nموجودی فعلی: {$referrerWallet->gold} گرم.\n\nاطلاعات بیشتر: $companyurl\n\nبا احترام،\n$companyName";
$this->Send($referrer->mobile, $message);
}
$Withdraw = Withdraw::create([
'user_id' => $customer->id,
'customer_id' => $customer->id,
"cash" => 0,
"gold" => $gift_for_inviter,
'sts' => 5,
]);
$wallet_interface = new WalletInterface($customer->id, 2);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => 0,
"gold" => $gift_for_inviter,
'expire_at' => now(),
'active' => true,
'title' => 'پاداش بابت ثبت نام',
'withdraw_id' => $Withdraw->id,
'start_at' => now(),
], 8, true, false);
$transaction = Transaction::where('customer_id', $customer->id)->latest()->first();
TransactionsAdmin::create([
'customer_id' => $customer->id,
'customer_to_id' => $customer->id,
'user_id' => $customer->id,
'wallet' => null, // یا مقدار مناسب دیگری
'transaction_id' => $transaction->id,
'cash' => 0,
'note' => 'پاداش بابت ثبت نام',
'type' => 1, // یا مقدار مناسب دیگری
'gold' => $gift_for_inviter,
'balance_cash' => 0, // یا مقدار مناسب دیگری
'withdraw_id' => $Withdraw->id,
]);
$referrerWallet = Wallet::where('owner', $customer->id)->first();
$message = "سلام " . $customer->name . " عزیز،\n\n" . $gift_for_invited . " گرم طلا بابت ثبت نام " . " به حساب شما واریز شد.\n" . "موجودی فعلی: " . $referrerWallet->gold . " گرم.\n\n" . "اطلاعات بیشتر: " . $companyurl . "\n\n" . "با احترام،\n" . $companyName;
$this->Send($customer->mobile, $message);
}
} else {
// This block will handle the case where the code doesn't match
// if (isset($response['code']) and $response['code'] === 'mobileNumber.not_valid') {
// return response()->json(['message' => "کد ملی تطابق ندارد",'response' =>$response], 422);
// } else {
// // This block will handle other errors from the $response variable
// return response()->json(['response' => $response], 422);
// }
return response()->json(['message' => "کد ملی ثبت شد، اما در حال حاضر سیستم نتوانست آن را تأیید کند. لطفاً منتظر بررسی و تأیید مدیر بمانید.",'response' =>$response], 422);
}
}
return response()->json(true);
} catch (\Exception $e) {
// نمایش 400 کاراکتر اول از پیام خطا
$errorMessage = substr($e->getMessage(), 0, 400);
return response()->json(['error' => $errorMessage], 500);
}
}
public function active_finger()
{
$customer = Customer::findOrFail(auth('customer')->id());
if ($customer->finger_print) {
$customer->finger_print = false; // Set to false if currently true
} else {
$customer->finger_print = true; // Set to true if currently false
}
$customer->save();
return response()->json($customer);
}
public function imFrom($code)
{
$referrer = Customer::where('referral_id', $code)->first();
if ($referrer) {
// Define the reward amount
$rewardAmount = 200000; // Adjusted reward amount as per the new requirement
// Update the referred customer with the referral code
$newCustomer = auth('customer')->user(); // Assuming the new customer is authenticated
$newCustomer->referral_id = $code;
$newCustomer->save();
// Construct the SMS message
$message = sprintf(
"%s با کد معرف شما ثبت نام کرد.\nکیف پول شما %d ریال به عنوان پاداش شارژ شد.\n%s",
$newCustomer->name,
$rewardAmount,
$this->Config('name_fa')
);
// Send SMS to the referrer
$this->Send($referrer->mobile, $message);
return response()->json(['message' => 'Referral reward processed and SMS sent to referrer.'], 200);
} else {
return response()->json(['error' => 'کد نامعتبر میباشد'], 422);
}
}
public function i_have(Request $request)
{
$user = auth('customer')->user();
$customer_referral_id = Customer::where("id", $user['id'])->first()->referral_id;
$return['users'] = Customer::where("referral_to_id", $customer_referral_id)->get();
$return['gifts'] = TransactionsAdmin::with(['withdraw', 'order', "user", 'customerTo', 'customer'])->where("customer_to_id", $user->id)->get();
$return['usersSum'] = $return['users']->count();
$return['giftsSum'] = number_format($return['gifts']->sum('gold'), 3);
return response()->json($return);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers\Customer;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\Fund;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class FundController extends SuperController
{
public function __construct(Request $request)
{
$model = Fund::class;
$this->with=['wallet'];
$select = ['*'];
$search=['name'];
$request->request->add(['customer_id'=>auth('customer')->id()]);
$query = Fund::with($this->with)->where('customer_id',auth('customer')->id());
parent::__construct($model, $this->with, $select, null,$query,$search);
}
public function deposit(Request $request){
$data = $request->all();
$wallet_interface = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,null);
$wallet = $wallet_interface->wallet;
if($wallet->gold < $data['value']){
throw new UnprocessableEntityHttpException('موجودی کمتر از مقدار وارد شده است');
}
$transaction = new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 6, false);
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,$data["fund_id"]);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 5, true);
return response()->json(true);
}
public function withdraw(Request $request){
$data = $request->all();
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,$data["fund_id"]);
$wallet = $wallet_interface_fund->wallet;
if($wallet->gold < $data['value']){
throw new UnprocessableEntityHttpException('موجودی کمتر از مقدار وارد شده است');
}
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 6, false);
$wallet_interface = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
$transaction = new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 5, true);
return response()->json(true);
}
public function show($id){
$query = Fund::with($this->with)->findOrFail($id);
return response()->json($query);
}
public function destroy($id){
$wallet_interface_fund = Wallet::where('owner',auth('customer')->id())->where('fund_id',$id)->first();
if (!is_null($wallet_interface_fund)){
if ($wallet_interface_fund->gold > 0){
throw new UnprocessableEntityHttpException('به علت داشتن موجودی امکان حذف صندوق وجود ندارد');
}
}
Fund::destroy($id);
return response()->json(true);
}
public function transactionTable(Request $request){
$records = Transaction::where('wallet',$request->wallet_id);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*',Transaction::$SELECT_CAJ,Transaction::$SELECT_TYPE_STR
])->export($records);
return response()->json($records);
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace App\Http\Controllers\Customer;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Jobs\CheckOrder;
use App\Models\Order;
use App\Models\Price;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class OrderController extends Controller
{
public function store(Request $request){
$user= auth()->user();
if ($user->is_legal == 0 or $user->id==4) {
return response()->json(['massage' => 'شما باید اول خود را احراز هویت کنید'], 422);
}
// if ()
$data = $request->all();
$data['customer_id'] = auth('customer')->id();
$data['sts'] = 2;
$data['payment_sts'] = 4;
$PriceMain = Price::orderBy('id','desc')->first();
$data['price'] = $PriceMain->price;
$add_sell_price = config('add_sell_price.major');
$customer = auth('customer')->user();
if (!auth('customer')->user()->trade_active){
throw new UnprocessableEntityHttpException('امکان سفارش برای شما غیرفعال است.');
}
$wallet = Wallet::where('owner',auth('customer')->id())->whereNull('fund_id')
->first();
$wallet_interface = new WalletInterface($data['customer_id'], 1);
if ($data['direction'] == 1){
// $order = Order::where('customer_id',auth('customer')->id())->where('sts',1)->first();
// if (!is_null($order)){
// throw new UnprocessableEntityHttpException('شما یک سفارش باز دارید,ابتدا نسبت به تسویه آن اقدام نمایید و مجددا تلاش کنید');
// }
$gold_block = 0;
$data['price_original'] = $data['price'];
$data['total_price_original'] = $data['amount']* $data['price_original'];
$data['price'] += $add_sell_price;
$data['total_price'] = $data['amount']* $data['price'];
$data['payment_remind'] = 0;
$data['payment_amount'] = $data['total_price'];
$data['fee'] = $add_sell_price;
$data['total_fee'] = $data['amount']* $data['fee'];
if ($wallet->cash < $data['total_price']){
if ($data['amount'] > $customer->gram){
throw new UnprocessableEntityHttpException('مقدار وارد شده بیش از سقف اعتبار شماست');
}
$data['sts'] = 1;
$data['payment_remind'] = $data['total_price'];
$data['payment_amount'] = 0;
$gold_block = $data['amount'];
}
$data['price_id'] = $PriceMain->id;
$order = Order::create($data);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => $data['total_price'],
"gold"=> $data['amount'],
'expire_at'=>now(),
'active'=>true,
'order_id'=>$order->id,
'start_at'=>now(),
'end_at'=>now()->addDay()
], 1, true,false,$gold_block);
if ($data['sts'] == 1){
CheckOrder::dispatch($order->id)->onConnection('database')->delay(now()->addMinutes(5));
}
$message = auth('customer')->user()->name." عزیز" ."\n"
.'در تاریخ '.verta()->format('Y/n/j H:i:s')." کیف طلایی شما "."\n"
.$data['amount']." گرم شارژ شد"."\n"
."با تشکر".$this->Config('name_fa');
}else{
$data['price_original'] = $data['price'];
$data['total_price_original'] = $data['amount']* $data['price_original'];
$data['price'] -= $add_sell_price;
$data['total_price'] = $data['amount']* $data['price'];
$data['payment_remind'] = 0;
$data['payment_amount'] = $data['total_price'];
$data['fee'] = $add_sell_price;
$data['total_fee'] = $data['amount']* $data['fee'];
if (($wallet->gold - $wallet->gold_block) < $data['amount']){
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
$order = Order::create($data);
new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['amount'],
"cash" => $data['total_price'],
'expire_at'=>now(),
'active'=>true,
'order_id'=>$order->id
], 2, false,true);
$message = auth('customer')->user()->name." عزیز" ."\n"
.'در تاریخ '.verta()->format('Y/n/j H:i:s')." کیف طلایی شما "."\n"
.$data['amount']." گرم کم شد"."\n"
."با تشکر".$this->Config('name_fa');
}
$this->Send(auth('customer')->user()->mobile,$message);
return response()->json($order);
}
public function table(Request $request){
$records = Order::where('customer_id',auth('customer')->id())
->where('type',1);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*',Order::$SELECT_STS_STR
])->export($records);
return response()->json($records);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\SuperController;
use Illuminate\Http\Request;
use App\Models\PriceTrigger; // اطمینان حاصل کنید که این مدل به درستی وارد شده است
class PriceTriggerController extends SuperController
{
public function __construct(Request $request)
{
$request->request->add(['customer_id'=>auth('customer')->id()]);
$model = PriceTrigger::class;
$this->with = ['customer'];
$this->select = ['*'];
$this->search = ['*'];
parent::__construct($model, $this->with, $this->select);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$data=PriceTrigger::where("customer_id",auth()->id())->get();
return response()->json($data);
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Http\Controllers\Customer;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\Fund;
use App\Models\Product;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class ProductController extends SuperController
{
public function __construct(Request $request)
{
$model = Product::class;
$this->with=['wallet'];
$select = ['*'];
$search=['name'];
$request->request->add(['customer_id'=>auth('customer')->id()]);
$query = Product::with($this->with);
parent::__construct($model, $this->with, $select, null,$query,$search);
}
public function pTable(Request $request)
{
$user = auth('customer')->user();
// $products = Product::with(['wallet' => function ($query) use ($user) {
// $query->where('owner', $user->id);
// }])->get();
$products = Product::whereHas('wallet', function ($query) use ($user) {
$query->where('owner', $user->id);
})->with(['wallet' => function ($query) use ($user) {
$query->where('owner', $user->id);
}])->get();
// Prepare the response
$user['rows'] = $products;
return response()->json($user);
}
public function deposit(Request $request){
$data = $request->all();
$wallet_interface = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,null);
$wallet = $wallet_interface->wallet;
if($wallet->gold < $data['value']){
throw new UnprocessableEntityHttpException('موجودی کمتر از مقدار وارد شده است');
}
$transaction = new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 6, false);
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,$data["fund_id"]);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 5, true);
return response()->json(true);
}
public function withdraw(Request $request){
$data = $request->all();
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type,$data["fund_id"]);
$wallet = $wallet_interface_fund->wallet;
if($wallet->gold < $data['value']){
throw new UnprocessableEntityHttpException('موجودی کمتر از مقدار وارد شده است');
}
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 6, false);
$wallet_interface = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
$transaction = new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['value'],
"fund_id"=>$data["fund_id"],
'expire_at'=>now(),
'active'=>true
], 5, true);
return response()->json(true);
}
public function show($id){
$query = Product::/*with(['walletMy as wallet'])->*/findOrFail($id);
$query['wallet']= $query->walletMy;
return response()->json($query);
}
public function destroy($id){
$wallet_interface_fund = Wallet::where('owner',auth('customer')->id())->where('fund_id',$id)->first();
if (!is_null($wallet_interface_fund)){
if ($wallet_interface_fund->gold > 0){
throw new UnprocessableEntityHttpException('به علت داشتن موجودی امکان حذف صندوق وجود ندارد');
}
}
Fund::destroy($id);
return response()->json(true);
}
public function transactionTable(Request $request){
$records = Transaction::where('wallet',$request->wallet_id);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*',Transaction::$SELECT_CAJ,Transaction::$SELECT_TYPE_STR
])->export($records);
return response()->json($records);
}
}
+319
View File
@@ -0,0 +1,319 @@
<?php
namespace App\Http\Controllers\Customer;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Customer;
use App\Models\Order;
use App\Models\User;
use App\Models\Withdraw;
use App\Models\BankAccount;
use App\Models\Price;
use App\Http\Controllers\Admin\TahesabController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class WalletController extends Controller
{
public function withdrawTable(Request $request)
{
$records = Withdraw::with(['transaction'])->where('customer_id', auth('customer')->id())->whereIn('sts', [2,1])->orderBy('id','desc');
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Withdraw::$SELECT_STS_STR,Withdraw::$SELECT_DAJ
])->export($records);
return response()->json($records);
}
public function walletMe()
{
$wallet = Wallet::select(['owner', 'id', 'gold', 'cash'])->where('owner', auth('customer')->id())
->first();
// $wallet['gold_sum'] = Wallet::where('owner', auth('customer')->id())->get();
$wallet['gold_sum'] = round(Wallet::where('owner', auth('customer')->id())->where('product_id', null)->sum('gold'), 2);
return response()->json($wallet);
}
public function priceData(Request $request)
{
return $response = Http::get('https://milli.gold/api/v1/public/milli-price/widget/external');
$prise = Price::with('order');
TableEngine::create($prise, $request)
->initSearch(['price'])
->select(['*'])
->export($prise);
return response()->json($prise);
}
public function transactionTable(Request $request)
{
if (isset($request->wallet_id)){
$wallet = Wallet::with('product')->where('id', $request->wallet_id)->where('owner', auth('customer')->id())->get();
}else{
$wallet = Wallet::with('product')->where('owner', auth('customer')->id())->get();
}
if ($wallet->isEmpty()) {
$records = ['query' => ['total' => 0], 'rows' => []];
} else {
$records = Transaction::with([
'order' => function ($q) {
$q->select(['*', Order::$SELECT_STS_STR]);
},
'withdraw' => function ($q) {
$q->select(['*', Order::$SELECT_STS_STR]);
},
'wallet.product'
])->whereIn('wallet', $wallet->pluck('id'))->whereNull('fund_id');
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*', Transaction::$SELECT_CAJ, Transaction::$SELECT_TYPE_STR, Transaction::$SELECT_SAJ, Transaction::$SELECT_EAJ
])->export($records);
}
foreach ($records['rows'] as &$record) {
if (empty($record->title) or $record->title == "تعریف نشده"){
$record->title = $record->type_str ;
$record->unit = "گرم";
if (isset($record->wallet)) {
$wallet = Wallet::with('product')->where('id',$record->wallet)->first();
if (isset($wallet->product)) {
if ($record->gold > 0){
$record->title = " خرید " ;
}else{
$record->title = " فروش " ;
}
$record->title .= $wallet->product->title ;
$record->unit = "عدد";
}
}
$record->save();
}
}
return response()->json($records);
}
public function transactionTableb(Request $request)
{
$wallet = Wallet::with('product')->where('owner', auth('customer')->id())->whereNull('fund_id')->get();
if (is_null($wallet)) {
$records = ['query' => ['total' => 0], 'rows' => []];
} else {
$records = Transaction::with(['order' => function ($q) {
return $q->select(['*', Order::$SELECT_STS_STR]);
}, 'withdraw' => function ($q) {
return $q->select(['*', Order::$SELECT_STS_STR]);
}, 'wallet.product'])->whereIn('wallet', $wallet->pluck('id'))->whereNull('fund_id');
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*', Transaction::$SELECT_CAJ, Transaction::$SELECT_TYPE_STR, Transaction::$SELECT_SAJ, Transaction::$SELECT_EAJ
])->export($records);
}
foreach ($records['rows'] as &$record) {
return $record['wallet'];
if (isset($record->wallet->product->title)) {
$record->title = $record->wallet->product->title."22";
$record->save();
} else {
$record->title = $record->type_str."22";
$record->save();
}
}
return response()->json($records);
}
public function withdraw(Request $request)
{
$customer = auth('customer')->user();
$data = $request->all();
if (!isset($data['card_id'])) {
return response()->json(['message' => 'کارت انتخاب نشده'], 422);
}
$bCart = BankAccount::where('id', $data['card_id'])->first();
if ($bCart->sts != 2) {
return response()->json(['message' => 'کارت انتخاب شده غیر فعال است یا ردشده'], 422);
}
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
$wallet = $wallet_interface_fund->wallet;
if ($data['value'] < 0) {
throw new UnprocessableEntityHttpException('مقدار برداشت باید مثبت باشد');
}
if ($data['value'] > $wallet->cash) {
throw new UnprocessableEntityHttpException('مقدار برداشت بیشتر از موجودی است');
}
$Withdraw = Withdraw::create([
'customer_id' => auth('customer')->id(),
"cash" => $data['value'],
"note" => "برداشت ریالی",
"bank_account_id" => $data['card_id'],
'sts' => 1,
'type' => 2
]);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"cash" => $data['value'],
'expire_at' => now(),
'withdraw_id' => $Withdraw->id,
'active' => true
], 4, false, false);
$userMobile = $customer->mobile; // User's mobile number
$userName = $customer->name; // User's name
$withdrawAmount = $data['value']; // amount
$tahesab = new TahesabController();
$tahesab->wallet([
"customer_id" => auth('customer')->id(),
"value" => $data['value'],
"direction" => 1,
]);
$companyName = $this->Config('name_fa'); // Company name from configuration
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ریال را دارد. با تشکر، $companyName";
if (isset($request->otp)) {
if (Customer::where("id", $customer->id)->first()->token_sms != $request->otp) {
return response()->json(['message' => 'رمز دوم اشتباه میباشد'], 422);
}
try {
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->Config('liman_token')
])->post('https://limangold.ir/kernel/customer/fin', [
'receive_bank_shaba' => $bCart->shaba_number,
'receive_bank_card' => $bCart->cart_number,
'receive_name' => $customer->name,
'receive_account_number' => $bCart->account_number,
'description' => $this->Config('name_fa') . ' | ' . $customer->mobile . ' | ' . $customer->name . ' | ' . $Withdraw->id,
'amount' => '1000'
])->json();
if (isset($response['id'])) {
$Withdraw->note = $response['id'];
$Withdraw->save();
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ثبت کرد و به لیمان منتقل شد. با تشکر، $companyName";
} else {
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ریال را دارد (مشکل در اتصال به لیمان). با تشکر، $companyName";
}
} catch (Exception $e) {
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ریال را دارد (مشکل در اتصال به لیمان). با تشکر، $companyName";
}
}
User::where('send_sms', 1)->get()->each(function ($admin) use ($message) {
$this->Send($admin->mobile, $message . ' ' . now()->format('H:i:s'));
});
return response()->json($Withdraw);
}
public function withdraw_physical(Request $request)
{
$data = $request->all();
$data['customer'] = Customer::with([/*"wallet"*/])->where('id', auth('customer')->id())->first();
$data['customer']['wallet_interface'] = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
if (!isset($data['address_id'])) {
return response()->json(['message' => 'آدرس انتخاب نشده است'], 422);
}
$data['adress'] = Address::find($data['address_id']);
if (!$data['adress'] || $data['adress']->customer_id != $data['customer']->id) {
return response()->json(['message' => 'آدرس معتبر نیست یا متعلق به شما نمی‌باشد'], 403);
}
foreach ($data['wallets'] as $key => $wallet) {
$data['wallets'][$key]['wallet'] = Wallet::with(["product"])->find($wallet['wallet_id']);
if (!$data['wallets'][$key]['wallet']) {
return response()->json(['message' => 'ولت مورد نظر یافت نشد.'], 422);
}
if ($data['wallets'][$key]['wallet']->owner != $data['customer']['id']) {
return response()->json(['message' => 'ولت انتخاب شده متعلق به شما نمی‌باشد.'], 422);
}
// بررسی وجود محصول در ولت
if (!$data['wallets'][$key]['wallet']['product']) {
return response()->json(['message' => 'محصولی در ولت مورد نظر یافت نشد.'], 422);
}
if ($data['wallets'][$key]['value'] > $data['wallets'][$key]['wallet']['gold']){
return response()->json([
'message' => "شما به اندازه کافی از {$data['wallets'][$key]['wallet']['product']['title']} ندارید"
], 422);
}
if ($data['wallets'][$key]['value'] == 0) {
return response()->json([
'message' => "مقدار انتخابی نمی‌تواند صفر باشد. لطفاً مقدار صحیحی را برای {$data['wallets'][$key]['wallet']['product']['title']} وارد کنید."
], 422);
}
$data['wallets'][$key]['wallet_interface'] = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $data['wallets'][$key]['wallet']["product_id"]);
}
$data['withdraw'] = new Withdraw(); // Create a new instance of the Withdraw model
$data['withdraw']->note = "برداشت فیزیکی"; // 50 for phisicals
$data['withdraw']->address_id = $data['address_id'];
$data['withdraw']->customer_id = $data['customer']['id'];
$data['withdraw']->sts = 50;
$data['withdraw']->save();
foreach ($data['wallets'] as $key => $wallet) {
$data['wallets'][$key]['transaction'][] = new TransactionInterface($data['wallets'][$key]['wallet_interface'], $_inp = [
"gold" => $data['wallets'][$key]['value'],
"number" => $data['wallets'][$key]['wallet']['product']['amount']*$data['wallets'][$key]['value'],
"product_id" => $data['wallets'][$key]['wallet']['product']['id'],
'expire_at' => now(),
'active' => true,
'title' => " برداشت {$data['wallets'][$key]['wallet']['product']['title']}",
'note' => " برداشت محصول {$data['wallets'][$key]['wallet']['product']['title']} شماره سند {$data['withdraw']->id}",
'withdraw_id' => $data['withdraw']->id,
], 6, false);
}
return response()->json($data['withdraw']['id']);
}
public function indexWithdraw(Request $request){
$records = Withdraw::with(['customer','bank_account','Address',"Transaction"])->where("customer_id",auth('customer')->id());
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Withdraw::$SELECT_STS_STR,Withdraw::$SELECT_DAJ
])->export($records);
return response()->json($records);
}
public function index_withdraw_physical(Request $request){
$records = Withdraw::with(['customer','bank_account','Address',"Transaction.product"])->where("customer_id",auth('customer')->id())->whereBetween('sts', [49, 70]);
TableEngine::create($records, $request->all())
->initSearch(['customer.name'])
->select([
'*',Withdraw::$SELECT_STS_STR,Withdraw::$SELECT_DAJ
])->export($records);
return response()->json($records);
}
public function withdrawOtp(Request $request)
{
$customer = auth('customer')->user();
$otp = rand(1000, 9999);
$customer->token_sms = $otp;
$customer->save();
$this->Send(
$customer->mobile,
'رمز عبور یکبار مصرف شما جهت برداشت پول از اپلیکیشن ' . $this->Config('name_fa') . ' می باشد: ' . $otp
);
return response()->json(true);
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
namespace App\Http\Controllers\Finance;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Price;
use App\Models\TransactionsAdmin;
use App\Models\User;
use App\Models\Withdraw;
use App\DB\Te\TableEngine;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Wallet;
class FinanceController extends Controller
{
public function fall(Request $request)
{
$transactions_admins = TransactionsAdmin::with(['withdraw','order',"user",'customerTo','customer']);
TableEngine::create($transactions_admins, $request)
->initSearch(['price'])
->select(['*'])
->export($transactions_admins);
return response()->json($transactions_admins);
}
public function index()
{
$tallaPrice = Price::latest()->first();
// $talla->update_date = Verta::instance(Carbon::parse($talla->updated_at))->format('Y/n/j-H:i');
$new_customer_major = Customer::where('type',1)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$new_customer_single = Customer::where('type',2)->whereDate('created_at','<=',now())->whereDate('created_at','>=',now()->subMonths(3))
->count();
$all_customer_major = Customer::where('type',1)->count();
$all_customer_single = Customer::where('type',2)->count();
$archive_customer_major = Customer::where('type',1)->where('is_archive',true)->count();
$archive_customer_single = Customer::where('type',2)->where('is_archive',true)->count();
$all_gold = Order::where('direction',2)->where('type',1)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$all_gold_single = Order::where('direction',2)->where('type',2)->sum('amount');// جمع طلاهایی که از مشتری خریدیم
$await_list = Order::where('direction',1)->where('sts',1)->get();
$best_customer_major=Order::with('customer')->where('type',1)->where('sts',2)->select('customer_id',DB::raw('sum(amount) as amount'))
->groupBy('customer_id')->limit(10)->get();
$best_customer_single=Wallet::with('customer')->whereNull('fund_id')->where('owner_type',2)->orderBy('gold','desc')->limit(10)->get();
// GT
$GT_all_customers = Customer::where('type',2)->where('is_archive',false)->count();
$GT_no_login_customers = Customer::where('type',2)->where('is_archive',false)->where('last_seen_at',null)->count();
$GT_no_valid_customers = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->count();
$GT_no_valid_customers_data = Customer::where('type',2)->where('is_archive',false)->where('is_legal',0)->get(['id','name','mobile']);
$GT_active_customers = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->count();
$GT_active_customers_data = Customer::where('type', 2)
->where('is_archive', false)
->whereIn('id', function($query) {
$query->select('owner')
->from('wallets');
})->get(['id','name','mobile']);
$transactions_admins = TransactionsAdmin::with(['withdraw','order',"user",'customerTo','customer'])->get();
return view('app', compact(
'GT_all_customers',
'GT_no_login_customers',
'GT_no_valid_customers',
'GT_no_valid_customers_data',
'GT_active_customers',
'GT_active_customers_data',
'transactions_admins',
'tallaPrice',
'new_customer_major',
'new_customer_single',
'all_customer_major',
'all_customer_single',
'archive_customer_major',
'archive_customer_single',
'all_gold',
'all_gold_single',
'await_list',
'best_customer_major',
'best_customer_single'
))->with('GT_deActive_customers', $GT_all_customers - $GT_active_customers)
->with('price', $tallaPrice->price);
}
public function startTransation(Request $request)
{
$user = auth()->user();
// riyal to tomman
$tomman = $request->value;
$riyal = (int)($request->value / 10);
$riyal .= 0;
$request->value = (int)($request->value / 10);
$Withdraw = Withdraw::create([
'customer_id' => auth('customer')->id(),
"cash" => $riyal,
'sts' => 1,
]);
$url = 'https://zify.ir/api/order/v2/create';
$payload = [
"payer" => [
"first_name" => $user->fname,
"last_name" => $user->lname,
"phone" => $user->mobile,
"email" => "",
"state" => $user->city,
"city" => $user->province,
"address_1" => $user->id,
"address_2" => $user->shop_name
],
"products" => [
[
"code" => "1",
"sellQuantity" => 1,
"title" => "IRR",
"amount" => $request->value,
"unlimited" => true,
"quantity" => $request->value,
"description" => "charge_account"
]
],
"returnUrl" => "https://api.gholaktala.ir/customer/charge_account_verify",
"clientRefId" => "$Withdraw->id",
"shipping_total" => 0,
"off_total" => 0,
"tax_total" => 0
];
$response = Http::withToken(env('ZIFI_TOKEN_GHOLAKTALLA'))
->post($url, $payload);
if ($response->successful()) {
$responseData = $response->json();
$orderCode = $responseData['data']['order'] ?? null;
if ($orderCode) {
$Withdraw->tracked_number = $orderCode;
$Withdraw->save();
return "https://zify.ir/order/accept/{$orderCode}";
} else {
return response()->json([
'message' => 'Order created successfully but order code is missing',
'data' => $responseData
]);
}
} else {
$response = $response->json();
return response()->json([$response][0], 422);
}
}
public function verifyTransation()
{
$Withdraw = Withdraw::with('customer')->where('id', $_GET['clientrefid'])->first();
$User = Customer::where('id', $Withdraw->customer_id)->first();
$url = 'https://zify.ir/api/order/v2/verify';
$payload = [
"order" => "$Withdraw->tracked_number",
];
$verifyResponse = Http::withToken(env('ZIFI_TOKEN_GHOLAKTALLA'))
->post($url, $payload);
$decodedResponse = json_decode($verifyResponse, true);
$verifyMessage = $decodedResponse['message'];
// return $decodedResponse['data'];
if (isset($decodedResponse['data']['refid']) || $verifyMessage == []) {
if ($Withdraw->cash == $decodedResponse['data']['amount'] * 10) {
$Withdraw->zify_code = $Withdraw->tracked_number;//ok
$Withdraw->tracked_number = $decodedResponse['data']['refid'];//ok
$Withdraw->sts = 2;//ok
$Withdraw->save();
$wallet_interface_fund = new WalletInterface($User->id, $User->type);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"cash" => $decodedResponse['data']['amount'] * 10,
'expire_at' => now(),
'withdraw_id' => $_GET['clientrefid'],
'active' => true
], 3, false, true);
//----------sms
// User information
$userMobile = $Withdraw->customer->mobile; // User's mobile number
$userName = $Withdraw->customer->name; // User's name
$chargedAmount = $Withdraw->cash; // Charged amount
// Company name
$companyName = $this->Config('name_fa'); // Company name from configuration
// Constructing the SMS message
$message = "کاربر $userName با شماره موبایل $userMobile حساب خود را به مقدار " . number_format($chargedAmount) . " ریال شارژ کرد. با تشکر، $companyName";
// Getting admin mobile numbers and sending the SMS
User::where('active', 1)->get()->each(function($admin) use ($message) {
$this->Send($admin->mobile, $message);
});
return view('showTransactionReport', compact('Withdraw'));
return redirect('https://app.gholaktala.ir/transactions');
}
return "مبلغ پرداختی دستکاری شده !";
} else {
$Withdraw->tracked_number;
$Withdraw->sts = 3;//no
$Withdraw->save();
return view('showTransactionReport', compact('Withdraw'));
}
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers\Single;
use App\Http\Controllers\Controller;
use App\Http\Controllers\SuperController;
use App\Models\BankAccount;
use App\Models\Customer;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class BankAccountController extends SuperController
{
public function __construct(Request $request)
{
$query = BankAccount::where('customer_id', auth('customer')->id());
$request->request->add(['customer_id' => auth('customer')->id()]);
parent::__construct(BankAccount::class, [], ['*', BankAccount::$SELECT_STS_STR], null, $query);
}
public function destroy($id)
{
$account = BankAccount::findOrFail($id);
if ($account->sts != 3) {
throw new UnprocessableEntityHttpException('امکان حذف این کارت بانکی وجود ندارد');
}
return parent::destroy($id);
}
public function listActiveBankAccount()
{
$query = BankAccount::where('customer_id', auth('customer')->id())
->whereIn('sts', [1, 2])->get();
return response()->json($query);
}
public function StoreBankAccount(Request $request)
{
if (empty($request->shaba_number) || empty($request->bank_name) ){
// || empty($request->cart_number) || empty($request->account_number)) {
throw new UnprocessableEntityHttpException('اطلاعات کارت را کامل وارد کنید.');
}
$customer = Customer::find(auth('customer')->id());
$message = "کارت جدیدی برای $customer->name ساخته شد منتظر تایید شما هستیم.";
$message .= $this->Config('name_fa');
User::where('active', 1) ->where('send_sms', 1)->get()->each(function($admin) use ($message) {
$this->Send($admin->mobile, $message);
});
$data = $request->only(['account_number', 'bank_name', 'cart_number', 'shaba_number', 'customer_id']);
BankAccount::create($data);
return response()->json($data);
}
}
+541
View File
@@ -0,0 +1,541 @@
<?php
namespace App\Http\Controllers\Single;
use App\DB\Te\TableEngine;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\TahesabController;
use App\Models\Customer;
use App\Models\Order;
use App\Models\Price;
use App\Models\Product;
use App\Models\User;
use App\Mail\YourMailableClass;
use Illuminate\Support\Facades\Mail;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Transaction;
use Rooyesh\Wallet\models\Wallet;
use App\Models\TransactionsAdmin;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Illuminate\Support\Facades\Http;
class SingleOrderController extends Controller
{
public function store(Request $request)
{
// throw new UnprocessableEntityHttpException('به دلیل نوسانات سفارشات بسته میباشد.');
$data = $request->all();
$transactionType = $data['direction'] == 1 ? "خرید" : "فروش";
if (auth('customer')->id()) {
$data['customer_id'] = auth('customer')->id();
$latestPrice = Price::latest()->first();
$data['all_price'] = $latestPrice;
$data['price'] = $latestPrice->price;
$data['price_id'] = $latestPrice->id;
$data['difference'] = config('fee.cash');
$data['service_charge_percentage'] = config('fee.service_charge_percentage');
$data['pay_at'] = (new \DateTime())->format('Y-m-d H:i:s');
} else if (auth('user')->id()) {//admin
$data['service_charge_percentage'] = 0;
}
$data['sts'] = 2;
$data['type'] = 2;
$data['payment_sts'] = 4;
$data['price_original'] = $data['price'];
$data['payment_remind'] = 0;
$data['fee'] = $data['difference'];
$wallet_interface = new WalletInterface($data['customer_id'], 2);
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
$response = [];
// Check if the user wants to transact with a product or non-product (gold)
if (isset($data['product_id']) and $data['product'] = Product::find($data['product_id'])) {
// Check if the user wants to buy
if ($data['direction'] == 1) {
$data['service_charge_percentage'] = ($data['product']['percent_fee_buy']) * $data['number'];
$data['difference'] = $data['fee'] = $data['product']['cash_fee_buy'];
$data['total_price_original'] = $data['product']['amount'] * ($data['price_original'] ?? 0);
// Check if the method is cash
if ($data['method'] == "cash") {
$response['buy'] = $this->processBuyTransactionProduct($data, $wallet, $wallet_interface);
} // Check if the method is gold
else if ($data['method'] == "gold") {
$response['buy'] = $this->processBuyTransactionProductByGold($data, $wallet, $wallet_interface);
}
} // Check if the user wants to sell
else if ($data['direction'] == 2) {
$data['service_charge_percentage'] = ($data['product']['percent_fee_sell']) * $data['number'];
$data['difference'] = $data['fee'] = $data['product']['cash_fee_sell'];
$data['total_price_original'] = $data['product']['amount'] * ($data['price_original'] ?? 0);
// Check if the method is cash
if ($data['method'] == "cash") {
$response['sell'] = $this->processSellTransactionProduct($data, $wallet, $wallet_interface);
} // Check if the method is gold
else if ($data['method'] == "gold") {
$response['sell'] = $this->processSellTransactionProductByGold($data, $wallet, $wallet_interface);
}
}
} else {
// Calculate total price and fee for non-product (gold) transaction
$data['total_price_original'] = $data['amount'] * ($data['price_original'] ?? 0);
$data['total_fee'] = $data['amount'] * $data['difference'];
$data['product'] = Product::find(13);
// Check if the user wants to buy
if ($data['direction'] == 1) {
if (!$data['product']['open_buy']) {
throw new UnprocessableEntityHttpException('خرید این محصول در این لحظه مقدور نمیباشد');
}
$response['buy'] = $this->processBuyTransaction($data, $wallet, $wallet_interface);
} // Check if the user wants to sell
else if ($data['direction'] == 2) {
if (!$data['product']['open_sell']) {
throw new UnprocessableEntityHttpException('خرید این محصول در این لحظه مقدور نمیباشد');
}
$response['sell'] = $this->processSellTransaction($data, $wallet, $wallet_interface);
}
}
// try {
// $tahesab = new TahesabController();
// $data['tahesab'] = $tahesab->storeTrade($data);
// }catch (\Exception $e){
// return response($e->getMessage(), 500);
// }
// $response['reward'] = $this->give_order_reward($data, $wallet, $wallet_interface);
$response['Notifications'] = $this->sendTransactionNotifications($data, $transactionType);
return response()->json([$response, $data]);
}
private function processBuyTransaction(&$data, $wallet, $wallet_interface)
{
$response = [];
$data['price'] += $data['difference'];
$data['total_price'] = $data['amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
$data['service_charge'] = $data['service_charge_percentage'] * $data['amount'];
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$data['amount'] -= $data['service_charge'];
if ($wallet->cash < $data['payment_amount']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
$data['order'] = $order = Order::create($data);
new TransactionInterface($wallet_interface, [
"cash" => $data['payment_amount'],
"gold" => $data['amount'],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, true, false);
$response['1'] = 2;
//send to liman
if ($this->Config('do_send_liman') == "true") {
$payload = [
'amount' => "$order->amount",
'description' => $this->Config('name_fa') . " - " . auth('customer')->user()->name,
'ref_id' => $order->id,
'direction' => 1,
'product_id' => 2
];
return $response = Http::withToken($this->Config('liman_token'))
->post("https://limangold.ir/kernel/customer/order", $payload)->json();
$order->total_price_liman = $response["payment_amount"];
$order->save();
}
return $response;
}
private function processBuyTransactionProduct(&$data, $wallet, $wallet_interface)
{
$data['price'] += $data['difference'];
$data['amount'] = $data['number'] * $data['product']['amount'];
$data['total_amount'] = $data['amount']+($data['product']['percent_fee_buy']*$data['amount']);
$data['total_price'] = $data['total_amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
$data['service_charge'] = ($data['product']['percent_fee_buy']*$data['amount']);
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$data['wallet'] = $wallet;
if ($wallet->cash < $data['payment_amount']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_buy']) {
throw new UnprocessableEntityHttpException('خرید این محصول در این لحظه مقدور نمیباشد');
}
$data['order'] = $order = Order::create($data);
$data['transaction'][] = new TransactionInterface($wallet_interface, $_inp = [
"number" => $data['number'],
"cash" => $data['total_price'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'title' => "برداشت وجه نقد"
], 12, false,false);
$wallet_interface_product = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $data["product_id"]);
$wallet_interface_product->wallet->gold = intval($wallet_interface_product->wallet->gold);
$wallet_interface_product->wallet->save();
new TransactionInterface($wallet_interface_product, [
"gold" => $data['number'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, true, false);
}
private function processBuyTransactionProductByGold(&$data, $wallet, $wallet_interface)
{
$data['price'] += $data['difference'];
$data['amount'] = $data['number'] * $data['product']['amount'];
$data['total_amount'] = $data['amount']+($data['product']['percent_fee_buy']*$data['amount']);
$data['total_price'] = $data['total_amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
$data['service_charge'] = ($data['product']['percent_fee_buy']*$data['amount']);
$data['total_fee'] = 0;
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$data['wallet'] = $wallet;
if ($wallet->gold < $data['total_amount']) {
throw new UnprocessableEntityHttpException('موجودی طلایی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_buy']) {
throw new UnprocessableEntityHttpException('خرید این محصول در این لحظه مقدور نمیباشد');
}
$data['order'] = $order = Order::create($data);
$data['transaction'][] = new TransactionInterface($wallet_interface, $_inp = [
"number" => $data['number'],
"gold" => $data['total_amount'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'title' => "برداشت طلای ابشده"
], 12, false,true);
$wallet_interface_product = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $data["product_id"]);
$wallet_interface_product->wallet->gold = intval($wallet_interface_product->wallet->gold);
$wallet_interface_product->wallet->save();
new TransactionInterface($wallet_interface_product, [
"gold" => $data['number'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, true, false);
}
private function processSellTransaction(&$data, $wallet, $wallet_interface)
{
$response = [];
$data['price'] -= $data['difference'];
$data['service_charge'] = $data['service_charge_percentage'] * $data['amount'];
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$data['total_price'] = $data['amount'] * $data['price'] -$data['service_charge_price'];
$data['payment_amount'] = $data['total_price'];
$data['payment_amount'] -= $data['service_charge_price'];
if ($wallet->gold < $data['amount']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
$data['order'] = $order = Order::create($data);
new TransactionInterface($wallet_interface, [
"gold" => $data['amount'],
"cash" => $data['total_price'],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id
], 2, false, true);
}
private function processSellTransactionProduct(&$data, $wallet, $wallet_interface)
{
$data['price'] -= $data['difference'];
$data['amount'] = $data['number'] * $data['product']['amount'];
$data['total_amount'] = $data['amount']-($data['product']['percent_fee_sell']*$data['amount']) ;
$data['total_price'] = $data['total_amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
$data['service_charge'] = ($data['product']['percent_fee_sell']*$data['amount']);
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$wallet_interface_product = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $data["product_id"]);
if ($wallet_interface_product->wallet->gold < $data['number']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_sell']) {
throw new UnprocessableEntityHttpException('فروش این محصول در این لحظه مقدور نمیباشد');
}
$data['order'] = $order = Order::create($data);
$wallet_interface_product->wallet->gold = intval($wallet_interface_product->wallet->gold);
$wallet_interface_product->wallet->save();
new TransactionInterface($wallet_interface_product, [
"gold" => $data['number'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, false, false);
$data['transaction'][] = new TransactionInterface($wallet_interface, $_inp = [
"number" => $data['number'],
"cash" => $data['total_price'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'title' => "واریز وجه نقد"
], 12, false,true);
}
private function processSellTransactionProductByGold(&$data, $wallet, $wallet_interface)
{
$data['price'] -= $data['difference'];
$data['amount'] = $data['number'] * $data['product']['amount'];
$data['total_amount'] = $data['amount']-($data['product']['percent_fee_sell']*$data['amount']) ;
$data['total_price'] = $data['total_amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
$data['service_charge'] = ($data['product']['percent_fee_sell']*$data['amount']);
$data['total_fee'] = 0;
$data['service_charge_price'] = $data['service_charge'] * $data['price_original'];
$wallet_interface_product = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type, null, $data["product_id"]);
if ($wallet_interface_product->wallet->gold < $data['number']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_sell']) {
throw new UnprocessableEntityHttpException('فروش این محصول در این لحظه مقدور نمیباشد');
}
$data['order'] = $order = Order::create($data);
$data['transaction'][] = new TransactionInterface($wallet_interface, $_inp = [
"number" => $data['number'],
"gold" => $data['total_amount'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'title' => "واریز طلای ابشده"
], 12, true,false);
$wallet_interface_product->wallet->gold = intval($wallet_interface_product->wallet->gold);
$wallet_interface_product->wallet->save();
new TransactionInterface($wallet_interface_product, [
"gold" => $data['number'],
"product_id" => $data["product_id"],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, false, false);
}
private function give_order_reward(&$data, $wallet, $wallet_interface)
{
$data['aCustomers'] = [];
$i = 0;
$data['aCustomers'][$i] = Customer::findOrFail($data['customer_id']);
while ($data['aCustomers'][$i + 1] = Customer::where('referral_id', $data['aCustomers'][$i]->referral_to_id)->first()) {
if ($data['aCustomers'][$i + 1]->profit_amount_by_lvl) {
$levels = json_decode(str_replace(['{', '}'], ['[', ']'], $data['aCustomers'][$i + 1]->profit_amount_by_lvl), true);
foreach ($levels as $level) {
if ($level[0] == $i + 1) {
// [$level[1],$data['aCustomers'][$i+1]];
if ($this->Config('has_page_earn_money') == true) {
$gift_for_invite = ($data['order']['service_charge'] * $level[1]) / 100;
$profit_receiver = $data['aCustomers'][$i + 1]->id;
$profit_sender = $data['aCustomers'][0]->id;
$Withdraw = Withdraw::create([
'user_id' => $profit_sender,
'customer_id' => $profit_receiver,
"cash" => 0,
"gold" => $gift_for_invite,
'sts' => 9,
]);
$wallet_interface = new WalletInterface($profit_receiver, 2);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => 0,
"gold" => $gift_for_invite,
'expire_at' => now(),
'active' => true,
'withdraw_id' => $Withdraw->id,
'start_at' => now(),
], 9, true, false);
$transaction = Transaction::where('customer_id', $profit_receiver)->latest()->first();
TransactionsAdmin::create([
'customer_id' => $profit_sender,
'customer_to_id' => $profit_receiver,
'user_id' => $profit_sender,
'order_id' => $data['order']['id'],
'wallet' => null, // یا مقدار مناسب دیگری
'transaction_id' => $transaction->id,
'cash' => 0,
'note' => ' سود بابت سفارش',
'type' => 1, // یا مقدار مناسب دیگری
'gold' => $gift_for_invite,
'balance_cash' => 0, // یا مقدار مناسب دیگری
'balance_gold' => $gift_for_invite, // مقدار صحیح برای `balance_gold`
'withdraw_id' => $Withdraw->id,
]);
}
}
}
}
if ($i == 100) break;
$i++; // برای جلوگیری از حلقه بی‌نهایت
}
return $data;
}
private function sendTransactionNotifications(array $data, string $transactionType)
{
$customer = Customer::findOrFail($data['customer_id']);
$companyName = $this->Config('name_fa');
$message = "کاربر {$customer->name} با شماره موبایل {$customer->mobile} اقدام به $transactionType {$data['product']['title']} به مقدار " .
"{$data['amount']} گرم به مبلغ " . number_format($data['total_price']) .
" ریال کرد. با تشکر، $companyName";
User::where('send_sms', 1)->get()->each(function ($admin) use ($message, $data, $transactionType, $companyName) {
$this->send($admin->mobile, $message);
});
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
// $pricePerGram = $data['total_price'] / $data['amount'];
$customerMessage = "$companyName\n$transactionType آبشده\nگرم: {$data['amount']}\n" .
"مبلغ کل: " . number_format($data['total_price']) . "\n\n" .
"موجودی طلایی: {$wallet->gold}\n" .
"مانده ریالی: " . number_format($wallet->cash) . "\n" .
$this->Config('app_url');
// ارسال SMS به مشتری
$this->send($customer->mobile, $customerMessage);
}
public function storeBackUp(Request $request)
{
$data = $request->all();
if (auth('customer')->id()) {// متد در پنل کاربر
$data['customer_id'] = auth('customer')->id();
$data['price'] = Price::orderBy('id', 'desc')->first()->price;
} elseif (auth('user')->user()) {// متد در پنل ادمین
$data['customer_id'] = $request->customer_id;
$data['price'] = $request->price;
}
$data['sts'] = 2;
$data['type'] = 2;
$data['payment_sts'] = 4;
$data['price_original'] = $data['price'];
$add_sell_price = config('add_sell_price.single');
$wallet_interface = new WalletInterface($data['customer_id'], 2);
$wallet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
$data['total_price_original'] = $data['amount'] * $data['price_original'];
$data['payment_remind'] = 0;
$data['fee'] = $add_sell_price;
$data['total_fee'] = $data['amount'] * $data['fee'];
if ($data['direction'] == 1) {
$data['price'] += $add_sell_price;
$data['total_price'] = $data['amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
if ($wallet->cash < $data['total_price']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
$order = Order::create($data);//buy
new TransactionInterface($wallet_interface, $_inp = [
"cash" => $data['total_price'],
"gold" => $data['amount'],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id,
'start_at' => now(),
], 1, true, false);
} else {//sell
$data['price'] -= $add_sell_price;
$data['total_price'] = $data['amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'];
if ($wallet->gold < $data['amount']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
$order = Order::create($data);
new TransactionInterface($wallet_interface, $_inp = [
"gold" => $data['amount'],
"cash" => $data['total_price'],
'expire_at' => now(),
'active' => true,
'order_id' => $order->id
], 2, false, true);
}
//----------------------------------------------------------------------------sms
// Determine transaction type
$transactionType = ($data['direction'] == 1) ? "خرید" : "فروش";
// User information
$customer = Customer::where("id", $data['customer_id'])->firstOrFail();
$userMobile = $customer->mobile; // User's mobile number
$userName = $customer->name; // User's name
$chargedAmount = $data['total_price']; // Total price in Rial
$chargedAmountGold = $data['amount']; // Amount of gold
// Company name
$companyName = $this->Config('name_fa'); // Company name from configuration
// Constructing the SMS message
$message = "کاربر $userName با شماره موبایل $userMobile اقدام به $transactionType طلا به مقدار " . $chargedAmountGold . " گرم به مبلغ " . number_format($chargedAmount) . " ریال کرد. با تشکر، $companyName";
// Getting admin mobile numbers and sending the SMS
User::where('active', 1)->get()->each(function ($admin) use ($message) {
$this->Send($admin->mobile, $message);
});
$Walet = Wallet::where('owner', $data['customer_id'])->whereNull('fund_id')->first();
$companyName = $this->Config('name_fa');
$companyurl = $this->Config('app_url');
$weight = $data['amount'];
$totalAmount = $data['total_price'];
$pricePerGram = $totalAmount / $weight;
$goldBalance = $Walet->gold;
$remainingBalance = $Walet->cash;
$message = "$companyName\n";
$message .= "خرید آبشده\n";
$message .= "گرم: $weight\n";
$message .= "قیمت گرم: " . number_format($pricePerGram) . "\n";
$message .= "مبلغ کل: " . number_format($totalAmount) . "\n\n";
$message .= "موجودی طلایی: $goldBalance\n";
$message .= "مانده ریالی: " . number_format($remainingBalance) . "\n";
$message .= "$companyurl" . "\n";
$this->Send($customer->mobile, $message);
return response()->json($order);
}
public function table(Request $request)
{
$records = Order::where('customer_id', auth('customer')->id())
->where('type', 2);
TableEngine::create($records, $request->all())
->initSearch([])
->select([
'*', Order::$SELECT_STS_STR
])->export($records);
return response()->json($records);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers\Site;
use App\Http\Controllers\Controller;
use App\Models\City;
use Illuminate\Http\Request;
class CityController extends Controller
{
public function stateList(){
$city = City::whereNull('parent_id')->get();
return response()->json($city);
}
public function cityList($state_id){
$city = City::where('parent_id',$state_id)->get();
return response()->json($city);
}
public function cityListAll(){
$city = City::all();
return response()->json($city);
}
}
+248
View File
@@ -0,0 +1,248 @@
<?php
namespace App\Http\Controllers\Site;
use App\Http\Controllers\Admin\PriceController;
use App\Http\Controllers\Controller;
use App\Mail\YourMailableClass;
use App\Models\Cnt;
use App\Models\ConfigStatic;
use App\Models\Customer;
use App\Models\Price;
use App\Models\PriceCandle;
use App\Models\PriceTrigger;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Morilog\Jalali\Jalalian;
class ReportController extends Controller
{
public function candleChart()
{
$candle = PriceCandle::select(["start",
"high",
"low",
"end",
"date_at"])->whereDate('date_at', '<=', date("Y-m-d"))
->whereDate('date_at', '>', Carbon::now()->subDays(30)->format("Y-m-d"))
->get()->toArray();
$a = [];
foreach ($candle as $c) {
$create['date'] = $c["date_at"];
unset($c["date_at"]);
$create['candle'] = array_values($c);
$a[] = array_values($create);
}
return response()->json($a);
}
public function updatePrise()
{
$difference = config('fee.single');
$lastPrice = Price::latest()->first();
$PriceTriggers = PriceTrigger::where("is_active", true)->get();
foreach ($PriceTriggers as $PriceTrigger) {
$priseGold = $PriceTrigger->dirction == 1
? $lastPrice->price - $difference
: ($PriceTrigger->dirction == 2 ? $lastPrice->price + $difference : $lastPrice->price);
if (eval('return $priseGold ' . $PriceTrigger->price_condition . ' $PriceTrigger->target_price;')) {
$customer = Customer::find($PriceTrigger->customer_id);
$message = "قیمت طلا به " . number_format($priseGold, -1) . " در هر گرم رسید\n" .$this->Config('name_fa');
if ($PriceTrigger->action == 'email') {
Mail::to("$customer->email")->send(new YourMailableClass($message, '', '', '', ''));
} elseif ($PriceTrigger->action == 'sms') {
$this->send($customer->mobile, $message);
}
$PriceTrigger->is_active = false;
$PriceTrigger->triggered_at = Carbon::now();
$PriceTrigger->save();
}
}
return response()->json();
}
public function upDownPrice()
{
$difference = config('fee.single');
$today = Carbon::now()->format("Y-m-d");
$prises = Price::where('date_at', $today)->get("price");
$minP = 0; // Initialize to the highest possible value
$maxP = 0; // Initialize to the lowest possible value
foreach ($prises as $p) {
// Initialize $minP to the first price if it's null
if ($minP == 0 || $p->price < $minP) {
$minP = $p->price;
}
// Initialize $maxP to the first price if it's null
if ($maxP == 0 || $p->price > $maxP) {
$maxP = $p->price;
}
}
if (count($prises) === 0) {
// Fetching the current gold price from the API
$response = Http::get('https://www.tala.ir/ajax/price');
$data = $response->json();
// Clean the price value retrieved from API
$data['gold']['gold_18k']['v'] = str_replace(',', '', $data['gold']['gold_18k']['v']);
$priceValue = $data['gold']['gold_18k']['v'] * 10; // Assuming the multiplication by 10 is needed
// Create and save the new Price instance
$price = new Price();
$price->price = $priceValue; // Assign the cleaned and calculated price value
$price->time_at = Carbon::now()->toTimeString(); // Set current time
$price->date_at = Carbon::now()->toDateString(); // Set current date
$price->save(); // Save to the database
return ['sell' => $price->price - $difference, 'buy' => $price->price + $difference];
} else {
// Assuming $minP and $maxP are defined elsewhere in your code
return ['sell' => $minP - $difference, 'buy' => $maxP + $difference];
}
// return $prises;
// $add_sell_price = config('add_sell_price.major');
// $price = PriceCandle::whereDate('date_at',)->first();
// $price_price = Price::orderBy('id','desc')->first();
}
public function lastPrice()
{
$difference = config('fee.single');
// try {
// $tala_ir = (int)str_replace(',', '', Http::timeout(2)->get('https://www.tala.ir/ajax/price')->json()['gold']['gold_18k']['v']) * 10;
// } catch (\Exception $e) {$tala_ir = 0;}
$main_product_id = Cnt::where('key', 'main_product')->first()['value'];
$pr_product = Product::find($main_product_id);
$priceValue = $pr_product['price'] + $pr_product['price_profit'];//$tala_ir;//4000
$lastPrice = Price::latest()->first();
if (!$lastPrice || $lastPrice->price != $priceValue and $priceValue > 30000000) {
$price = new Price();
$price->price = $priceValue; // Assign the cleaned price value
$price->time_at = Carbon::now()->toTimeString();
$price->date_at = Carbon::now()->toDateString();
$price->save();
$this->updatePrise();
$candle = PriceCandle::whereDate('date_at',date("Y-m-d"))->first();
if (!is_null($candle)){
$candle->end = $priceValue;
if ($priceValue < $candle->low){
$candle->low = $priceValue;}
elseif ($priceValue > $candle->high){
$candle->high = $priceValue;}$candle->save();
}else{
PriceCandle::create([
"start"=>$priceValue,
"end"=>$priceValue,
"high"=>$priceValue,
"low"=>$priceValue,
"date_at"=>date("Y-m-d")
]);
}
}
$price = Price::orderBy('id', 'desc')->first();
if ($price) {
return [
'sell' => $price->price - $difference,
'buy' => $price->price + $difference,
'price_last' => $price->price + $difference,
'price' => $priceValue,
// 'tala_ir' => $tala_ir,
// 'henzagold' => $henzagold_18,
// 'Ounce' => $henzagold_ons_gold,
// 'milli' => $milli,
];
} else {
return [];
}
}
public function check()
{
$service = Http::
withHeaders([
'accept' => 'application/json',
'Authorization' => 'Bearer ohxsrbjagqvbt0glaygt'
])->get('https://studio.persianapi.com/index.php/web-service/common/gold-currency-coin?format=json&limit=30&page=1')
->json();
$list = [];
if (isset($service['result'])) {
foreach ($service['result'] as $item) {
if ($item['key'] == 137120 || $item['key'] == 137119) {
$list[] = $item;
if ($item['key'] == 137120) {
(new PriceController())->store(new Request(["price" => $item['price']]));
}
}
}
Cnt::where('key', 'price')->update(['value_json' => $list]);
}
}
public function test()
{
$a = '{{12, 23, {4, 0, {1}, {1}}}, 0, {1}}';
$b = str_split($a);
$c = [];
$str = "";
foreach ($b as $item) {
if ($item != " ") {
print_r($item);
print_r('++');
if ($item == ',' || $item == '}') {
if (!in_array($c[count($c) - 1], ['{', '}'])) {
$c[count($c) - 1] += (int)$str;
print_r((int)$str);
print_r('^^');
} else {
$c[] = $str;
print_r($c);
print_r('&&');
}
$str = "";
} elseif (in_array($item, ['{', '}'])) {
$c[] = $item;
print_r($c);
print_r('**');
} else {
$str .= $item;
print_r($str);
print_r('@@');
}
}
}
dd($c);
$d = [];
$e = [];
foreach ($c as $item) {
if ($item == '}') {
print_r($d[count($d) - 1]);
print_r('***');
$e[] = $d[count($d) - 1];
} else {
$d[] = $item;
print_r($d);
print_r('-----');
}
}
dd($e);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Controllers\Site;
use App\Http\Controllers\Controller;
use App\Services\NotificationService;
use Illuminate\Http\Request;
class myNotificationController extends Controller
{
protected $notificationService;
public function __construct(NotificationService $notificationService)
{
$this->notificationService = $notificationService;
}
public function mySendNotification(Request $request)
{
return 1;
$message = $request->input('message');
$response = $this->notificationService->sendNotification($message);
return response()->json($response);
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace App\Http\Controllers;
use App\DB\Te\TableEngine;
use App\Models\Cnt;
use Illuminate\Http\Request;
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']) && isset($data['lname'])){
$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']);
}
if ($this->name_model == 'customer'){
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
do {
$uniqueId = '';
for ($i = 0; $i < 4; $i++) { // ایجاد یک کد چهار رقمی
$index = random_int(0, $charactersLength - 1);
$uniqueId .= $characters[$index];
}
// بررسی اینکه آیا کد ایجاد شده یونیک است
$existingCustomer = $this->model::where('referral_id', $uniqueId)->first();
} while ($existingCustomer); // تکرار تا زمانی که کد یونیک ایجاد شود
$data['referral_id'] = $uniqueId; // ذخیره کد یونیک در فیلد referral_id
$message = "{$data['name']} عزیز، اکانت شما در پلتفرم {$this->Config('name_fa')} ایجاد شد.\nنام کاربری: {$data['mobile']}\nورود به نرم افزار: {$this->Config('app_url')}";
$this->Send($data['mobile'], $message);
}
}
}
$user = $this->model::create($data);
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']) && isset($data['lname'])){
$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);
//*******کداضافه شده
// ->where('active', '<=', now()) // فیلتر محصولات فعال
// ->get();
//*********
}else{
$query_table = $this->query;
// $query_table = $query_table->where('active', '<=', now());
}
TableEngine::create($query_table, $data)
->initSearch($this->search)
->select($this->select)
->export($query_table);
return $query_table;
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
namespace App\Http\Controllers\Pay;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; // For UUID generation
use Ramsey\Uuid\Uuid;
class PaymanController extends Controller
{
protected $accessToken = 'b71c3737-7b89-4f2c-9301-767439079407';
/**
* Get access token from Payman API.
*/
public function login()
{
$response = Http::withHeaders(['Cookie' => 'cookiesession1=678A8C341A085F7AF93FECC7B44ACDFF'])
->asForm()
->post('https://payman2.sandbox.faraboom.co/oauth/token', [
'Client_id' => 'demopayman',
'Client_secret' => '!8cr?40V',
'Grant_type' => 'client_credentials',
]);
$this->accessToken = $response->json()['access_token'];
return $response->json();
}
/**
* Create a Payman account.
*/
public function create()
{
$t = Uuid::uuid4()->toString();
$response = Http::withHeaders([
'app-key' => 'demopayman',
'Client-Ip-Address' => '127.0.0.1',
'Client-Platform-Type' => 'web',
'Client-Device-Id' => '169.254.75.178',
'Client-User-Id' => '09352673656',
'Client-User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
'Content-Type' => 'application/json',
'Mobile-no' => '09352673656',
'National-code' => '0082205388',
'Authorization' => 'Bearer b71c3737-7b89-4f2c-9301-767439079407',
'Cookie' => 'cookiesession1=678A8C341A085F7AF93FECC7B44ACDFF',
])
->post('https://payman2.sandbox.faraboom.co/v1/payman/create', [
'payman' => [
'bank_code' => 'SINAIR',
'user_id' => 'demopayman',
'permission_ids' => [1],
'contract' => [
'expiration_date' => '2026-01-15T01:28:09.5662061+04:30',
'max_daily_transaction_count' => 50,
'max_monthly_transaction_count' => 100,
'max_transaction_amount' => 500000,
],
],
'redirect_url' => 'http://localhost',
'trace_id' => $t,
]);
// دریافت پاسخ از API
$statusCode = $response->status(); // وضعیت HTTP
$responseBody = $response->json(); // بدنه پاسخ به صورت JSON
$responseHeaders = $response->headers(); // هدرهای پاسخ
$responseBodyRaw = $response->body(); // بدنه خام پاسخ (به صورت متن)
// برگشت وضعیت و بدنه پاسخ
return response()->json([
'status' => $statusCode,
'json' => $response->json(),
'headers' => $response->headers(),
'body' => $response->body(),
]);
$response = Http::timeout(4)->withHeaders([
'Cookie' => 'cookiesession1=678A8C341A085F7AF93FECC7B44ACDFO',
'app-key' => 'demopayman',
'Client-Ip-Address' => $_SERVER['REMOTE_ADDR'],
'Client-Platform-Type' => 'web',
'Client-Device-Id' => '169.254.75.178',
'Client-User-Id' => '09352673656',
'Client-User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
'Content-Type' => 'application/json',
'Mobile-no' => '09352673656',
'National-code' => '0082205388',
'Authorization' => 'Bearer b71c3737-7b89-4f2c-9301-767439079407',
])->post('https://payman2.sandbox.faraboom.co/v1/payman/create', [
'payman' => [
'bank_code' => 'SINAIR',
'user_id' => 'demopayman',
'permission_ids' => [1],
'contract' => [
'expiration_date' => '2026-01-15T01:28:09.5662061+04:30', // Updated expiration date
'max_daily_transaction_count' => 50,
'max_monthly_transaction_count' => 100,
'max_transaction_amount' => 500000,
'start_date' => '2025-01-15T08:28:09.5662061+04:30',
'Daily_max_transaction_amount' => 500000000,
]
],
'redirect_url' => 'https://api.gholaktala.ir/',
'trace_id' => $t,
]);
return $response->getStatusCode().$t.$response;
/*{
"access_token": "b71c3737-7b89-4f2c-9301-767439079407",
"token_type": "bearer",
"scope": "all",
"expires_in": 28954155
}*/
}
/**
* Retrieve details for a specific trace ID.
*/
public function createTrace()
{
$traceId = Str::uuid()->toString();
$response = Http::timeout(4)->withHeaders([
'Cookie' => 'cookiesession1=678A8C341A085F7AF93FECC7B44ACDFO',
'Authorization' => 'Bearer ' . $this->accessToken, // Using stored access token
])->get('https://payman2.sandbox.faraboom.co/v1/payman/create/trace', [
'trace_id' => $traceId,
'redirect_url' => 'https://api.gholaktala.ir/',
]);
if ($response->status() === 302) {
$location = $response->header('Location');
return redirect()->away($location);
}
return response()->json([
'headers' => $response->headers(),
'body' => $response->body(),
]);
}
/**
* Get Payman account ID by payman_code.
*/
public function getId()
{
$url = 'https://payman2.sandbox.faraboom.co/v1/payman/getId';
$paymanCode = '2gZ04Yx9iHEP'; // You may want to dynamically set this value
return $response = Http::timeout(4)
->withHeaders([
'Authorization' => 'Bearer ' . $this->accessToken, // Using stored access token
'App-Key' => 'demopayman',
'Cookie' => 'cookiesession1=678A8C341A085F7AF93FECC7B44ACDFF',
])
->get($url, [
'payman_code' => $paymanCode // pass the payman_code as a query parameter
])->json();
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace App\Http\Controllers\pay;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
class paypingController extends Controller
{
public function startTransation(Request $request)
{
$user = auth()->user();
$finalPriseP = $request->value;
if ($user->id ==4){
$finalPriseP =10700;
}
$Withdraw = Withdraw::create([
'customer_id' => auth('customer')->id(),
"cash" => $finalPriseP,
"note" => "واریز ریالی",
'sts' => 1,
]);
try {
$response = Http::withHeaders([
'payping' => '@XOKcNveJ$wpqYy%rdpb78oBh31Aos*bIdQemiUeeq9e9G!oey23SMXp40Ew2fodjx9J5buKNW0M4@nYMr1PR6d0KtuqhLQlx*K$', // Custom header with 'payping' value
])->post("https://payping.limangold.ir/payment/start", [
"amount" => $finalPriseP/10, // Payment amount
"user_name" => $user->name, // User name
"user_id" => $user->id, // User ID
"user" => $user, // User ID
"title" => $this->Config('name_fa'), // Title of the payment
"return_url" => "https://".$this->Config('app_url')."/transactions", // Callback URL
"server_call_url" => url("/customer/charge_account_verify/".$Withdraw->id), // Callback URL
"item" => "gp1Q", // Item identifier
])->json();
}catch (\Exception $exception){
return response()->json(["message"=>"مشکل در ارتباط با درگاه","R"=>$response??$exception,], 422);
}
$Withdraw->tracked_number = $response['id'];
$Withdraw->save();
return $response['url'];
return response()->json(["res"=>$response], 422);
}
public function verifyTransationByID(Request $request ,$id)
{
if ($request->header('payping') !== '@XOKcNveJ$wpqYy%rdpb78oBh31Aos*bIdQemiUeeq9e9G!oey23SMXp40Ew2fodjx9J5buKNW0M4@nYMr1PR6d0KtuqhLQlx*K$') {
return response()->json(['auth needed'], 401);
}
$Withdraw = Withdraw::with('customer')->where('id',$id)->first();
$app_url = $this->Config('app_url');
$User = Customer::where('id', $Withdraw->customer_id)->first();
$GTransaction = Http::withHeaders([
'payping' => '@XOKcNveJ$wpqYy%rdpb78oBh31Aos*bIdQemiUeeq9e9G!oey23SMXp40Ew2fodjx9J5buKNW0M4@nYMr1PR6d0KtuqhLQlx*K$', // Custom header with 'payping' value
])->post("https://payping.limangold.ir/payment/verify", [
"id" => "$Withdraw->tracked_number",
])->json();
if (isset( $GTransaction['active']) and $GTransaction['active'] == 5) {
if ($Withdraw->cash == $GTransaction['amount'] * 10) {
$Withdraw->zify_code = $Withdraw->tracked_number;
$Withdraw->tracked_number = $GTransaction['invoiceNo'];//ok
$Withdraw->sts = 2;//ok
$Withdraw->save();
$wallet_interface_fund = new WalletInterface($User->id, $User->type);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"cash" => $GTransaction['amount'] * 10,
'expire_at' => now(),
'withdraw_id' => $Withdraw->id,
'active' => true
], 3, false, true);
//----------sms
$userMobile = $Withdraw->customer->mobile; // User's mobile number
$userName = $Withdraw->customer->name; // User's name
$chargedAmount = $Withdraw->cash; // Charged amount
$companyName = $this->Config('name_fa'); // Company name from configuration
$message = "کاربر $userName با شماره موبایل $userMobile حساب خود را به مقدار " . number_format($chargedAmount) . " ریال شارژ کرد. با تشکر، $companyName";
User::where('send_sms', 1)->get()->each(function($admin) use ($message) {
$this->Send($admin->mobile, $message);
});
return view('showTransactionReport', compact('Withdraw','app_url'));
return redirect('https://app.gholaktala.ir/transactions');
}
return "مبلغ پرداختی دستکاری شده !";
} else {
$Withdraw->tracked_number;
$Withdraw->sts = 3;//no
$Withdraw->save();
return view('showTransactionReport', compact('Withdraw','app_url'));
}
}
public function verifyTransation()
{
$Withdraw = Withdraw::with('customer')->where('id', $_GET['clientrefid'])->first();
$app_url = $this->Config('app_url');
$User = Customer::where('id', $Withdraw->customer_id)->first();
$url = 'https://zify.ir/api/order/v2/verify';
$payload = [
"order" => "$Withdraw->tracked_number",
];
$verifyResponse = Http::withToken("cf09ee0187335f173c786e7660d778d2dd71ab582d282999f751427f5923d525")
->post($url, $payload);
$decodedResponse = json_decode($verifyResponse, true);
$verifyMessage = $decodedResponse['message'];
// return $decodedResponse['data'];
if (isset($decodedResponse['data']['refid']) || $verifyMessage == []) {
if ($Withdraw->cash == $decodedResponse['data']['amount'] * 10) {
$Withdraw->zify_code = $Withdraw->tracked_number;//ok
$Withdraw->tracked_number = $decodedResponse['data']['refid'];//ok
$Withdraw->sts = 2;//ok
$Withdraw->save();
$wallet_interface_fund = new WalletInterface($User->id, $User->type);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"cash" => $decodedResponse['data']['amount'] * 10,
'expire_at' => now(),
'withdraw_id' => $_GET['clientrefid'],
'active' => true
], 3, false, true);
$User = Customer::where('id', $Withdraw->customer_id)->first();
$url = 'https://limangold.ir/kernel/admin/fin';
$payload = [
"amount" => $decodedResponse['data']['amount'] * 10,
"customer_id" => "23",
"date_at" => \Carbon\Carbon::today()->format('Y/m/d'),
"receive_account_number" => "000",
"receive_bank" => "پیپینگ",
"receive_name" => "لیمان گلد",
"send_account_number" => "000",
"send_bank" => " زیفای کد $Withdraw->zify_code",
"send_name" => $User->name,
"track_number" => $decodedResponse['data']['refid'],
"type" => 1,
];
$verifyResponse = Http::withToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvbGltYW5nb2xkLmlyXC9rZXJuZWxcL2F1dGhcL2xvZ2luIiwiaWF0IjoxNzI3NTMwNjA0LCJleHAiOjE3MzAxMjI2MDQsIm5iZiI6MTcyNzUzMDYwNCwianRpIjoiYXBINmlPZXlGTE9oTUhRdyIsInN1YiI6MiwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.IrO6icD-EXjgZ3mYyeEAP4aqG7q35yJTCU_hQhEDGwk")
->post($url, $payload);
//----------sms
// User information
$userMobile = $Withdraw->customer->mobile; // User's mobile number
$userName = $Withdraw->customer->name; // User's name
$chargedAmount = $Withdraw->cash; // Charged amount
// Company name
$companyName = $this->Config('name_fa'); // Company name from configuration
// Constructing the SMS message
$message = "کاربر $userName با شماره موبایل $userMobile حساب خود را به مقدار " . number_format($chargedAmount) . " ریال شارژ کرد. با تشکر، $companyName";
// Getting admin mobile numbers and sending the SMS
User::where('send_sms', 1)->get()->each(function($admin) use ($message) {
$this->Send($admin->mobile, $message);
});
return view('showTransactionReport', compact('Withdraw','app_url'));
return redirect('https://app.gholaktala.ir/transactions');
}
return "مبلغ پرداختی دستکاری شده !";
} else {
$Withdraw->tracked_number;
$Withdraw->sts = 3;//no
$Withdraw->save();
return view('showTransactionReport', compact('Withdraw','app_url'));
}
}
}
+69
View File
@@ -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,
];
}
+21
View File
@@ -0,0 +1,21 @@
<?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 (! $request->expectsJson()) {
return route('login');
}
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
+32
View File
@@ -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);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
+49
View File
@@ -0,0 +1,49 @@
<?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)) {
$match_id = $match[0];
$path = preg_replace('/[0-9]+$/', '{id}', $request->path());
}
$format = 'validation.'.$path.'@'.strtolower($method);
if (config($format)) {
if ($path == 'admin/user/{id}'){
$replace = preg_replace('/update_id/', $match_id, config($format));
$validator = Validator::make($request->all(), $replace);
}
// 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();
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
+16
View File
@@ -0,0 +1,16 @@
[10-Jun-2024 13:13:18 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance' not found in /home/montechi/public_html/server_app/app/Http/Middleware/PreventRequestsDuringMaintenance.php:7
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Http/Middleware/PreventRequestsDuringMaintenance.php on line 7
[10-Jun-2024 13:18:13 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Http\Middleware\TrustHosts' not found in /home/montechi/public_html/server_app/app/Http/Middleware/TrustHosts.php:7
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Http/Middleware/TrustHosts.php on line 7
[10-Jun-2024 13:19:38 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Cookie\Middleware\EncryptCookies' not found in /home/montechi/public_html/server_app/app/Http/Middleware/EncryptCookies.php:7
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Http/Middleware/EncryptCookies.php on line 7
[10-Jun-2024 15:50:57 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Http\Middleware\TrustProxies' not found in /home/montechi/public_html/server_app/app/Http/Middleware/TrustProxies.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Http/Middleware/TrustProxies.php on line 8
+4
View File
@@ -0,0 +1,4 @@
[10-Jun-2024 15:14:07 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Http\Kernel' not found in /home/montechi/public_html/server_app/app/Http/Kernel.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Http/Kernel.php on line 8
+53
View File
@@ -0,0 +1,53 @@
<?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 Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
class CheckOrder 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 = 3;
$order->save();
$wallet_interface = new WalletInterface($order->customer_id, 1);
new TransactionInterface($wallet_interface, $_inp = [
"cash" => $order->total_price,
"gold" => $order->amount,
'expire_at'=>now()->addYear(),
'active'=>true,
'order_id'=>$order->id,
'note'=>'کنسل شدن سفارش'
], 1, false,true,(-1*$order->amount));
}
}
}
+12
View File
@@ -0,0 +1,12 @@
[10-Jun-2024 20:04:30 UTC] PHP Fatal error: Uncaught Error: Interface 'Illuminate\Contracts\Queue\ShouldQueue' not found in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php on line 15
[10-Jun-2024 20:06:01 UTC] PHP Fatal error: Uncaught Error: Interface 'Illuminate\Contracts\Queue\ShouldQueue' not found in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php on line 15
[10-Jun-2024 20:09:52 UTC] PHP Fatal error: Uncaught Error: Interface 'Illuminate\Contracts\Queue\ShouldQueue' not found in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Jobs/CheckOrder.php on line 15
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
protected $table = 'settings';
protected $fillable = [
'key',
'title_fa',
'value',
];
protected $casts = [
];
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class YourMailableClass extends Mailable
{
use Queueable, SerializesModels;
public $transactionId;
public $transactionDate;
public $quantity;
public $price;
public $totalAmount;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($transactionId, $transactionDate, $quantity, $price, $totalAmount)
{
$this->transactionId = $transactionId;
$this->transactionDate = $transactionDate;
$this->quantity = $quantity;
$this->price = $price;
$this->totalAmount = $totalAmount;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.transaction_notification')
->with([
'transactionId' => $this->transactionId,
'transactionDate' => $this->transactionDate,
'quantity' => $this->quantity,
'price' => $this->price,
'totalAmount' => $this->totalAmount,
]);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
use HasFactory,Selector;
public $timestamps=FALSE;
protected $fillable =[
'city',
'province',
'phone',
'address',
'zip',
'customer_id',
'major_id',
'default_address',
];
protected $casts = [
'default_address'=>'boolean'
];
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class BankAccount extends Model
{
use HasFactory,SoftDeletes,Selector;
protected $fillable = [
'customer_id',
'cart_number',
'shaba_number',
'bank_name',
'account_number',
'sts'
];
static $STS = [
1=>'در انتظار تایید',
2=>'تایید شده',
3=>'رد شده',
];
public function customer(){
return $this->belongsTo(Customer::class);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable=[
'title',
'code',
'parent_id',
'has_children',
'level'
];
protected $casts = [
'has_children'=>'boolean'
];
static $LEVEL = [
1=>'استان',
2=>'شهر',
];
public function children(){
return $this->hasMany(City::class,'parent_id')->with('children');
}
public function parent(){
return $this->belongsTo(City::class,'parent_id')->with('parent');
}
}
+21
View File
@@ -0,0 +1,21 @@
<?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',
'value_json'
];
protected $casts = [
'value_json'=>'array'
];
}
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Hash;
use Rooyesh\Wallet\models\Wallet;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class Customer extends Authenticatable implements JWTSubject
{
use HasFactory,SoftDeletes,Selector;
protected $fillable = [
'fname',
'lname',
'name',
'active',
'finger_print',
'mobile',
'email',
'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',
'referral_id',
'referral_to_id',
'credential_id',
'moshtari_code',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'token_sms',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
"active" => "boolean",
"gold" => "float",
"is_archive" => "boolean",
"finger_print" => "boolean",
];
static $TYPE = [
1=>'همکار',
2=>'خانگی',
3=>'سرمایه گذار'
];
static $TYPES = [
1=>'همکار',
2=>'خانگی',
3=>'سرمایه گذار'
];
public function setNameAttribute($value = null)
{
$fname = $this->attributes['fname'] ?? '';
$lname = $this->attributes['lname'] ?? '';
$this->attributes['name'] = trim("$fname $lname");
}
public function wallet()
{
return $this->hasMany(Wallet::class ,'owner')->with(['fund','product'])->select(['cash', 'fund_id','product_id','gold', 'owner']);
}
public function user()
{
return $this->belongsTo(User::class)->select(['id','name']);
}
public function referral()
{
return $this->belongsTo(Customer::class, 'referral_to_id', 'referral_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 tahesab()
{
return $this->hasMany(Tahesab::class, 'customer_id', 'id');
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Rooyesh\Wallet\models\Wallet;
class Fund extends Model
{
use HasFactory,Selector,SoftDeletes;
protected $fillable =[
'title',
'file_id',
'customer_id',
];
public function wallet()
{
return $this->hasMany(Wallet::class);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Log extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'customer_id',
'data'
];
public function customer()
{
return $this->belongsTo(Customer::class)->select(['id','name']);
}
public function user()
{
return $this->belongsTo(User::class)->select(['id','name']);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?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 $receiver;
protected $fillable = [
'sms',
'receiver',
'platforms',
];
// public function receiver(){
// return $this->belongsTo(Customer::class,'receiver',"mobile")->select(['id','name','mobile','n_code','is_legal']);
// }
public function person()
{
return $this->belongsTo(Customer::class, 'receiver', 'mobile')
->select(['id', 'name', 'mobile', 'n_code', 'is_legal'])
->withDefault(function ($receiver) {
$mobile = $this->receiver;
if ($mobile && $user = User::where('mobile', $mobile)->first()) {
$receiver->fill($user->only(['id', 'name', 'mobile', 'n_code', 'is_legal']));
}
});
}
}
+64
View File
@@ -0,0 +1,64 @@
<?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',
'amount',//میزان طلا
'price',//قیمت هر گرم طلا برای مشتری
'total_price',//قیمت کل برای مشتری
'price_original',//قیمت هر گرم طلا بدون سود
'total_price_liman',//قیمت هر گرم طلا بدون سود
'total_price_original',//قیمت کل بدون سود
'fee',//سود هر گرم
'total_fee',//سود کل
'service_charge_percentage',//درصد کارمزد
'service_charge',//میزان کارمزد
'service_charge_price',//مبلغ کارمزد به ریال
'payment_sts',
'payment_amount',//میزان پرداخت شده
'payment_remind',//میزان مبلغ باقی مانده
'type',//نوع مشتری
'pay_at',//تاریخ انجام معامله در پنل ادمین
'price_id',//
];
static $STS = [
1 => 'باز',
2 => 'موفق',
3 => 'ناموفق'
];
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);
}
public function transactions(){
return $this->hasMany(Transaction::class);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Price extends Model
{
use HasFactory;
protected $fillable = [
"price",
"date_at",
"time_at",
"user_id"
];
public function user()
{
return $this->belongsTo(User::class)->select(['id','name']);
}
public function order(){
return $this->hasMany(Order::class, 'price_id');
}
}
+18
View File
@@ -0,0 +1,18 @@
<?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"
];
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PriceTrigger extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'customer_id',
'target_price',
'price_condition',
'action',
'is_active',
'triggered_at',
];
protected $casts = [
"is_active" => "boolean",
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
+121
View File
@@ -0,0 +1,121 @@
<?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', // The title of the record.
'price', // The amount of the record.
'amount', // The amount of the record.
'unit', // The unit of the item.
'group_type', // The unit of the item.
'file_id', // The ID of the associated file.
'can_canceled', // Whether the record can be canceled (boolean).
'active', // The active status of the record (boolean).
'for_barayand', // Whether it is for Barayand (boolean).
'show', // Whether to show the record (boolean).
'open_sell', // Whether selling is open (boolean).
'auto_open_at', // Whether selling is open (boolean).
'auto_close_at', // Whether selling is open (boolean).
'kalhor_name', // The name of the Kalhor entity.
'default_credit', // Default credit amount.
'reading_method', // The method of reading.
'open_buy', // Whether buying is open (boolean).
'percent_fee_sell', // Add percent_fee_sell to fillable
'cash_fee_buy', // Add cash_fee_buy to fillable
'cash_fee_sell', // Add cash_fee_sell to fillable
'percent_fee_buy', // Add percent_fee_buy to fillable
'metal_id', //the material of metal (#gold or #silver)
];
protected $casts = [
'can_canceled' => 'boolean', // Cast to boolean.
'active' => 'boolean', // Cast to boolean.
'show' => 'boolean', // Cast to boolean.
'for_barayand' => 'boolean', // Cast to boolean.
'open_sell' => 'boolean', // Cast to boolean.
'auto_sell' => 'boolean', // Cast to boolean (you mentioned this in your casts but it's missing in `$fillable`).
'open_buy' => 'boolean', // Cast to boolean.
'auto_buy' => 'boolean', // Cast to boolean.
'price' => 'int', // Cast to float.
'percent_fee_sell' => 'float', // Cast to float.
'percent_fee_buy' => 'float', // Cast to float.
'cash_fee_buy' => 'int', // Cast to int or decimal if needed
'cash_fee_sell' => 'int', // Cast to int or decimal if needed
];
static $METAL_ID = [
1=>'طلا',
2=>'نقره',
];
public function wallet()
{
return $this->hasOne(Wallet::class);
}
public function walletMy()
{
return $this->hasOne(Wallet::class)->where('owner',auth()->user()->id);
}
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 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','سند ورود طلا');
}
}
+260
View File
@@ -0,0 +1,260 @@
<?php
/**
* Created by PhpStorm.
* User: AraNote
* Date: 29/04/2018
* Time: 04:38 PM
*/
namespace App\Models;
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;
return Verta::instance($value)->format(self::$DATE_FORMAT);
}
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;
}
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));
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
protected $table = 'settings';
protected $fillable = [
'key',
'title_fa',
'value',
'value_json'
];
protected $casts = [
'value_json'=>'array'
];
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tahesab extends Model
{
use HasFactory;
protected $table = 'tahesab';
protected $fillable = [
'customer_id',
'amount',
'desc',
'order_id',
'date',
'created_at',
'updated_at',
'sh_factor',
'tahesab_id',
'res',
'factor_number',
'tah_id',
];
static $STS = [
1 => 'باز',
2 => 'موفق',
3 => 'ناموفق'
];
static $DIRECTION = [
1 => 'خرید',
2 => 'فروش'
];
static $PAYMENT_STS=[
1 => 'در انتظار پرداخت',
2 => 'در حال پرداخت',
3 => 'partially_paid',
4 => 'پرداخت شده',
5 => 'partially_refunded',
6 => 'مرجوعی',
7 => 'پرداخت نشده',
];
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id', 'id');
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class TransactionsAdmin extends Model
{
use HasFactory,SoftDeletes,Selector;
protected $fillable = [
'customer_id',
'order_id',
'customer_to_id',
'user_id',
'wallet',
'transaction_id',
'cash',
'note',
'type',
'gold',
'balance_cash',
'balance_gold',
'withdraw_id',
];
// static $STS = [
// 1=>'در انتظار تایید',
// 2=>'تایید شده',
// 3=>'رد شده',
// ];
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function customerTo()
{
return $this->belongsTo(Customer::class, 'customer_to_id');
}
public function user()
{
return $this->belongsTo(User::class);
}
public function order()
{
return $this->belongsTo(Order::class);
}
// public function transaction()
// {
// return $this->belongsTo(\Rooyesh\Wallet\Models\Transaction::class, 'transaction_id');
// }
public function withdraw()
{
return $this->belongsTo(Withdraw::class);
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable,Selector,SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'fname',
'lname',
'name',
'password',
'mobile',
'user_type',
'token_sms',
'last_seen_at',
'active',
'send_sms',
'avatar_id',
'email',
'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',
'send_sms'=> 'boolean',
];
/**
* 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);
}
}
+1
View File
@@ -0,0 +1 @@
<?php␍␍namespace App\Models;␍␍use Illuminate\Database\Eloquent\Factories\HasFactory;␍use Illuminate\Database\Eloquent\Model;␍use Rooyesh\Wallet\models\Transaction;␍␍␍class Withdraw extends Model␍{␍ use HasFactory,Selector;␍ protected $fillable = [␍ 'customer_id',␍ 'user_id',␍ 'cash',␍ 'gold',␍ 'note',␍ 'tracked_number',␍ 'bank_account_id',␍ 'date_at',//تاریخ و ساعت واریز␍ 'sts',␍ 'type',␍ ];␍ static $STS = [␍ 1 => 'در انتظار واریز',␍ 2 => 'واریز شد',␍ 4 => 'واریز توسط ادمین',␍ 5 => 'پاداش معرفی',␍ 9 => 'سود زیر مجموعه',␍ 3 => 'واریز ناموفق',␍ 50 => 'در انتظار ارسال',␍ 51 => 'ارسال شده',␍ 52 => 'لغو شده',␍ ];␍ public function customer()␍ {␍ return $this->belongsTo('App\Models\Customer')->select(['id','name',"mobile"]);␍ }␍ public function Address()␍ {␍ return $this->belongsTo('App\Models\Address');␍ }␍ public function Transaction()␍ {␍ return $this->hasMany(Transaction::class, 'withdraw_id', 'id');␍ }␍ public function bank_account()␍ {␍ return $this->hasOne('App\Models\BankAccount','id','bank_account_id');␍ }␍}␍
+168
View File
@@ -0,0 +1,168 @@
[10-Jun-2024 05:12:23 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Order.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Order.php on line 8
[10-Jun-2024 05:12:47 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Log.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Log.php on line 8
[10-Jun-2024 08:43:37 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Fund.php:10
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Fund.php on line 10
[10-Jun-2024 08:46:18 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/Customer.php:13
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Customer.php on line 13
[10-Jun-2024 08:49:06 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
[10-Jun-2024 08:49:30 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 15:43:01 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Price.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Price.php on line 8
[10-Jun-2024 15:46:46 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Withdraw.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Withdraw.php on line 8
[10-Jun-2024 20:04:25 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Cnt.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Cnt.php on line 8
[10-Jun-2024 20:04:25 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/Customer.php:13
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Customer.php on line 13
[10-Jun-2024 20:04:25 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Fund.php:10
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Fund.php on line 10
[10-Jun-2024 20:04:26 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/User.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/User.php on line 15
[10-Jun-2024 20:04:28 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Price.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Price.php on line 8
[10-Jun-2024 20:04:29 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Order.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Order.php on line 8
[10-Jun-2024 20:04:30 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Log.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Log.php on line 8
[10-Jun-2024 20:04:31 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 20:04:35 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
[10-Jun-2024 20:05:30 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Withdraw.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Withdraw.php on line 8
[10-Jun-2024 20:05:32 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Log.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Log.php on line 8
[10-Jun-2024 20:05:39 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Price.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Price.php on line 8
[10-Jun-2024 20:05:40 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/Customer.php:13
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Customer.php on line 13
[10-Jun-2024 20:05:46 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Fund.php:10
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Fund.php on line 10
[10-Jun-2024 20:05:51 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Cnt.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Cnt.php on line 8
[10-Jun-2024 20:05:54 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Order.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Order.php on line 8
[10-Jun-2024 20:05:55 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/User.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/User.php on line 15
[10-Jun-2024 20:06:09 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 20:06:10 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
[10-Jun-2024 20:07:30 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Log.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Log.php on line 8
[10-Jun-2024 20:07:30 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Withdraw.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Withdraw.php on line 8
[10-Jun-2024 20:07:51 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Cnt.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Cnt.php on line 8
[10-Jun-2024 20:07:54 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Order.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Order.php on line 8
[10-Jun-2024 20:07:56 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/User.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/User.php on line 15
[10-Jun-2024 20:07:58 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 20:07:58 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
[10-Jun-2024 20:09:52 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Order.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Order.php on line 8
[10-Jun-2024 20:09:53 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
[10-Jun-2024 20:09:53 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 20:10:42 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/BankAccount.php:9
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/BankAccount.php on line 9
[10-Jun-2024 20:10:56 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Auth\User' not found in /home/montechi/public_html/server_app/app/Models/User.php:15
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/User.php on line 15
[10-Jun-2024 20:11:06 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Cnt.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Cnt.php on line 8
[10-Jun-2024 20:11:44 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/Fund.php:10
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/Fund.php on line 10
[10-Jun-2024 20:11:56 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Database\Eloquent\Model' not found in /home/montechi/public_html/server_app/app/Models/PriceCandle.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Models/PriceCandle.php on line 8
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* @var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::prefix('auth')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/auth.php'));
Route::prefix('admin')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
Route::prefix('customer')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/customer.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
}
+20
View File
@@ -0,0 +1,20 @@
[10-Jun-2024 01:41:36 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Support\Providers\AuthServiceProvider' not found in /home/montechi/public_html/server_app/app/Providers/AuthServiceProvider.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Providers/AuthServiceProvider.php on line 8
[10-Jun-2024 01:42:04 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Support\ServiceProvider' not found in /home/montechi/public_html/server_app/app/Providers/BroadcastServiceProvider.php:8
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Providers/BroadcastServiceProvider.php on line 8
[10-Jun-2024 01:42:33 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Support\Providers\RouteServiceProvider' not found in /home/montechi/public_html/server_app/app/Providers/RouteServiceProvider.php:11
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Providers/RouteServiceProvider.php on line 11
[10-Jun-2024 01:43:01 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Foundation\Support\Providers\EventServiceProvider' not found in /home/montechi/public_html/server_app/app/Providers/EventServiceProvider.php:10
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Providers/EventServiceProvider.php on line 10
[10-Jun-2024 01:46:49 UTC] PHP Fatal error: Uncaught Error: Class 'Illuminate\Support\ServiceProvider' not found in /home/montechi/public_html/server_app/app/Providers/AppServiceProvider.php:7
Stack trace:
#0 {main}
thrown in /home/montechi/public_html/server_app/app/Providers/AppServiceProvider.php on line 7
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class NotificationService
{
protected $endpoint;
protected $primaryKey;
public function __construct()
{
$this->endpoint = 'https://<your-namespace>.servicebus.windows.net/<your-notification-hub>/messages';
$this->primaryKey = env('AZURE_NOTIFICATION_HUB_PRIMARY_KEY');
}
public function sendNotification($message)
{
$response = Http::withHeaders([
'Authorization' => $this->primaryKey,
'Content-Type' => 'application/json'
])->post($this->endpoint, [
'data' => $message
]);
return $response->json();
}
}
+256
View File
@@ -0,0 +1,256 @@
# Changelog
## 7.2.4
* [Fixed] Timeout option is propagated to guzzle client
## 7.2.3
* [Fixed] Include socket_id in batch trigger if included.
## 7.2.2
* [FIXED] composer.phar file removed from package
## 7.2.1
* [FIXED] authenticateUser returns correct auth value
## 7.2.0
* [CHANGED] explicit support for 8.1
* [CHANGED] Ignore pull_request_template.md on vendor
* [ADDED] has_mixed_channels method to allow triggering a single event on multiple channels
* [FIXED] path option can be used for proxied servers under subdirectory.
* [CHANGED] base_path's leading slash is trimmed on every call to Guzzle.
## 7.1.0-beta
* [ADDED] `authenticateUser`, `authorizeChannel` and `authorizePresenceChannel`
* [ADDED] `sendToUser` and `sendToUserAsync`
* [ADDED] `terminateUserConnections` and `terminateUserConnectionsAsync`
* [FIXED] `get_object_vars()` error on `/src/Pusher.php`
* [DEPRECATED] `socketAuth` and `presenceAuth` in favour of `authorizeChannel` and `authorizePresenceChannel`
* [DEPRECATED] Internal functions `make_request` and `make_batch_request` that were exposed as public
## 7.0.2
* [CHANGED] Add psr/log v2.0 and v3.0 compatibility
## 7.0.1
* [FIXED] Infinite recursion in `presence_auth`.
## 7.0.0
* [DEPRECATED] `get_channel_info`, `get_channels`, `socket_auth`, `presence_auth` in favour of camelCased versions
* [DEPRECATED] `get_users_info` in favour of `getPresenceUsers`
* [DEPRECATED] `ensure_valid_signature` in favour of `verifySignature`
* [CHANGED] Restrict `$app_id` parameter of the `Pusher()` object to `string` (`int` was possible).
* [ADDED] Return types.
* [ADDED] Namespacing, PSR-12 formatting.
## 6.1.0
* [ADDED] triggerAsync and triggerBatchAsync using the Guzzle async interface.
## 6.0.1
* [CHANGED] Use type hints where possible (mixed type not available in PHP7).
* [CHANGED] Document that functions can throw GuzzleException.
## 6.0.0
* [CHANGED] internal HTTP client to Guzzle
* [ADDED] optional client parameter to constructor
* [CHANGED] useTLS is true by default
* [REMOVED] `curl_options` from options
* [REMOVED] customer logger
* [REMOVED] host, port and timeout constructor parameters
* [REMOVED] support for PHP 7.1
* [CHANGED] lower severity level of logging to DEBUG level
## 5.0.3
* [CHANGED] Ensure version in Pusher.php is bumped on release.
## 5.0.2
* [CHANGED] Add release automation actions.
## 5.0.1
* [FIXED] Notice raised due to reference to potentially missing object property in `trigger` method
## 5.0.0
* [CHANGED] The methods that make HTTP requests now throw an `ApiErrorException` instead of returning `false` for non-2xx responses
* [CHANGED] `trigger` now accepts a `$params` associative array instead of a `$socket_id` as the third parameter
* [ADDED] Support for requesting channel attributes as part of a `trigger` and `triggerBatch` request via an `info` parameter
* [REMOVED] `debug` parameter from methods that make HTTP requests and from the constructor options
* [REMOVED] Support for legacy push notifications (this has been superseded by https://github.com/pusher/push-notifications-php)
## 4.1.5
* [ADDED] Support for PHP 8.
## 4.1.4
* [FIXED] Errors in the failure path of `get_...` methods revealed by stricter type checking in PHP7.4
## 4.1.3
* No functional change, previous release was only partially successful
## 4.1.2
* [ADDED] option `encryption_master_key_base64`
* [DEPRECATED] option `encryption_master_key`
## 4.1.1
* [ADDED] Support for PHP 7.4.
## 4.1.0
* [ADDED] `path` configuration option.
## 4.0.0
* [REMOVED] Support for PHP 5.x, PHP 7.0 and HHVM.
## 3.4.1
* [ADDED] Support for PHP 7.3.
## 3.4.0
* [ADDED] `get_users_info` method.
## 3.3.1
* [FIXED] PHP Notice for Undefined `socket_id` in triggerBatch
## 3.3.0
* [ADDED] Support for End-to-end encrypted channels for triggerbatch
* [FIXED] trigger behavior with mixtures of encrypted and non-encrypted channels
## 3.2.0
* [ADDED] This release adds support for end to end encrypted channels, a new feature for Channels. Read more [in our docs](https://pusher.com/docs/client_api_guide/client_encrypted_channels).
* [DEPRECATED] Renamed `encrypted` option to `useTLS` - `encrypted` will still work!
## 3.1.0
* [ADDED] This release adds Webhook validation as well as a data structure to store Webhook payloads.
## 3.0.4
* [FIXED] Non zero indexed arrays of channels no longer get serialized as an object.
## 3.0.3
* [ADDED] PSR-3 logger compatibility.
* [CHANGED] Improved PHP docs.
## 3.0.2
* [FIXED] Insufficient check for un-initialized curl resource.
* [FIXED] Acceptance tests.
## 3.0.1
* [CHANGED] Info messages are now prefixed with INFO and errors are now prefixed with ERROR.
## 3.0.0
* [NEW] Added namespaces (thanks [@vinkla](https://github.com/vinkla)).
## 2.6.4
* [FIXED] Log the curl error in more circumstances
## 2.6.1
* [FIXED] Check for correct status code when POSTing to native push notifications API.
## 2.6.0
* [ADDED] support for publishing push notifications on up to 10 interests.
## 2.5.0
* [REMOVED] Native push notifications payload validation in the client.
## 2.5.0-rc2
* [FIXED] DDN and Native Push endpoints were not assembled correctly.
## 2.5.0-rc1
* [NEW] Native push notifications
## 2.4.2
* [CHANGED] One curl instance per Pusher instance
## 2.4.1
* [FIXED] Presence data could not be submitted after the style changes
## 2.4.0
* [ADDED] Support for batch events
* [ADDED] Curl options
* [FIXED] Applied fixes from StyleCI
## 2.3.0
* [ADDED] A new `cluster` option for the Pusher constructor.
## 2.2.2
* [FIXED] Fixed a PHP 5.2 incompatibility caused by referencing a private method in array_walk.
## 2.2.1
* [FIXED] Channel name and socket_id values are now validated.
* [BROKE] Inadvertently broke PHP 5.2 compatibility by referencing a private method in array_walk.
## 2.2.0
* [CHANGED] `new Pusher($app_key, $app_secret, $app_id, $options)` - The `$options` parameter
has been added as the forth parameter to the constructor and other additional
parameters are now deprecated.
## 2.1.3
* [NEW] `$pusher->trigger` can now take an `array` of channel names as a first parameter to allow the same event to be published on multiple channels.
* [NEW] `$pusher->get` generic function can be used to make `GET` calls to the REST API
* [NEW] `$pusher->set_logger` to allow internal logging to be exposed and logged in your own logs.
## 2.1.2
* [CHANGED] Debug response from `$pusher->trigger` call is now an associative array in the form `array( 'body' => '{String} body text of response', 'status' => '{Number} http status of the response' )`
## 2.1.1
* [CHANGED] Added optional $options parameter to get_channel_info. get_channel_info($channel, $options = array() )
## 2.1.0
* [CHANGED] Renamed get_channel_stats to get_channel_info
* [CHANGED] get_channels now takes and $options parameter. get_channels( $options = array() )
* [REMOVED] get_presence_channels
## 2.0.1
* [FIXED] Overwritten socket_id parameter in trigger: https://github.com/pusher/pusher-php-server/pull/3
## 2.0.0
* [NEW] Versioning introduced at 2.0.0
* [NEW] Added composer.json for submission to https://packagist.org/
* [CHANGED] `get_channels()` now returns an object which has a `channels` property. This must be accessed to get the Array of channels in an application.
* [CHANGED] `get_presence_channels()` now returns an object which has a `channels` property. This must be accessed to get the Array of channels in an application.
+36
View File
@@ -0,0 +1,36 @@
{
"name": "pusher/pusher-php-server",
"description" : "Library for interacting with the Pusher REST API",
"keywords": ["php-pusher-server", "pusher", "rest", "realtime", "real-time", "real time", "messaging", "push", "trigger", "publish", "events"],
"license": "MIT",
"require": {
"php": "^7.3|^8.0",
"ext-curl": "*",
"ext-json": "*",
"guzzlehttp/guzzle": "^7.2",
"psr/log": "^1.0|^2.0|^3.0",
"paragonie/sodium_compat": "^1.6"
},
"require-dev": {
"phpunit/phpunit": "^9.3",
"overtrue/phplint": "^2.3"
},
"autoload": {
"psr-4": {
"Pusher\\": "src/"
}
},
"autoload-dev": {
"psr-4": { "": "tests/" }
},
"config": {
"preferred-install": "dist"
},
"extra": {
"branch-alias": {
"dev-master": "5.0-dev"
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
+16
View File
@@ -0,0 +1,16 @@
<?php
require 'pusher/pusher-http-php-master/lib/Pusher.php';
$options = [
'cluster' => 'your_cluster',
'useTLS' => true
];
$pusher = new Pusher\Pusher(
'your_app_key',
'your_app_secret',
'your_app_id',
$options
);
$data['message'] = 'hello world';
$pusher->trigger('my-channel', 'my-event', $data);

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