This commit is contained in:
2024-11-25 19:32:51 +05:00
parent 7259cdcb26
commit 9d77e50191
11 changed files with 557 additions and 77 deletions

View File

@@ -84,69 +84,10 @@ class OnlinePaymentController extends Controller
return view(OnlinePaymentRepo::statusView(), $data);
}
public function sber(Request $request)
public function sber(OnlinePaymentStoreRequest $request)
{
// Validate the order id
if (
validator(
$request->all(),
['orderId' => ['required', 'string', 'max:50', 'exists:online_payment_histories,orderId']]
)->fails()
) {
return ['wrong order id'];
}
$data = OnlinePaymentRepo::checkPaymentSber($request);
// Find order from history
$paymentHistory = OnlinePaymentHistory::where('orderId', $request->orderId)->first();
// Find related resource
$resource = (new $paymentHistory->online_paymantable_type)->find(id: $paymentHistory->online_paymantable_id);
// If resource could not be found or does not exist, then inform it via logs
if (! $resource) {
Log::channel('halkbank_payment_check_error')
->error('Related resource not found', [
'orderId' => $request->orderId,
'onlinePaymentHistory_id' => $paymentHistory->id,
'related_resource' => [
'type' => $paymentHistory->online_paymantable_type,
'id' => $paymentHistory->online_paymantable_id,
],
]);
}
$resource->load('branch');
$response = Http::asForm()->post('https://mpi.gov.tm/payment/rest/getOrderStatus.do', [
'language' => 'ru',
'orderId' => $request->orderId,
'userName' => $resource->branch->billing_sber_username,
'password' => $resource->branch->billing_sber_password,
]);
$payment_status = $response['ErrorCode'] == '0';
if ($payment_status) {
$resource->update([
'paid' => true,
]);
$paymentHistory->update([
'paymentStatus' => OnlinePaymentRepo::PAID,
]);
} else {
$paymentHistory->update([
'paymentStatus' => OnlinePaymentRepo::FAILED,
]);
}
return view(OnlinePaymentRepo::statusView(), [
'success' => $payment_status,
'title' => $payment_status ? __('Payment is successful') : __('Payment has failed'),
'pnr' => $paymentHistory->orderNumber,
'branch_name' => $resource->branch->name,
'price_amount' => $paymentHistory->amount,
'return_url' => $resource->panelUrl('index'),
]);
return view(OnlinePaymentRepo::statusView(), $data);
}
}

View File

@@ -6,6 +6,7 @@ use App\Models\Branch\Branch;
use App\Repos\Order\Loan\LoanOrderRepo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
@@ -186,4 +187,31 @@ class SberPaymentOrder extends Model implements HasMedia
static::creating(LoanOrderRepo::creating());
}
/**
* Price for order
*/
public function priceAmount(): float
{
return 250;
}
/**
* Panel url
*/
public function panelUrl(string $type = 'index'): string
{
return match ($type) {
'index' => sprintf('%s/resources/nova-sber-payment-orders', config('nova.path')),
default => config('nova.path'),
};
}
/**
* Payment itmes
*/
public function paymentItems(): HasMany
{
return $this->hasMany(SberPaymentOrderItem::class, 'sber_payment_order_id');
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Modules\SberPaymentOrder\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
/**
* @property int $id
* @property int $sber_payment_order_id
* @property int $online_payment_history_id
* @property ?string $payer_name
* @property ?string $payer_card
* @property ?string $payment_order_number
* @property string $tmt_payment_amount
* @property string $usd_payment_amount
* @property bool $paid
* @property \Illuminate\Support\Carbon $created_at
* @property \Illuminate\Support\Carbon $updated_at
*/
class SberPaymentOrderItem extends Model implements HasMedia
{
use InteractsWithMedia;
/**
* Table
*
* @var string
*/
protected $table = 'sber_payment_orders';
/**
* Guarded attributes
*/
protected $guarded = [];
/**
* Parent order
*/
public function parent(): BelongsTo
{
return $this->belongsTo(SberPaymentOrder::class, 'sber_payment_order_id');
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Modules\SberPaymentOrder\Nova\Resources\Item;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
trait NovaSberPaymentOrderItemAuth
{
/** View button */
public function authorizedToView(Request $request)
{
return false;
}
/** Create button */
public static function authorizedToCreate(Request $request)
{
return false;
}
/** Create */
public static function authorizeToCreate(Request $request)
{
throw_unless(auth()->user()->isMe(), AuthorizationException::class);
}
/** Edit button */
public function authorizedToUpdate(Request $request): bool
{
$user = auth()->user();
if ($user->isMe()) {
return true;
}
return false;
}
/** Update */
public function authorizeToUpdate(Request $request): void
{
$user = auth()->user();
if ($user->isMe()) {
return;
}
throw new AuthorizationException;
}
/** Delete button */
public function authorizedToDelete(Request $request)
{
$user = auth()->user();
if ($user->isMe()) {
return true;
}
return false;
}
/** Force delete */
public function authorizedToForceDelete(Request $request)
{
return auth()->user()->isMe() ? true : false;
}
}

View File

@@ -6,6 +6,7 @@ use App\Models\Branch\Branch;
use App\Modules\SberPaymentOrder\Nova\Resources\Concerns\NovaSberPaymentOrderAuth;
use App\Modules\SberPaymentOrder\Nova\Resources\Concerns\SberPaymentOrderFieldsForDetail;
use App\Modules\SberPaymentOrder\Nova\Resources\Concerns\SberPaymentOrderFieldsForIndex;
use App\Modules\VisaMasterPaymentOrder\Nova\Resources\NovaSberPaymentOrderItem;
use App\Nova\Actions\MakeSberPaymentAction;
use App\Nova\Resource;
use App\Repos\Order\Card\CardOrderRepo;
@@ -18,6 +19,7 @@ use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Laravel\Nova\Fields\Badge;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\Hidden;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Select;
@@ -317,6 +319,8 @@ class NovaSberPaymentOrder extends Resource
Files::make('Ugradyjy we kabul ediji (talyp) 2015-nji ýyldan soňra Türkmenistanyň raýatynyň pasportyny ikinji gezek alandan soňra birinji gezek alan pasportynyň seriýasy baradaky maglumaty bilmeýän ,bolsa onda polisiýanyň degişli edaralaryndan birinji alan pasportynyň seriýasy baradaky güwänamasy', 'sender_passport_local_old_replacement'),
]),
HasMany::make(__('Payment items'), 'paymentItems', NovaSberPaymentOrderItem::class),
];
}

View File

@@ -0,0 +1,171 @@
<?php
namespace App\Modules\VisaMasterPaymentOrder\Nova\Resources;
use App\Models\Branch\Branch;
use App\Models\Payment\OnlinePaymentHistory;
use App\Modules\SberPaymentOrder\Nova\Resources\Item\NovaSberPaymentOrderItemAuth;
use App\Nova\Actions\CheckOnlinePayment;
use App\Nova\Resource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Actions\ActionResponse;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
/**
* @template TModel of \App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem
*/
class NovaSberPaymentOrderItem extends Resource
{
use NovaSberPaymentOrderItemAuth;
/**
* The model the resource corresponds to.
*
* @var class-string<\App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem>
*/
public static $model = \App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* @var array<int, string>
*/
public static $search = [
'id',
];
/**
* The relationships that should be eager loaded on index queries.
*
* @var array
*/
// public static $with = ['branch'];
/**
* Indicates whether the resource should automatically poll for new resources.
*
* @var bool
*/
public static $polling = true;
/**
* The interval at which Nova should poll for new resources.
*
* @var int
*/
public static $pollingInterval = 30;
/**
* Indicates whether to show the polling toggle button inside Nova.
*
* @var bool
*/
public static $showPollingToggle = true;
/**
* Get the displayable label of the resource.
*/
public static function label(): string
{
return __('Payments');
}
/**
* Get the displayable singular label of the resource.
*/
public static function singularLabel(): string
{
return __('Payment');
}
/**
* Get the fields displayed by the resource.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return array<int, \Laravel\Nova\Fields\FieldElement|\Laravel\Nova\Panel>
*/
public function fields(NovaRequest $request): array
{
return [
ID::make(),
Text::make('Amaly geçiren raýatyň F.A.A.', 'payer_name'),
Text::make('Amaly geçiren raýatyň kart belgisi (mask)', 'payer_card'),
Text::make('Töleg ýyly', fn ($model) => $model->created_at->format('Y')),
Text::make('Töleg aýy', fn ($model) => $model->created_at->translatedFormat('F')),
Text::make('Amalyň geçirilen wagty', fn ($model) => $model->created_at->format('H:i, d.m.Y')),
Text::make('Amalyň möçberi', fn ($model) => $model->usd_payment_amount.' USD'),
Text::make('Amalyň manat möçberi', fn ($model) => $model->tmt_payment_amount.' TMT'),
Text::make('Amalyň referensi', fn ($model) => $model->payment_order_number),
Boolean::make(__('Paid'), 'paid'),
];
}
public function actions(NovaRequest $request): array
{
return [
Action::using('HALKBANK töleg barla', function (ActionFields $fields, Collection $models) {
/** @var \App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem $item */
$item = $models->first();
$onlinePaymentResource = OnlinePaymentHistory::find($item->online_payment_history_id);
if (! $onlinePaymentResource) {
return ActionResponse::danger('Online payment resource tapylmady');
}
$relatedResource = (new $onlinePaymentResource->online_paymantable_type)
->find(id: $onlinePaymentResource->online_paymantable_id);
if (! $relatedResource) {
return ActionResponse::danger('Bu resource tapylmady');
}
$username = $relatedResource->branch->billing_sber_username;
$password = $relatedResource->branch->billing_sber_password;
if ($username == '') {
return Action::modal('modal-response', [
'title' => 'HALKBANK API',
'body' => 'Ulanyjy ady bilen açar sözi gabat gelmedi',
]);
}
$response = Http::asForm()->post('https://mpi.gov.tm/payment/rest/getOrderStatus.do', [
'language' => 'ru',
'orderId' => $onlinePaymentResource->orderId,
'userName' => $username,
'password' => $password,
]);
return Action::modal('modal-response', [
'title' => 'HALKBANK API',
'html' => CheckOnlinePayment::resultHTML($response),
]);
})->icon('server')
->sole()
->withoutConfirmation(),
];
}
}

View File

@@ -5,7 +5,7 @@ namespace App\Nova\Actions;
use App\Models\CurrencyRate;
use App\Models\Payment\OnlinePaymentHistory;
use App\Modules\SberPaymentOrder\Models\SberPaymentOrder;
use App\Nova\Actions\Sber\SberActionFields;
use App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem;
use App\Repos\Payment\OnlinePaymentRepo;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
@@ -15,7 +15,9 @@ use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Laravel\Nova\Actions\Action;
use Laravel\Nova\Actions\ActionResponse;
use Laravel\Nova\Fields\ActionFields;
use Laravel\Nova\Fields\Heading;
use Laravel\Nova\Fields\Hidden;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;
@@ -26,19 +28,46 @@ class MakeSberPaymentAction extends Action
/**
* Perform the action on the given models.
*/
public function handle(SberActionFields $fields, Collection $models): mixed
public function handle(ActionFields $fields, Collection $models): mixed
{
$usd_to_tmt = CurrencyRate::where('currency_from', 'USD')->where('currency_to', 'TMT')->first('value');
$payment_amount = floatval($fields->payment_amount);
if (! $usd_to_tmt || ! $payment_amount) {
if (! $usd_to_tmt || ! property_exists($fields, 'payment_amount') || ! property_exists($fields, 'usd_payment')) {
return ActionResponse::danger('Walýuta hasaby girizilmedik, operator bilen habarlaşmagyňyzy haýyş edýärin.');
}
$today = today();
$resource = $models->first();
$payment_amount = floatval($fields->payment_amount);
$hasBeenPaid = false;
$resource->paymentItems->each(function ($item) use (&$hasBeenPaid, $today) {
if ($item->paid) {
if ($today->format('m Y') == $item->created_at->format('m Y')) {
$hasBeenPaid = true;
}
}
});
if ($hasBeenPaid) {
return Action::modal('modal-response', [
'title' => 'Bul aý töleg edildi!',
'body' => 'Bul aý töleg edildi.',
]);
}
if (! $this->canAcceptPayment($today)) {
return Action::modal('modal-response', [
'title' => 'Bu gun aýyn sonky guni!',
'body' => 'Ayyn sonky guni toleg alynmayar.',
]);
}
if (! $resource->branch || ! $resource->branch->billing_sber_username) {
return ActionResponse::danger('Şahamça sber tölegi kabul edip bilmeýär.');
return Action::modal('modal-response', [
'title' => 'Billing maglumatlary şahamçada ýok!',
'body' => 'Şahamça visa/master tölegi kabul edip bilmeýär.',
]);
}
$tvebTaxTMT = floatval($usd_to_tmt->value) * 18;
@@ -47,9 +76,16 @@ class MakeSberPaymentAction extends Action
$payment = $this->order($resource, $total_amount);
return $payment['status'] === 'success'
? ActionResponse::openInNewTab($payment['url'])
: ActionResponse::danger('Töleg ýerinde näsazlyk!');
if ($payment['status'] !== 'success') {
return Action::modal('modal-response', [
'title' => 'Töleg ýerinde näsazlyk!',
'body' => 'Halkbank apida mesele bar.',
]);
}
$this->createPaymentRecord($payment, $resource, $total_amount, $fields->usd_payment);
return ActionResponse::openInNewTab($payment['url']);
}
/**
@@ -102,6 +138,17 @@ class MakeSberPaymentAction extends Action
}
}),
Hidden::make('usd_payment')
->dependsOn('payment_amount', function ($field, $request, $formData) use ($usd_to_rub, $rub_to_tmt) {
if (property_exists($formData, 'payment_amount')) {
$usdValue = number_format($formData->payment_amount / ($usd_to_rub * $rub_to_tmt), 2, '.', '');
$field->setValue($usdValue);
} else {
$field->setValue('');
}
}),
Text::make(__('Jemi (TMT)'), 'total_amount')
->fullWidth()
->readonly()
@@ -149,10 +196,13 @@ class MakeSberPaymentAction extends Action
return [
'status' => 'failed',
'url' => '',
'order_id' => '',
'order_number' => '',
'online_payment_history_id' => '',
];
}
OnlinePaymentHistory::create([
$onlinePaymentHistory = OnlinePaymentHistory::create([
'online_paymantable_id' => $resource->id,
'online_paymantable_type' => SberPaymentOrder::class,
'amount' => number_format($amount, 2, '', ''),
@@ -170,6 +220,63 @@ class MakeSberPaymentAction extends Action
return [
'status' => 'success',
'url' => $paymentResponse['formUrl'],
'order_id' => $paymentResponse['orderId'],
'order_number' => $orderNumber,
'online_payment_history_id' => $onlinePaymentHistory->id,
];
}
/**
* Create payment record
*
* @param $payment
* @param $resource
*/
public function createPaymentRecord($payment, $resource, $total_amount, $usd_payment)
{
SberPaymentOrderItem::create([
'visa_master_payment_order_id' => $resource->id,
'online_payment_history_id' => $payment['online_payment_history_id'],
'payment_order_number' => $payment['order_number'],
'tmt_payment_amount' => $total_amount,
'usd_payment_amount' => $usd_payment,
]);
}
public function canAcceptPayment($today)
{
$year = $today->format('Y');
$month = $today->format('m');
$lastDay = lastDayOfMonth(year: $year, month: $month);
// Condition 1: Check if today is the last day of the month
if ($today->format('Y-m-d') === $lastDay->format('Y-m-d')) {
info('check 1');
return false;
}
// Determine the day of the week for the last day of the month
$lastDayOfWeek = $lastDay->format('l'); // e.g., 'Sunday', 'Saturday'
// Condition 2: If the last day is Sunday, disallow Friday, Saturday, Sunday
if ($lastDayOfWeek === 'Sunday') {
$forbiddenDays = ['Friday', 'Saturday', 'Sunday'];
if (in_array($today->format('l'), $forbiddenDays)) {
info('check 2');
return false;
}
}
// Condition 3: If the last day is Saturday, disallow Friday
if ($lastDayOfWeek === 'Saturday' && $today->format('l') === 'Friday') {
info('check 3');
return false;
}
// If none of the conditions match, allow payment
return true;
}
}

View File

@@ -4,6 +4,7 @@ namespace App\Repos\Payment;
use App\Models\Branch\Branch;
use App\Models\Payment\OnlinePaymentHistory;
use App\Repos\Payment\Sber\HandlesSberPeyments;
use App\Repos\Payment\VisaMaster\HandlesVisaMasterPayments;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
@@ -13,6 +14,7 @@ use Laravel\Nova\Makeable;
class OnlinePaymentRepo
{
use HandlesVisaMasterPayments;
use HandlesSberPeyments;
use Makeable;
/**
@@ -182,7 +184,7 @@ class OnlinePaymentRepo
*
* @return array<string, bool|string>
*/
public static function successfulPaymentResponse($paymentHistory, $bank_branch, $resource): array
public static function successfulPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL): array
{
return [
'success' => true,
@@ -190,7 +192,7 @@ class OnlinePaymentRepo
'pnr' => $paymentHistory->orderNumber,
'branch_name' => $bank_branch->name,
'price_amount' => convertToOriginalFormat($paymentHistory->amount).' TMT',
'return_url' => url('/work-place/resources/nova-visa-master-payment-orders/'.$resource->visa_master_payment_order_id),
'return_url' => $returnURL,
];
}
@@ -201,7 +203,7 @@ class OnlinePaymentRepo
* @param $bank_branch
* @param $resource
*/
public static function failedPaymentResponse($paymentHistory, $bank_branch, $resource)
public static function failedPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL)
{
return [
'success' => false,
@@ -209,7 +211,7 @@ class OnlinePaymentRepo
'pnr' => $paymentHistory->orderNumber,
'branch_name' => $bank_branch->name,
'price_amount' => convertToOriginalFormat($paymentHistory->amount).' TMT',
'return_url' => url('/work-place/resources/nova-visa-master-payment-orders/'.$resource->visa_master_payment_order_id),
'return_url' => $returnURL,
];
}

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Repos\Payment\Sber;
use App\Models\Payment\OnlinePaymentHistory;
use App\Modules\SberPaymentOrder\Models\SberPaymentOrderItem;
use App\Repos\Payment\OnlinePaymentRepo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
trait HandlesSberPeyments
{
/**
* Check payment payment visa master
*
* @param Request $request
*
* @return array<string, bool|string>
*/
public static function checkPaymentSber(Request $request): array
{
// Find order from history
$paymentHistory = OnlinePaymentHistory::where('orderId', $request->orderId)->first();
// Find related resource
$resource = SberPaymentOrderItem::where('online_payment_history_id', $paymentHistory->id)->first();
// If resource could not be found or does not exist, then inform it via logs
if (! $resource) {
static::logResourceNotFound($request, $paymentHistory);
return static::resourceNotFound();
}
$bank_branch = $resource->parent->branch;
$response = Http::asForm()->post('https://mpi.gov.tm/payment/rest/getOrderStatus.do', [
'language' => 'ru',
'orderId' => $request->orderId,
'userName' => $bank_branch->billing_sber_username,
'password' => $bank_branch->billing_sber_password,
]);
$payment_status = $response['ErrorCode'] == '0';
$returnURL = url('/work-place/resources/nova-sber-payment-orders/'.$resource->sber_payment_order_id);
if ($payment_status) {
$resource->update([
'payer_name' => $response['cardholderName'],
'payer_card' => $response['Pan'],
'paid' => true,
]);
$paymentHistory->update([
'paymentStatus' => OnlinePaymentRepo::PAID,
]);
return static::successfulPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL);
}
$resource->update([
'payer_name' => $response['cardholderName'] ?? '-',
'payer_card' => $response['Pan'] ?? '-',
]);
$paymentHistory->update([
'paymentStatus' => OnlinePaymentRepo::FAILED,
]);
return static::failedPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL);
}
}

View File

@@ -42,6 +42,7 @@ trait HandlesVisaMasterPayments
]);
$payment_status = $response['ErrorCode'] == '0';
$returnURL = url('/work-place/resources/nova-visa-master-payment-orders/'.$resource->visa_master_payment_order_id);
if ($payment_status) {
$resource->update([
@@ -54,7 +55,7 @@ trait HandlesVisaMasterPayments
'paymentStatus' => OnlinePaymentRepo::PAID,
]);
return static::successfulPaymentResponse($paymentHistory, $bank_branch, $resource);
return static::successfulPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL);
}
$resource->update([
@@ -66,6 +67,6 @@ trait HandlesVisaMasterPayments
'paymentStatus' => OnlinePaymentRepo::FAILED,
]);
return static::failedPaymentResponse($paymentHistory, $bank_branch, $resource);
return static::failedPaymentResponse($paymentHistory, $bank_branch, $resource, $returnURL);
}
}

View File

@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('sber_payment_order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('sber_payment_order_id')->constrained('visa_master_payment_orders')->nullOnDelete();
$table->foreignId('online_payment_history_id')->nullable()->constrained('online_payment_histories')->nullOnDelete();
$table->string('payer_name')->nullable();
$table->string('payer_card')->nullable();
$table->string('payment_order_number')->nullable();
$table->string('tmt_payment_amount');
$table->string('usd_payment_amount');
$table->boolean('paid')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('sber_payment_order_items');
}
};