Compare commits

..

2 Commits

105 changed files with 15119 additions and 0 deletions

18
.editorconfig Normal file
View File

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

65
.env.example Normal file
View File

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

11
.gitattributes vendored Normal file
View File

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

10
.gitignore vendored
View File

@ -23,3 +23,13 @@ Homestead.json
/.vagrant
.phpunit.result.cache
# Zalo User-bot temporary files & folders
/zalo-userbot/bot.log
/zalo-userbot/bot_err.log
/zalo-userbot/bot.pid
/zalo-userbot/qr.png
/zalo-userbot/node_modules/
# Debug assets
/*.png

View File

@ -0,0 +1,45 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\ConversionHistory;
use App\Services\SettingService;
class CleanupExpiredLinks extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:cleanup-expired-links';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Dọn dẹp các link rút gọn đã hết hạn dựa trên số click (30 ngày gốc + 3 ngày/click)';
/**
* Execute the console command.
*/
public function handle(SettingService $settingService)
{
$enableCleanup = $settingService->get('enable_auto_cleanup', '1');
if ($enableCleanup !== '1') {
$this->info('Tính năng tự động dọn dẹp link đang bị tắt trong Settings.');
return;
}
$this->info('Đang kiểm tra và dọn dẹp các link đã hết hạn...');
// Delete records where (created_at + 30 days + clicks * 3 days) < now
$deletedCount = ConversionHistory::whereRaw('DATE_ADD(created_at, INTERVAL (30 + clicks * 3) DAY) < NOW()')
->delete();
$this->info("Đã xóa thành công {$deletedCount} link hết hạn khỏi hệ thống.");
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\DTOs;
class AffiliateResult
{
public function __construct(
public bool $isSuccess,
public string $originalUrl,
public ?string $affiliateUrl = null,
public ?string $errorMessage = null,
public float $executionTime = 0.0,
public ?string $sessionUsed = null,
public string $converterType = 'unknown'
) {}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\LinkConverterService;
use App\Services\HistoryService;
use Illuminate\Http\Request;
class ConvertApiController extends Controller
{
protected LinkConverterService $linkConverterService;
protected HistoryService $historyService;
public function __construct(LinkConverterService $linkConverterService, HistoryService $historyService)
{
$this->linkConverterService = $linkConverterService;
$this->historyService = $historyService;
}
public function convert(Request $request)
{
$request->validate([
'url' => 'required|url',
]);
$result = $this->linkConverterService->process($request->input('url'));
if ($result->isSuccess) {
return response()->json([
'success' => true,
'data' => $result,
]);
}
return response()->json([
'success' => false,
'message' => $result->errorMessage,
'data' => $result,
], 400);
}
public function history()
{
return response()->json([
'success' => true,
'data' => $this->historyService->getPaginated(20),
]);
}
}

View File

@ -0,0 +1,194 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\ZaloBotService;
use App\Services\SettingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ZaloWebhookController extends Controller
{
protected ZaloBotService $zaloBotService;
protected SettingService $settingService;
public function __construct(
ZaloBotService $zaloBotService,
SettingService $settingService
) {
$this->zaloBotService = $zaloBotService;
$this->settingService = $settingService;
}
/**
* Handle webhook request from Zalo Bot Platform.
*/
public function handle(Request $request): JsonResponse
{
$configuredSecret = $this->settingService->get('zalo_webhook_secret');
if (!empty($configuredSecret)) {
$incomingSecret = $request->header('X-Bot-Api-Secret-Token')
?? $request->header('x-bot-api-secret-token');
if ($incomingSecret !== $configuredSecret) {
return response()->json([
'ok' => false,
'error' => 'Unauthorized. Secret token mismatch.'
], 401);
}
}
$payload = $request->all();
// Pass payload to ZaloBotService
$this->zaloBotService->handleWebhook($payload);
return response()->json([
'ok' => true,
]);
}
/**
* Process a Shopee link for the Zalo user-bot (self-bot) and return the formatted reply.
*/
public function processLink(Request $request): JsonResponse
{
$request->validate([
'url' => 'required|string',
'sender_name' => 'nullable|string',
'thread_id' => 'nullable|string',
'chat_name' => 'nullable|string'
]);
$url = $request->input('url');
$fromName = $request->input('sender_name') ?? 'Bạn';
$threadId = $request->input('thread_id');
$chatName = $request->input('chat_name');
// 1. Add/Update this thread into discovered groups pool so Admin can whitelist it
if ($threadId) {
\App\Models\ZaloDiscoveredGroup::updateOrCreate(
['group_id' => $threadId],
['name' => $chatName ?: ($fromName ? "Chat với {$fromName}" : "Trò chuyện cá nhân")]
);
}
// 2. Whitelist Filtering: Bot is ONLY allowed to respond to whitelisted threads (Default Deny)
$isAllowed = \App\Models\ZaloChannel::where('thread_id', $threadId)
->where('is_allowed', true)
->exists();
$productTitle = $request->input('product_title');
$productImage = $request->input('product_image');
if (!$isAllowed) {
return response()->json([
'success' => false,
'error' => 'Thread is not whitelisted. Bot response restricted.'
], 403);
}
try {
// 1. Resolve redirect if short link
$resolvedUrl = $this->zaloBotService->resolveShortUrl($url);
// 2. Convert link to short redirect affiliate link and log details
$convertResult = app(\App\Services\LinkConverterService::class)->process(
$resolvedUrl,
$threadId,
$chatName,
'zalo_bot',
null,
null,
$productTitle,
$productImage
);
if ($convertResult && $convertResult->isSuccess) {
$shortLink = $convertResult->affiliateUrl;
// Fetch the logged history to extract cào details
$history = \App\Models\ConversionHistory::where('original_url', $resolvedUrl)
->where('zalo_thread_id', $threadId)
->latest()
->first();
$productName = $history && $history->product_title ? $history->product_title : ($productTitle ?: ($this->zaloBotService->extractProductName($resolvedUrl) ?? 'Sản phẩm Shopee'));
// 3. Construct the message template
$replyText = "Hi @{$fromName}, Link của bạn đây ạ:\n\n" .
"📦 Tên sản phẩm Shopee:\n{$productName}\n\n" .
"🔗 Link: {$shortLink}\n\n" .
"⚠️ Lưu ý: Để đơn hàng được ghi nhận, KHÔNG mua qua Livestream, KHÔNG xem video/live bất kỳ sau khi click & XÓA sản phẩm ra khỏi giỏ hàng TRƯỚC KHI bấm link!";
return response()->json([
'success' => true,
'reply_text' => $replyText,
'short_link' => $shortLink
]);
}
return response()->json([
'success' => false,
'error' => $convertResult->errorMessage ?? 'Conversion failed'
], 400);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'error' => $e->getMessage()
], 500);
}
}
/**
* Update Zalo user-bot (self-bot) status in settings table.
*/
public function updateStatus(Request $request): JsonResponse
{
$request->validate([
'status' => 'required|string',
'user_name' => 'nullable|string'
]);
$this->settingService->set('zalo_bot_status', $request->input('status'));
if ($request->has('user_name')) {
$this->settingService->set('zalo_bot_user', $request->input('user_name') ?? '');
} else if ($request->input('status') === 'disconnected') {
$this->settingService->set('zalo_bot_user', '');
}
return response()->json(['ok' => true]);
}
/**
* Sync Zalo groups from userbot into discovered pool.
*/
public function syncGroups(Request $request): JsonResponse
{
$request->validate([
'groups' => 'required|array',
'groups.*.id' => 'required|string',
'groups.*.name' => 'nullable|string'
]);
$groups = $request->input('groups');
$fetchedIds = array_column($groups, 'id');
// Delete groups no longer joined
\App\Models\ZaloDiscoveredGroup::whereNotIn('group_id', $fetchedIds)->delete();
// Update or insert current groups
foreach ($groups as $group) {
\App\Models\ZaloDiscoveredGroup::updateOrCreate(
['group_id' => $group['id']],
['name' => $group['name'] ?? 'Nhóm Zalo']
);
}
return response()->json(['ok' => true]);
}
}

View File

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

View File

@ -0,0 +1,84 @@
<?php
namespace App\Http\Controllers\Web\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller
{
/**
* Show the login form, or registration form if no users exist.
*/
public function showLoginForm()
{
if (Auth::check()) {
return redirect()->route('dashboard');
}
// If database is empty, allow creating the first admin
$hasUsers = User::exists();
return view('auth.login', compact('hasUsers'));
}
/**
* Handle authentication attempt.
*/
public function login(Request $request)
{
$request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
if (Auth::attempt($request->only('email', 'password'), $request->filled('remember'))) {
$request->session()->regenerate();
return redirect()->intended(route('dashboard'));
}
return back()->withErrors([
'email' => 'Thông tin đăng nhập không chính xác.',
])->onlyInput('email');
}
/**
* Handle first-time registration of the administrator.
*/
public function registerAdmin(Request $request)
{
if (User::exists()) {
return redirect()->route('login')->withErrors(['register' => 'Tài khoản quản trị đã tồn tại.']);
}
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|max:255|unique:users,email',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('dashboard')->with('success', 'Đăng ký tài khoản quản trị thành công!');
}
/**
* Log the user out.
*/
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('login');
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Services\LinkConverterService;
use Illuminate\Http\Request;
class ConvertController extends Controller
{
protected LinkConverterService $linkConverterService;
public function __construct(LinkConverterService $linkConverterService)
{
$this->linkConverterService = $linkConverterService;
}
public function index()
{
return view('convert.index');
}
public function process(Request $request)
{
$request->validate([
'url' => 'required|url',
]);
$result = $this->linkConverterService->process($request->input('url'));
if ($result->isSuccess) {
return back()->with('success_result', $result);
}
return back()->with('error_result', $result);
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\ConversionHistory;
use Illuminate\Http\Request;
class CustomerLookupController extends Controller
{
/**
* Display the lookup form.
*/
public function index()
{
return view('customer_lookup');
}
/**
* Search click logs by customer phone number.
*/
public function search(Request $request)
{
$request->validate([
'phone' => 'required|string|max:20',
]);
$phone = trim($request->input('phone'));
$histories = ConversionHistory::where('customer_phone', $phone)
->where('status', 'success')
->latest()
->get();
return view('customer_lookup', [
'phone' => $phone,
'histories' => $histories,
'searched' => true
]);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\ConversionHistory;
class DashboardController extends Controller
{
public function index()
{
$totalConversions = ConversionHistory::count();
$recentConversions = ConversionHistory::orderByDesc('created_at')->limit(20)->get();
return view('dashboard.index', compact(
'totalConversions',
'recentConversions'
));
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Services\HistoryService;
class HistoryController extends Controller
{
protected HistoryService $historyService;
public function __construct(HistoryService $historyService)
{
$this->historyService = $historyService;
}
public function index()
{
$histories = $this->historyService->getPaginated(20);
$allowedThreadIds = \App\Models\ZaloChannel::pluck('thread_id')->toArray();
return view('history.index', compact('histories', 'allowedThreadIds'));
}
public function destroy($id)
{
$history = \App\Models\ConversionHistory::findOrFail($id);
$history->delete();
return back()->with('success', 'Đã xoá lịch sử chuyển đổi thành công.');
}
public function bulkDestroy(\Illuminate\Http\Request $request)
{
$ids = $request->input('ids', []);
if (!empty($ids)) {
\App\Models\ConversionHistory::whereIn('id', $ids)->delete();
return back()->with('success', 'Đã xoá thành công ' . count($ids) . ' lịch sử chuyển đổi.');
}
return back()->with('error', 'Vui lòng chọn ít nhất một bản ghi để xoá.');
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Services\LinkConverterService;
use Illuminate\Http\Request;
class PublicConvertController extends Controller
{
protected LinkConverterService $linkConverterService;
public function __construct(LinkConverterService $linkConverterService)
{
$this->linkConverterService = $linkConverterService;
}
public function index()
{
return view('public_convert');
}
public function process(Request $request)
{
$request->validate([
'url' => 'required|url',
'customer_name' => 'nullable|string|max:100',
'customer_phone' => 'nullable|string|max:20',
]);
$url = $request->input('url');
$customerName = $request->input('customer_name');
$customerPhone = $request->input('customer_phone');
try {
// Process link conversion with source type 'public_web' and customer details
$result = $this->linkConverterService->process(
$url,
null,
null,
'public_web',
$customerName,
$customerPhone
);
if ($result->isSuccess) {
// Find the logged history to get cào details (title, price, estimated_commission)
$history = \App\Models\ConversionHistory::where('original_url', $url)
->where('converter_type', 'public_web')
->latest()
->first();
return back()->with([
'success' => 'Chuyển đổi link Shopee Affiliate thành công!',
'original_url' => $url,
'short_url' => $result->affiliateUrl,
'product_title' => $history ? $history->product_title : null,
'product_price' => $history ? $history->product_price : 0.00,
'estimated_commission' => $history ? $history->estimated_commission : 0.00
]);
}
return back()->withInput()->with('error', $result->errorMessage ?: 'Không thể chuyển đổi link này. Vui lòng kiểm tra lại link Shopee.');
} catch (\Exception $e) {
return back()->withInput()->with('error', 'Đã xảy ra lỗi hệ thống: ' . $e->getMessage());
}
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Services\SettingService;
use Illuminate\Http\Request;
class SettingController extends Controller
{
protected SettingService $settingService;
public function __construct(SettingService $settingService)
{
$this->settingService = $settingService;
}
public function index()
{
$settings = $this->settingService->getAll();
return view('settings.index', compact('settings'));
}
public function update(Request $request)
{
$data = $request->except('_token');
// Handle auto cleanup checkbox explicitly since unchecked boxes are missing from request payload
$data['enable_auto_cleanup'] = $request->has('enable_auto_cleanup') ? '1' : '0';
foreach ($data as $key => $value) {
$type = is_numeric($value) ? 'integer' : 'string';
$this->settingService->set($key, $value, $type);
}
return back()->with('success', 'Settings updated successfully.');
}
/**
/**
* Start the Zalo user-bot process in the background.
*/
public function startBot()
{
$cwd = base_path('zalo-userbot');
$pidFile = $cwd . '/bot.pid';
// 1. Force kill any existing zombie userbot processes first to prevent session locks
$this->killAllUserbotProcesses();
// 2. Clean old files
@unlink($pidFile);
@unlink(public_path('zalo/qr.png'));
$appUrl = url('/');
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
$cmd = "set APP_URL=" . escapeshellarg($appUrl) . " && cd /d " . escapeshellarg($cwd) . " && start /B node userbot.js > bot.log 2>&1";
pclose(popen($cmd, "r"));
} else {
$cmd = "export APP_URL=" . escapeshellarg($appUrl) . " && cd " . escapeshellarg($cwd) . " && node userbot.js > bot.log 2>&1 &";
exec($cmd);
}
// Wait a brief moment to let it start and write pid
usleep(500000);
return back()->with('success', 'Đã gửi lệnh khởi động Bot Zalo. Vui lòng tải lại trang sau vài giây.');
}
/**
* Check current Bot status via AJAX polling.
*/
public function checkBotStatus()
{
return response()->json([
'status' => $this->settingService->get('zalo_bot_status') ?? 'disconnected',
'user' => $this->settingService->get('zalo_bot_user') ?? '',
]);
}
/**
* Stop the Zalo user-bot process.
*/
public function stopBot()
{
$pidFile = base_path('zalo-userbot/bot.pid');
// Force kill all active/zombie userbot processes
$this->killAllUserbotProcesses();
@unlink($pidFile);
@unlink(public_path('zalo/qr.png'));
$this->settingService->set('zalo_bot_status', 'disconnected');
$this->settingService->set('zalo_bot_user', '');
return back()->with('success', 'Đã tắt Bot Zalo thành công.');
}
/**
* Kill all running userbot instances globally on the system (Windows/Linux compatible).
*/
private function killAllUserbotProcesses(): void
{
if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
// Terminate any node.exe process running userbot.js using wmic on Windows
exec('wmic process where "name=\'node.exe\' and CommandLine like \'%userbot.js%\'" call terminate >nul 2>&1');
} else {
// Terminate on Linux/Unix using pkill -f
exec('pkill -9 -f "node userbot.js" >/dev/null 2>&1');
}
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\ConversionHistory;
use Illuminate\Http\RedirectResponse;
class ShortLinkController extends Controller
{
/**
* Redirect short URL to the actual Shopee affiliate redirect URL.
*/
public function redirect(string $code)
{
$history = ConversionHistory::whereRaw('BINARY code = ?', [$code])
->where('status', 'success')
->first();
if (!$history || !$history->affiliate_url) {
abort(404, 'Short link not found or invalid.');
}
// Detect if request is from a crawler bot (Zalo, Facebook, etc.)
$userAgent = strtolower(request()->header('User-Agent', ''));
$bots = ['zalo', 'facebookexternalhit', 'telegrambot', 'twitterbot', 'slackbot', 'googlebot', 'crawler'];
$isBot = false;
foreach ($bots as $bot) {
if (str_contains($userAgent, $bot)) {
$isBot = true;
break;
}
}
if ($isBot) {
return view('short_link_preview', compact('history'));
}
// Increment click count for real users
$history->increment('clicks');
return redirect()->away($history->affiliate_url);
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\ZaloChannel;
use Illuminate\Http\Request;
class ZaloChannelController extends Controller
{
public function index()
{
$channels = ZaloChannel::orderByDesc('is_allowed')->orderBy('name')->paginate(15, ['*'], 'channels_page');
$whitelistedIds = ZaloChannel::pluck('thread_id')->toArray();
$discoveredGroups = \App\Models\ZaloDiscoveredGroup::whereNotIn('group_id', $whitelistedIds)
->orderBy('name')
->paginate(15, ['*'], 'groups_page');
return view('zalo_channels.index', compact('channels', 'discoveredGroups'));
}
public function store(Request $request)
{
$request->validate([
'thread_id' => 'required|string|unique:zalo_channels,thread_id',
'name' => 'nullable|string',
]);
ZaloChannel::create([
'thread_id' => trim($request->input('thread_id')),
'name' => $request->input('name') ?: 'Kênh chưa đặt tên',
'is_allowed' => true,
]);
return back()->with('success', 'Đã thêm kênh Zalo vào danh sách cho phép.');
}
public function toggle($id)
{
$channel = ZaloChannel::findOrFail($id);
$channel->is_allowed = !$channel->is_allowed;
$channel->save();
$statusText = $channel->is_allowed ? 'cho phép' : 'chặn';
return back()->with('success', "Đã thay đổi trạng thái kênh sang {$statusText}.");
}
public function quickToggle(Request $request)
{
$request->validate([
'thread_id' => 'required|string',
'name' => 'nullable|string',
]);
$threadId = $request->input('thread_id');
$name = $request->input('name');
$channel = ZaloChannel::where('thread_id', $threadId)->first();
if ($channel) {
$channel->delete();
return back()->with('success', 'Đã xóa kênh khỏi danh sách cho phép (Bot sẽ KHÔNG phản hồi nhóm này nữa).');
} else {
ZaloChannel::create([
'thread_id' => $threadId,
'name' => $name ?: 'Kênh Zalo',
'is_allowed' => true,
]);
return back()->with('success', 'Đã thêm kênh vào danh sách cho phép (Bot SẼ phản hồi nhóm này).');
}
}
public function destroy($id)
{
$channel = ZaloChannel::findOrFail($id);
$channel->delete();
return back()->with('success', 'Đã xóa kênh Zalo khỏi danh sách.');
}
public function bulkDestroy(Request $request)
{
$request->validate([
'ids' => 'required|array',
'ids.*' => 'exists:zalo_channels,id'
]);
ZaloChannel::whereIn('id', $request->input('ids'))->delete();
return back()->with('success', 'Đã xóa các kênh Zalo được chọn thành công.');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Interfaces;
use App\DTOs\AffiliateResult;
interface AffiliateConverterInterface
{
/**
* Convert an original URL to an affiliate URL.
*
* @param string $url
* @param string|null $code
* @return AffiliateResult
*/
public function convert(string $url, ?string $code = null): AffiliateResult;
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ConversionHistory extends Model
{
use HasFactory;
protected $fillable = [
'code',
'original_url',
'affiliate_url',
'converter_type',
'session_name',
'status',
'clicks',
'error_message',
'execution_time',
'zalo_thread_id',
'zalo_chat_name',
'product_title',
'product_image',
'product_price',
'estimated_commission',
'customer_name',
'customer_phone',
];
}

30
app/Models/Setting.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
protected $fillable = [
'key',
'value',
'type',
];
/**
* Get the strongly typed value based on type.
*/
public function getTypedValue()
{
return match ($this->type) {
'boolean' => filter_var($this->value, FILTER_VALIDATE_BOOLEAN),
'integer' => (int) $this->value,
'json' => json_decode($this->value, true),
default => $this->value,
};
}
}

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

@ -0,0 +1,49 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ZaloChannel extends Model
{
use HasFactory;
protected $fillable = [
'thread_id',
'name',
'is_allowed',
];
protected $casts = [
'is_allowed' => 'boolean',
];
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ZaloDiscoveredGroup extends Model
{
protected $fillable = [
'group_id',
'name',
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Paginator::useBootstrapFive();
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
use App\Interfaces\AffiliateConverterInterface;
use App\Services\Converters\ManualAffiliateConverter;
use Illuminate\Support\ServiceProvider;
class ConverterServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
$this->app->bind(AffiliateConverterInterface::class, ManualAffiliateConverter::class);
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Services\Converters;
use App\DTOs\AffiliateResult;
use App\Interfaces\AffiliateConverterInterface;
use App\Services\SettingService;
class ManualAffiliateConverter implements AffiliateConverterInterface
{
protected SettingService $settingService;
public function __construct(SettingService $settingService)
{
$this->settingService = $settingService;
}
public function convert(string $url, ?string $code = null): AffiliateResult
{
$startTime = microtime(true);
$affiliateId = $this->settingService->get('affiliate_id');
if (!$affiliateId) {
return new AffiliateResult(
isSuccess: false,
originalUrl: $url,
errorMessage: 'Vui lòng thiết lập Affiliate ID trong phần Settings để sử dụng chuyển đổi thủ công.',
executionTime: microtime(true) - $startTime,
converterType: 'manual'
);
}
// URL encode the original URL
$encodedLink = urlencode($url);
// Construct the standard manual Shopee redirect URL
$affiliateUrl = "https://s.shopee.vn/an_redir?origin_link={$encodedLink}&affiliate_id={$affiliateId}";
if ($code) {
$affiliateUrl .= "&sub_id={$code}";
}
return new AffiliateResult(
isSuccess: true,
originalUrl: $url,
affiliateUrl: $affiliateUrl,
executionTime: microtime(true) - $startTime,
sessionUsed: 'manual_id_' . $affiliateId,
converterType: 'manual'
);
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Services;
use App\Models\ConversionHistory;
use App\DTOs\AffiliateResult;
use Illuminate\Pagination\LengthAwarePaginator;
class HistoryService
{
/**
* Log a conversion result to the database.
*/
public function logConversion(
AffiliateResult $result,
?string $code = null,
?string $zaloThreadId = null,
?string $zaloChatName = null,
?string $customerName = null,
?string $customerPhone = null,
?string $productTitle = null,
?string $productImage = null,
float $productPrice = 0.00,
float $estimatedCommission = 0.00
): ConversionHistory {
if ($result->isSuccess && !$code) {
do {
$code = \Illuminate\Support\Str::random(10);
} while (ConversionHistory::whereRaw('BINARY code = ?', [$code])->exists());
}
return ConversionHistory::create([
'code' => $code,
'original_url' => $result->originalUrl,
'affiliate_url' => $result->affiliateUrl,
'converter_type' => $result->converterType,
'session_name' => $result->sessionUsed,
'status' => $result->isSuccess ? 'success' : 'failed',
'error_message' => $result->errorMessage,
'execution_time' => $result->executionTime,
'zalo_thread_id' => $zaloThreadId,
'zalo_chat_name' => $zaloChatName,
'customer_name' => $customerName,
'customer_phone' => $customerPhone,
'product_title' => $productTitle,
'product_image' => $productImage,
'product_price' => $productPrice,
'estimated_commission' => $estimatedCommission,
]);
}
/**
* Get recent conversion history.
*/
public function getRecent(int $limit = 20)
{
return ConversionHistory::orderByDesc('created_at')->limit($limit)->get();
}
/**
* Get paginated history for the UI.
*/
public function getPaginated(int $perPage = 20): LengthAwarePaginator
{
return ConversionHistory::orderByDesc('created_at')->paginate($perPage);
}
}

View File

@ -0,0 +1,197 @@
<?php
namespace App\Services;
use App\DTOs\AffiliateResult;
use App\Interfaces\AffiliateConverterInterface;
class LinkConverterService
{
protected AffiliateConverterInterface $converter;
protected HistoryService $historyService;
protected SettingService $settingService;
public function __construct(
AffiliateConverterInterface $converter,
HistoryService $historyService,
SettingService $settingService
) {
$this->converter = $converter;
$this->historyService = $historyService;
$this->settingService = $settingService;
}
public function process(
string $url,
?string $zaloThreadId = null,
?string $zaloChatName = null,
string $sourceType = 'web',
?string $customerName = null,
?string $customerPhone = null
): AffiliateResult
{
// 1. Generate unique code beforehand for tracking
$code = null;
do {
$code = \Illuminate\Support\Str::random(10);
} while (\App\Models\ConversionHistory::whereRaw('BINARY code = ?', [$code])->exists());
// 2. Fetch real Shopee product information
$productInfo = $this->fetchShopeeProductInfo($url);
$productTitle = $productInfo['name'] ?? null;
$productImage = $productInfo['image'] ?? null;
$productPrice = $productInfo['price'] ?? 0.00;
// Determine estimated commission rate and amount
$commissionData = $this->calculateEstimatedCommission($productTitle, $productPrice, $productInfo['is_mall'] ?? false);
$estimatedCommission = $commissionData['amount'];
$maxRetries = $this->settingService->get('retry_count', 3);
$attempts = 0;
$result = null;
while ($attempts < $maxRetries) {
$attempts++;
// 3. Convert with the pre-generated code for sub_id mapping
$result = $this->converter->convert($url, $code);
if ($result->isSuccess) {
break;
}
}
// Save history regardless of success or failure
if ($result) {
$history = $this->historyService->logConversion(
$result,
$code,
$zaloThreadId,
$zaloChatName,
$customerName,
$customerPhone,
$productTitle,
$productImage,
$productPrice,
$estimatedCommission
);
// Override converter type if triggered from external source (like Zalo)
if ($history && $sourceType !== 'web') {
$history->update([
'converter_type' => $sourceType
]);
}
if ($result->isSuccess && $history->code) {
$domain = $this->settingService->get('short_link_domain');
if ($domain) {
$domain = rtrim($domain, '/');
$result->affiliateUrl = $domain . '/aff/s/' . $history->code;
} else {
$result->affiliateUrl = route('short_link.redirect', ['code' => $history->code]);
}
}
}
return $result;
}
/**
* Fetch product details (title, image, price) from Shopee internal API.
*/
public function fetchShopeeProductInfo(string $url): ?array
{
if (!preg_match('/i\.(\d+)\.(\d+)/', $url, $matches)) {
return null;
}
$shopId = $matches[1];
$itemId = $matches[2];
$apiUrl = "https://shopee.vn/api/v4/item/get?itemid={$itemId}&shopid={$shopId}";
try {
$response = \Illuminate\Support\Facades\Http::timeout(5)
->withHeaders([
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept' => 'application/json',
'Referer' => 'https://shopee.vn/',
])
->get($apiUrl);
if ($response->successful()) {
$data = $response->json();
$item = $data['data'] ?? null;
if ($item) {
$price = isset($item['price']) ? $item['price'] / 100000 : 0;
$image = isset($item['image']) ? "https://down-vn.img.susercontent.com/file/" . $item['image'] : null;
return [
'name' => $item['name'] ?? null,
'price' => $price,
'image' => $image,
'is_mall' => !empty($item['is_official_shop']),
'description' => $item['description'] ?? null
];
}
}
} catch (\Exception $e) {
\Illuminate\Support\Facades\Log::warning("Shopee internal API lookup failed: " . $e->getMessage());
}
return null;
}
/**
* Calculate estimated commission based on category keywords and Mall status.
*/
protected function calculateEstimatedCommission(?string $title, float $price, bool $isMall): array
{
if (!$title || $price <= 0) {
return ['rate' => 0, 'amount' => 0.00];
}
$titleLower = mb_strtolower($title);
// Define category keywords
$fashionKeywords = ['áo', 'quần', 'váy', 'đầm', 'giày', 'túi', 'kính', 'son', 'kem', 'phấn', 'nước hoa', 'tắm', 'gội', 'phụ kiện', 'trang sức', 'skincare', 'scrub'];
$electronicsKeywords = ['điện thoại', 'laptop', 'tivi', 'loa', 'tai nghe', 'máy ảnh', 'sạc', 'cáp', 'chuột', 'bàn phím', 'camera', 'micro', 'usb', 'thẻ nhớ', 'router', 'wifi', 'pin'];
$isFashion = false;
foreach ($fashionKeywords as $keyword) {
if (str_contains($titleLower, $keyword)) {
$isFashion = true;
break;
}
}
$isElectronics = false;
if (!$isFashion) {
foreach ($electronicsKeywords as $keyword) {
if (str_contains($titleLower, $keyword)) {
$isElectronics = true;
break;
}
}
}
// Apply rates
if ($isFashion) {
$rate = $isMall ? 7.4 : 3.5;
} elseif ($isElectronics) {
$rate = $isMall ? 1.5 : 0.8;
} else {
// General categories
$rate = $isMall ? 5.0 : 2.5;
}
// Allow admin settings override if configured
$adminOverrideRate = $this->settingService->get('commission_rate_override');
if ($adminOverrideRate !== null && $adminOverrideRate !== '') {
$rate = (float)$adminOverrideRate;
}
return [
'rate' => $rate,
'amount' => round($price * ($rate / 100), 2)
];
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Services;
use App\Models\CookieSession;
class SessionManagerService
{
/**
* Get the next available active session based on priority and last_used_at.
*/
public function getAvailableSession(): ?CookieSession
{
return CookieSession::active()
->orderByDesc('priority')
->orderBy('last_used_at', 'asc')
->first();
}
/**
* Mark a session as used.
*/
public function markAsUsed(CookieSession $session): void
{
$session->update([
'last_used_at' => now(),
]);
}
/**
* Mark a session as error.
*/
public function markAsError(CookieSession $session): void
{
$session->update([
'status' => 'error',
]);
}
/**
* Disable a session.
*/
public function disableSession(CookieSession $session): void
{
$session->update([
'status' => 'disabled',
]);
}
}

View File

@ -0,0 +1,65 @@
<?php
namespace App\Services;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
class SettingService
{
/**
* Get a setting value by key, with optional default.
*/
public function get(string $key, mixed $default = null): mixed
{
// Use cache to prevent repeated DB queries for settings
$setting = Cache::rememberForever("setting.{$key}", function () use ($key) {
return Setting::where('key', $key)->first();
});
if (!$setting) {
return $default;
}
return $setting->getTypedValue();
}
/**
* Set or update a setting.
*/
public function set(string $key, mixed $value, string $type = 'string'): void
{
// Convert array/object to json if necessary
if (is_array($value) || is_object($value)) {
$value = json_encode($value);
$type = 'json';
} elseif (is_bool($value)) {
$value = $value ? 'true' : 'false';
$type = 'boolean';
}
Setting::updateOrCreate(
['key' => $key],
[
'value' => (string) $value,
'type' => $type,
]
);
// Invalidate cache
Cache::forget("setting.{$key}");
}
/**
* Get all settings as an associative array.
*/
public function getAll(): array
{
$settings = Setting::all();
$result = [];
foreach ($settings as $setting) {
$result[$setting->key] = $setting->getTypedValue();
}
return $result;
}
}

View File

@ -0,0 +1,237 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ZaloBotService
{
protected LinkConverterService $linkConverterService;
protected SettingService $settingService;
public function __construct(
LinkConverterService $linkConverterService,
SettingService $settingService
) {
$this->linkConverterService = $linkConverterService;
$this->settingService = $settingService;
}
/**
* Handle incoming Zalo Bot webhook request.
*/
public function handleWebhook(array $payload): void
{
Log::info('Zalo Webhook payload received', $payload);
// Check if message structure exists (mimics Telegram format)
$message = $payload['message'] ?? null;
if (!$message) {
return;
}
$chatId = $message['chat']['id'] ?? null;
$text = $message['text'] ?? '';
if (!$chatId || empty($text)) {
return;
}
// Get sender name (fallback to "Bạn")
$fromName = trim(
($message['from']['first_name'] ?? '') . ' ' . ($message['from']['last_name'] ?? '')
);
if (empty($fromName)) {
$fromName = $message['from']['username'] ?? 'Bạn';
}
// Find Shopee links
$urls = $this->extractShopeeUrls($text);
if (empty($urls)) {
return;
}
foreach ($urls as $url) {
$this->processAndReplyLink($chatId, $fromName, $url);
}
}
/**
* Process a single Shopee link and reply to the chat.
*/
protected function processAndReplyLink(string $chatId, string $fromName, string $url): void
{
try {
// 1. Resolve redirects if it's a short URL (e.g. s.shopee.vn or shp.ee)
$resolvedUrl = $this->resolveShortUrl($url);
// 2. Extract product name from resolved URL
$productName = $this->extractProductName($resolvedUrl) ?? 'Sản phẩm Shopee';
// 3. Estimate commission
$commission = $this->estimateCommission($resolvedUrl);
// 4. Convert link to our local affiliate short link
$convertResult = $this->linkConverterService->process($resolvedUrl);
if ($convertResult && $convertResult->isSuccess) {
$shortLink = $convertResult->affiliateUrl;
// 5. Construct the message template matching competitor's chatbot
$replyText = "Hi @{$fromName}, Link của bạn đây ạ:\n\n" .
"📦 {$productName}\n" .
"🔗 Link: {$shortLink}\n" .
"💵 Hoa hồng ước tính: {$commission}\n\n" .
"⚠️ Lưu ý: Để hoa hồng hợp lệ, KHÔNG mua qua Livestream, KHÔNG xem video/live bất kỳ sau khi click & XÓA sản phẩm ra khỏi giỏ hàng TRƯỚC KHI bấm link!";
// 6. Send reply message
$this->sendMessage($chatId, $replyText);
} else {
Log::error("Failed to convert Shopee URL via Zalo: " . ($convertResult->errorMessage ?? 'Unknown error'));
}
} catch (\Exception $e) {
Log::error("Error processing link in ZaloBotService: " . $e->getMessage());
}
}
/**
* Extract all Shopee URLs from text.
*/
public function extractShopeeUrls(string $text): array
{
$pattern = '/(?:https?:\/\/)?(?:[a-zA-Z0-9-]+\.)?shopee\.vn\/[^\s]+|(?:https?:\/\/)?shp\.ee\/[^\s]+/i';
if (preg_match_all($pattern, $text, $matches)) {
$urls = [];
foreach ($matches[0] as $url) {
if (!str_starts_with(strtolower($url), 'http://') && !str_starts_with(strtolower($url), 'https://')) {
$url = 'https://' . $url;
}
$urls[] = $url;
}
return $urls;
}
return [];
}
/**
* Resolve short URLs (s.shopee.vn or shp.ee) to get the final redirected URL.
*/
public function resolveShortUrl(string $url): string
{
if (str_contains($url, '/an_redir') || (!str_contains($url, 's.shopee.vn') && !str_contains($url, 'shp.ee'))) {
return $url;
}
try {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true); // Get headers only
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Check redirect location manually
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] >= 300 && $info['http_code'] < 400) {
if (preg_match('/[Ll]ocation:\s*(.+)/', $response, $matches)) {
$resolvedUrl = trim($matches[1]);
// Recursively resolve redirect if it's still a redirect link
return $this->resolveShortUrl($resolvedUrl);
}
}
} catch (\Exception $e) {
Log::warning("Could not resolve short URL redirect: " . $e->getMessage());
}
return $url;
}
/**
* Extract product/shop name from Shopee URL.
*/
public function extractProductName(string $url): ?string
{
$parsedUrl = parse_url($url);
if (!isset($parsedUrl['path'])) {
return null;
}
$path = urldecode($parsedUrl['path']);
$path = trim($path, '/');
// Match typical Shopee product paths ending with -i.SHOP_ID.ITEM_ID
if (preg_match('/^(.*?)-i\.\d+\.\d+$/', $path, $matches)) {
$slug = $matches[1];
$name = str_replace(['-', '_'], ' ', $slug);
return trim($name);
}
// Shop pages / Usernames
if (!str_contains($path, '/')) {
$name = str_replace(['-', '_'], ' ', $path);
return trim($name);
}
return null;
}
/**
* Predictable estimate of product commission based on the item ID.
*/
public function estimateCommission(string $url): string
{
$itemId = 0;
if (preg_match('/-i\.\d+\.(\d+)$/', $url, $matches)) {
$itemId = (int)$matches[1];
}
if ($itemId === 0) {
$itemId = crc32($url);
}
// Predictable single estimate between 4.0% and 7.5% based on itemId or crc32
$rate = 4.0 + (abs($itemId) % 36) / 10.0;
return number_format($rate, 1) . '%';
}
/**
* Send message using Zalo Bot Creator HTTP API.
*/
public function sendMessage(string $chatId, string $text): bool
{
$token = $this->settingService->get('zalo_bot_token') ?? env('ZALO_BOT_TOKEN');
if (!$token) {
Log::error('Zalo Bot Token is not configured. Cannot send message.');
return false;
}
$apiUrl = "https://bot-api.zaloplatforms.com/bot{$token}/sendMessage";
Log::info('Sending message to Zalo Bot', [
'chat_id' => $chatId,
'url' => "https://bot-api.zaloplatforms.com/bot[HIDDEN]/sendMessage"
]);
$response = Http::timeout(10)->post($apiUrl, [
'chat_id' => $chatId,
'text' => $text,
]);
if ($response->successful()) {
Log::info('Message sent successfully to Zalo Bot');
return true;
}
Log::error('Failed to send message to Zalo Bot', [
'status' => $response->status(),
'body' => $response->body()
]);
return false;
}
}

18
artisan Normal file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

19
bootstrap/app.php Normal file
View File

@ -0,0 +1,19 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

2
bootstrap/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

6
bootstrap/providers.php Normal file
View File

@ -0,0 +1,6 @@
<?php
return [
App\Providers\AppServiceProvider::class,
App\Providers\ConverterServiceProvider::class,
];

86
composer.json Normal file
View File

@ -0,0 +1,86 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pail": "^1.2.2",
"laravel/pint": "^1.24",
"laravel/sail": "^1.41",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^11.5.50"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

8395
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
config/app.php Normal file
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

117
config/auth.php Normal file
View File

@ -0,0 +1,117 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

117
config/cache.php Normal file
View File

@ -0,0 +1,117 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
];

184
config/database.php Normal file
View File

@ -0,0 +1,184 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
(PHP_VERSION_ID >= 80500 ? Mysql::ATTR_SSL_CA : PDO::MYSQL_ATTR_SSL_CA) => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

80
config/filesystems.php Normal file
View File

@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

132
config/logging.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
config/mail.php Normal file
View File

@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];

129
config/queue.php Normal file
View File

@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

38
config/services.php Normal file
View File

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

217
config/session.php Normal file
View File

@ -0,0 +1,217 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];

1
database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,45 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,49 @@
<?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('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@ -0,0 +1,35 @@
<?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('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@ -0,0 +1,57 @@
<?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('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,51 @@
<?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('conversion_histories', function (Blueprint $table) {
$table->id();
$table->string('code')->unique()->nullable();
$table->text('original_url');
$table->text('affiliate_url')->nullable();
$table->string('converter_type')->comment('manual, public_web, zalo_bot');
$table->string('session_name')->nullable();
$table->string('status')->default('success')->comment('success, failed');
$table->unsignedInteger('clicks')->default(0);
$table->text('error_message')->nullable();
$table->decimal('execution_time', 8, 4)->default(0);
// Zalo thread attribution
$table->string('zalo_thread_id')->nullable();
$table->string('zalo_chat_name')->nullable();
// Product info
$table->string('product_title')->nullable();
$table->string('product_image')->nullable();
$table->decimal('product_price', 15, 2)->default(0.00);
$table->decimal('estimated_commission', 15, 2)->default(0.00);
// Customer attribution
$table->string('customer_name')->nullable();
$table->string('customer_phone')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('conversion_histories');
}
};

View File

@ -0,0 +1,30 @@
<?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('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value')->nullable();
$table->string('type')->default('string')->comment('string, boolean, integer, json');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('settings');
}
};

View File

@ -0,0 +1,30 @@
<?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('zalo_channels', function (Blueprint $table) {
$table->id();
$table->string('thread_id')->unique();
$table->string('name')->nullable();
$table->boolean('is_allowed')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('zalo_channels');
}
};

View File

@ -0,0 +1,29 @@
<?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('zalo_discovered_groups', function (Blueprint $table) {
$table->id();
$table->string('group_id')->unique();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('zalo_discovered_groups');
}
};

View File

@ -0,0 +1,25 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
}
}

BIN
debug_after_click.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

BIN
debug_screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

17
package.json Normal file
View File

@ -0,0 +1,17 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/vite": "^4.0.0",
"axios": "^1.11.0",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^2.0.0",
"tailwindcss": "^4.0.0",
"vite": "^7.0.7"
}
}

36
phpunit.xml Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_URL" value=""/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>

25
public/.htaccess Normal file
View File

@ -0,0 +1,25 @@
<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}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# 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>

0
public/favicon.ico Normal file
View File

20
public/index.php Normal file
View File

@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());

2
public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

BIN
public/zalo/qr.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

11
resources/css/app.css Normal file
View File

@ -0,0 +1,11 @@
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
}

1
resources/js/app.js Normal file
View File

@ -0,0 +1 @@
import './bootstrap';

4
resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,4 @@
import axios from 'axios';
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

View File

@ -0,0 +1,83 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shopee Affiliate Link | {{ !$hasUsers ? 'Khởi tạo Admin' : 'Đăng nhập' }}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@4.0.0-beta2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.min.css">
</head>
<body class="login-page bg-body-tertiary">
<div class="login-box">
<div class="card card-outline card-primary shadow">
<div class="card-header text-center">
<a href="#" class="h3 text-decoration-none"><b>Shopee Affiliate</b> Link</a>
</div>
<div class="card-body">
@if(!$hasUsers)
<p class="login-box-msg text-danger fw-bold">Khởi tạo tài khoản Quản trị viên (Lần đầu tiên)</p>
<form action="{{ route('register.admin') }}" method="POST">
@csrf
<div class="input-group mb-3">
<input type="text" name="name" class="form-control" placeholder="Họ và tên" required value="{{ old('name') }}">
<div class="input-group-text"><span class="bi bi-person"></span></div>
</div>
<div class="input-group mb-3">
<input type="text" name="email" class="form-control" placeholder="Tài khoản (Username) hoặc Email" required value="{{ old('email') }}">
<div class="input-group-text"><span class="bi bi-envelope"></span></div>
</div>
<div class="input-group mb-3">
<input type="password" name="password" class="form-control" placeholder="Mật khẩu (ít nhất 8 ký tự)" required>
<div class="input-group-text"><span class="bi bi-lock-fill"></span></div>
</div>
<div class="input-group mb-3">
<input type="password" name="password_confirmation" class="form-control" placeholder="Xác nhận mật khẩu" required>
<div class="input-group-text"><span class="bi bi-lock-fill"></span></div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" class="btn btn-primary d-block w-100">Khởi tạo tài khoản & Vào Dashboard</button>
</div>
</div>
</form>
@else
<p class="login-box-msg">Đăng nhập để vào trang quản trị</p>
@if($errors->any())
<div class="alert alert-danger p-2 small">
<ul class="mb-0 ps-3">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('login') }}" method="POST">
@csrf
<div class="input-group mb-3">
<input type="text" name="email" class="form-control" placeholder="Tài khoản (Username) hoặc Email" required value="{{ old('email') }}">
<div class="input-group-text"><span class="bi bi-envelope"></span></div>
</div>
<div class="input-group mb-3">
<input type="password" name="password" class="form-control" placeholder="Mật khẩu" required>
<div class="input-group-text"><span class="bi bi-lock-fill"></span></div>
</div>
<div class="row align-items-center">
<div class="col-8">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember">
<label class="form-check-label" for="remember">Ghi nhớ</label>
</div>
</div>
<div class="col-4">
<button type="submit" class="btn btn-primary d-block w-100">Đăng nhập</button>
</div>
</div>
</form>
@endif
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@ -0,0 +1,84 @@
@extends('layouts.app')
@section('title', 'Convert Link')
@section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-primary card-outline mb-4">
<div class="card-header">
<div class="card-title">Paste your Shopee link here</div>
</div>
<form action="{{ route('convert.process') }}" method="POST">
@csrf
<div class="card-body">
<div class="input-group input-group-lg mb-3">
<input type="url" name="url" class="form-control" placeholder="https://shopee.vn/..." required autofocus value="{{ old('url') }}">
<button type="submit" class="btn btn-primary">Convert</button>
<button type="reset" class="btn btn-secondary">Clear</button>
</div>
</div>
</form>
</div>
@if(session('success_result'))
@php $result = session('success_result'); @endphp
<div class="card card-success card-outline">
<div class="card-header">
<h3 class="card-title">Conversion Successful</h3>
</div>
<div class="card-body">
<div class="mb-3">
<label>Original URL</label>
<input type="text" class="form-control" value="{{ $result->originalUrl }}" readonly>
</div>
<div class="mb-3">
<label>Affiliate URL</label>
<div class="input-group">
<input type="text" id="affiliate_url" class="form-control fw-bold text-success" value="{{ $result->affiliateUrl }}" readonly>
<button class="btn btn-outline-secondary" type="button" onclick="copyToClipboard()">Copy</button>
</div>
</div>
<div class="row text-muted small">
<div class="col-md-4">Converter: <strong>{{ $result->converterType }}</strong></div>
<div class="col-md-4">Session: <strong>{{ $result->sessionUsed }}</strong></div>
<div class="col-md-4">Execution Time: <strong>{{ number_format($result->executionTime, 4) }}s</strong></div>
</div>
</div>
</div>
@endif
@if(session('error_result'))
@php $result = session('error_result'); @endphp
<div class="card card-danger card-outline">
<div class="card-header">
<h3 class="card-title">Conversion Failed</h3>
</div>
<div class="card-body">
<p class="text-danger fw-bold">{{ $result->errorMessage }}</p>
<div class="mb-3">
<label>Original URL</label>
<input type="text" class="form-control" value="{{ $result->originalUrl }}" readonly>
</div>
<div class="row text-muted small">
<div class="col-md-4">Converter: <strong>{{ $result->converterType }}</strong></div>
<div class="col-md-4">Session: <strong>{{ $result->sessionUsed ?? '-' }}</strong></div>
</div>
</div>
</div>
@endif
</div>
</div>
@endsection
@push('scripts')
<script>
function copyToClipboard() {
var copyText = document.getElementById("affiliate_url");
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard.writeText(copyText.value);
alert("Copied: " + copyText.value);
}
</script>
@endpush

View File

@ -0,0 +1,282 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tra Cứu Lượt Click & Hoa Hồng - Shopee Affiliate</title>
<!-- Fonts & Icons -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.min.css">
<style>
:root {
--bg-gradient: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
--accent-primary: #8b5cf6;
--accent-secondary: #ec4899;
--glass-bg: rgba(255, 255, 255, 0.03);
--glass-border: rgba(255, 255, 255, 0.08);
--text-main: #f8fafc;
--text-muted: #94a3b8;
}
body {
font-family: 'Inter', sans-serif;
background: var(--bg-gradient);
min-height: 100vh;
color: var(--text-main);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-x: hidden;
position: relative;
padding: 40px 0;
}
.blur-sphere-1 {
position: absolute;
width: 400px;
height: 400px;
background: radial-gradient(circle, rgba(139, 92, 246, 0.12) 0%, rgba(0,0,0,0) 70%);
top: -100px;
left: -100px;
z-index: 0;
pointer-events: none;
}
.blur-sphere-2 {
position: absolute;
width: 450px;
height: 450px;
background: radial-gradient(circle, rgba(236, 72, 153, 0.12) 0%, rgba(0,0,0,0) 70%);
bottom: -150px;
right: -100px;
z-index: 0;
pointer-events: none;
}
.container {
position: relative;
z-index: 10;
max-width: 800px;
}
.brand-logo {
text-align: center;
margin-bottom: 2rem;
}
.brand-logo i {
font-size: 2.5rem;
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
margin-bottom: 0.5rem;
filter: drop-shadow(0 0 10px rgba(139, 92, 246, 0.3));
}
.brand-title {
font-size: 1.85rem;
font-weight: 800;
letter-spacing: -0.025em;
background: linear-gradient(to right, #ffffff, #c084fc);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.glass-card {
background: var(--glass-bg);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 2.5rem;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
width: 100%;
}
.form-control-custom {
background: rgba(15, 23, 42, 0.6);
border: 1px solid var(--glass-border);
border-radius: 14px;
color: var(--text-main);
padding: 0.85rem 1.25rem;
font-size: 1rem;
transition: all 0.2s ease;
}
.form-control-custom:focus {
background: rgba(15, 23, 42, 0.8);
border-color: var(--accent-primary);
box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2);
color: var(--text-main);
}
.btn-custom {
background: linear-gradient(135deg, var(--accent-primary), #7c3aed);
border: none;
border-radius: 14px;
color: #ffffff;
font-weight: 600;
padding: 0.85rem 1.5rem;
transition: all 0.2s ease;
}
.btn-custom:hover {
transform: translateY(-1px);
background: linear-gradient(135deg, #9333ea, #6d28d9);
}
.stat-card {
background: rgba(255, 255, 255, 0.02);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 1.25rem;
text-align: center;
}
.stat-val {
font-size: 1.5rem;
font-weight: 800;
color: #34d399;
}
.table-custom {
color: var(--text-main);
border-color: rgba(255, 255, 255, 0.05);
}
.table-custom th {
color: var(--text-muted);
font-weight: 600;
font-size: 0.85rem;
text-transform: uppercase;
border-bottom-width: 2px;
padding: 1rem;
}
.table-custom td {
padding: 1rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
font-size: 0.95rem;
}
footer {
margin-top: 3rem;
color: #4b5563;
font-size: 0.85rem;
text-align: center;
z-index: 10;
}
footer a {
color: var(--text-muted);
text-decoration: none;
}
footer a:hover {
color: #ffffff;
}
</style>
</head>
<body>
<div class="blur-sphere-1"></div>
<div class="blur-sphere-2"></div>
<div class="container">
<div class="brand-logo">
<i class="bi bi-person-badge-fill"></i>
<h1 class="brand-title">Tra Cứu Kết Quả Affiliate</h1>
<p class="text-muted small">Nhập số điện thoại để theo dõi hiệu suất lượt click & hoa hồng ước tính</p>
</div>
<div class="glass-card">
<!-- Search Form -->
<form action="{{ route('customer_lookup.search') }}" method="GET" class="mb-4">
<div class="d-flex flex-column flex-sm-row gap-3">
<input type="text" name="phone" class="form-control form-control-custom flex-grow-1"
placeholder="Nhập số điện thoại đăng ký (ví dụ: 0987654321)"
value="{{ $phone ?? '' }}" required autocomplete="off">
<button type="submit" class="btn btn-custom"><i class="bi bi-search me-1"></i> Tra cứu</button>
</div>
</form>
@if(isset($searched) && $searched)
<hr style="border-color: rgba(255, 255, 255, 0.1);" class="my-4">
<!-- Summary Stats -->
<div class="row g-3 mb-4">
<div class="col-6 col-md-4">
<div class="stat-card">
<div class="text-muted small mb-1">Số link đã tạo</div>
<div class="stat-val text-white">{{ $histories->count() }}</div>
</div>
</div>
<div class="col-6 col-md-4">
<div class="stat-card">
<div class="text-muted small mb-1">Tổng lượt click</div>
<div class="stat-val text-info">{{ number_format($histories->sum('clicks')) }}</div>
</div>
</div>
<div class="col-12 col-md-4">
<div class="stat-card">
<div class="text-muted small mb-1">Hoa hồng ước tính</div>
<div class="stat-val">~{{ number_format($histories->sum('estimated_commission')) }}đ</div>
</div>
</div>
</div>
<!-- Warning disclaimer -->
<div class="alert alert-warning border-0 bg-warning bg-opacity-10 text-warning rounded-4 px-4 py-3 mb-4 small" role="alert">
<i class="bi bi-info-circle-fill me-2"></i>
<strong>Lưu ý:</strong> Hoa hồng trên đây chỉ **ước tính tham khảo** dựa trên giá sản phẩm. Số tiền thực tế nhận được phụ thuộc vào đơn hàng mua thành công hợp lệ được Shopee đối soát duyệt chi trả.
</div>
<!-- Result Table -->
<div class="table-responsive">
<table class="table table-custom align-middle">
<thead>
<tr>
<th>Thời gian</th>
<th>Sản phẩm</th>
<th>Giá bán</th>
<th>Lượt click</th>
<th>Hoa hồng ước tính</th>
</tr>
</thead>
<tbody>
@forelse($histories as $history)
<tr>
<td class="text-nowrap small text-muted">{{ $history->created_at->format('H:i d/m/Y') }}</td>
<td class="text-truncate fw-semibold" style="max-width: 250px;" title="{{ $history->product_title ?? 'Sản phẩm Shopee' }}">
{{ $history->product_title ?? 'Sản phẩm Shopee' }}
</td>
<td class="text-nowrap">{{ $history->product_price > 0 ? number_format($history->product_price) . 'đ' : '-' }}</td>
<td class="text-center text-nowrap fw-bold text-info">{{ number_format($history->clicks) }}</td>
<td class="text-nowrap fw-bold text-success">{{ $history->estimated_commission > 0 ? '~' . number_format($history->estimated_commission) . 'đ' : '-' }}</td>
</tr>
@empty
<tr>
<td colspan="5" class="text-center py-4 text-muted">Không tìm thấy lịch sử tạo link nào cho số điện thoại này.</td>
</tr>
@endif
</tbody>
</table>
</div>
@endif
<div class="text-center mt-4">
<a href="{{ route('public_convert.index') }}" class="btn btn-link text-decoration-none small text-muted"><i class="bi bi-arrow-left me-1"></i> Quay lại trang tạo link</a>
</div>
</div>
<footer>
&copy; 2026 - Rút Gọn Link Shopee Affiliate.
</footer>
</div>
</body>
</html>

View File

@ -0,0 +1,74 @@
@extends('layouts.app')
@section('title', 'Dashboard')
@section('content')
<div class="row">
<div class="col-lg-4 col-12">
<div class="small-box text-bg-info">
<div class="inner">
<h3>{{ $totalConversions }}</h3>
<p>Total Conversions (Offline)</p>
</div>
<div class="small-box-icon">
<i class="bi bi-link"></i>
</div>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Recent Conversions</h3>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>ID</th>
<th>Original URL</th>
<th>Affiliate URL</th>
<th>Status</th>
<th>Session</th>
<th>Time</th>
</tr>
</thead>
<tbody>
@forelse($recentConversions as $conv)
<tr>
<td>{{ $conv->id }}</td>
<td><a href="{{ $conv->original_url }}" target="_blank" class="text-truncate d-inline-block" style="max-width: 200px;">{{ $conv->original_url }}</a></td>
<td>
@if($conv->code)
@php $shortUrl = route('short_link.redirect', ['code' => $conv->code]); @endphp
<a href="{{ $shortUrl }}" target="_blank" title="Redirects to: {{ $conv->affiliate_url }}">{{ $shortUrl }}</a>
@elseif($conv->affiliate_url)
<a href="{{ $conv->affiliate_url }}" target="_blank" class="text-truncate d-inline-block" style="max-width: 200px;">{{ $conv->affiliate_url }}</a>
@else
-
@endif
</td>
<td>
@if($conv->status === 'success')
<span class="badge text-bg-success">Success</span>
@else
<span class="badge text-bg-danger">Failed</span>
@endif
</td>
<td>{{ $conv->session_name ?? '-' }}</td>
<td>{{ $conv->created_at->diffForHumans() }}</td>
</tr>
@empty
<tr>
<td colspan="6" class="text-center">No conversions yet.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</div>
@endsection

View File

@ -0,0 +1,247 @@
@extends('layouts.app')
@section('title', 'Lịch sử chuyển đổi')
@section('content')
<div class="row">
<div class="col-12">
<!-- Bulk Action Header -->
<div class="mb-3 d-flex align-items-center justify-content-between">
<div>
<p class="m-0 text-muted small">Chọn các dòng cần xóa hoặc quản link</p>
</div>
<div>
<button type="button" id="btn-bulk-delete" class="btn btn-danger btn-sm d-none shadow-sm fw-bold" onclick="submitBulkDelete()">
<i class="bi bi-trash3-fill me-1"></i> Xóa mục đã chọn (<span id="select-count">0</span>)
</button>
</div>
</div>
<div class="card shadow-sm">
<div class="card-body table-responsive p-0">
<table class="table table-hover align-middle text-nowrap">
<thead>
<tr>
<th style="width: 40px;" class="px-3">
<input type="checkbox" id="select-all" class="form-check-input">
</th>
<th>Thời gian</th>
<th>Kênh Zalo</th>
<th>Khách hàng</th>
<th>Link gốc</th>
<th>Link rút gọn</th>
<th>Lượt click</th>
<th>Trạng thái</th>
<th class="text-end px-3">Hành động</th>
</tr>
</thead>
<tbody>
@forelse($histories as $history)
<tr>
<td class="px-3">
<input type="checkbox" value="{{ $history->id }}" class="form-check-input history-checkbox">
</td>
<td>{{ $history->created_at->format('H:i:s d/m/Y') }}</td>
<td>
@if($history->zalo_thread_id)
<div class="d-flex align-items-center gap-3">
<div>
<span class="d-block fw-bold text-primary" title="Thread ID: {{ $history->zalo_thread_id }}">
<i class="bi bi-chat-dots-fill me-1"></i> {{ $history->zalo_chat_name ?? 'Nhóm Zalo' }}
</span>
<small class="text-muted" style="font-size: 0.75rem;">ID: {{ $history->zalo_thread_id }}</small>
</div>
<div>
<form action="{{ route('zalo_channels.quick_toggle') }}" method="POST" class="d-inline">
@csrf
<input type="hidden" name="thread_id" value="{{ $history->zalo_thread_id }}">
<input type="hidden" name="name" value="{{ $history->zalo_chat_name }}">
@if(in_array($history->zalo_thread_id, $allowedThreadIds))
<button type="submit" class="btn btn-danger btn-sm py-0 px-2 fw-bold text-white shadow-sm" style="font-size: 0.75rem;" title="Ngắt kết nối Bot với nhóm này">
<i class="bi bi-slash-circle-fill"></i> Chặn
</button>
@else
<button type="submit" class="btn btn-success btn-sm py-0 px-2 fw-bold text-white shadow-sm" style="font-size: 0.75rem;" title="Cho phép Bot phản hồi nhóm này">
<i class="bi bi-check-circle-fill"></i> Cho phép
</button>
@endif
</form>
</div>
</div>
@else
<span class="badge text-bg-secondary px-2"><i class="bi bi-globe me-1"></i> Web Rút Gọn</span>
@endif
</td>
<td>
@if($history->customer_name || $history->customer_phone)
<span class="d-block fw-bold text-dark">{{ $history->customer_name ?: 'Ẩn danh' }}</span>
@if($history->customer_phone)
<small class="text-muted"><i class="bi bi-telephone-fill me-1" style="font-size: 0.7rem;"></i>{{ $history->customer_phone }}</small>
@endif
@else
<span class="text-muted">-</span>
@endif
</td>
<td>
<a href="{{ $history->original_url }}" target="_blank" class="text-truncate d-inline-block" style="max-width: 250px;" title="{{ $history->original_url }}">{{ $history->original_url }}</a>
</td>
<td>
@if($history->code)
@php
$domainSetting = app(\App\Services\SettingService::class)->get('short_link_domain');
if ($domainSetting) {
$shortUrl = rtrim($domainSetting, '/') . '/aff/s/' . $history->code;
} else {
$shortUrl = route('short_link.redirect', ['code' => $history->code]);
}
@endphp
<div class="d-inline-flex align-items-center gap-2">
<a href="{{ $shortUrl }}" target="_blank" class="fw-bold text-success">{{ $shortUrl }}</a>
<button type="button" onclick="copyToClipboard('{{ $shortUrl }}', this)" class="btn btn-outline-primary btn-sm py-0 px-1 border-0" title="Copy Link">
<i class="bi bi-clipboard"></i>
</button>
</div>
@elseif($history->affiliate_url)
<a href="{{ $history->affiliate_url }}" target="_blank" class="text-truncate d-inline-block" style="max-width: 250px;">{{ $history->affiliate_url }}</a>
@else
<span class="text-muted">-</span>
@endif
</td>
<td>
<span class="badge text-bg-info px-2 py-1 text-white" style="font-weight: 600;"><i class="bi bi-eye-fill me-1"></i> {{ number_format($history->clicks) }}</span>
</td>
<td>
@if($history->status === 'success')
<span class="badge text-bg-success"><i class="bi bi-check-circle me-1"></i> Thành công</span>
@elseif($history->zalo_thread_id && $history->status === 'failed' && str_contains($history->error_message, 'restricted'))
<span class="badge text-bg-warning text-dark" title="{{ $history->error_message }}"><i class="bi bi-slash-circle me-1"></i> Bị chặn (Whitelist)</span>
@else
<span class="badge text-bg-danger" title="{{ $history->error_message }}"><i class="bi bi-exclamation-triangle me-1"></i> Thất bại</span>
@endif
</td>
<td class="text-end px-3">
<button type="button" onclick="deleteSingle({{ $history->id }})" class="btn btn-outline-danger btn-sm py-1 px-2 border-0" title="Xóa lịch sử">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
@empty
<tr>
<td colspan="9" class="text-center py-4 text-muted">Không tìm thấy lịch sử nào.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@if($histories->hasPages())
<div class="card-footer clearfix bg-light">
{{ $histories->links() }}
</div>
@endif
</div>
</div>
</div>
<!-- Hidden Bulk & Single Delete Forms -->
<form id="bulk-delete-form" action="{{ route('history.bulk_destroy') }}" method="POST" style="display:none;">
@csrf
@method('DELETE')
</form>
<form id="single-delete-form" method="POST" style="display:none;">
@csrf
@method('DELETE')
</form>
@endsection
@push('scripts')
<script>
const selectAllCheckbox = document.getElementById('select-all');
const checkboxes = document.querySelectorAll('.history-checkbox');
const bulkDeleteBtn = document.getElementById('btn-bulk-delete');
const selectCountSpan = document.getElementById('select-count');
const bulkDeleteForm = document.getElementById('bulk-delete-form');
const singleDeleteForm = document.getElementById('single-delete-form');
// Toggle select all checkboxes
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('change', function() {
checkboxes.forEach(cb => {
cb.checked = this.checked;
});
updateBulkDeleteButton();
});
}
// Toggle single checkbox
checkboxes.forEach(cb => {
cb.addEventListener('change', function() {
if (!this.checked) {
selectAllCheckbox.checked = false;
} else {
const allChecked = Array.from(checkboxes).every(c => c.checked);
selectAllCheckbox.checked = allChecked;
}
updateBulkDeleteButton();
});
});
// Update bulk action button visibility
function updateBulkDeleteButton() {
const checkedCount = Array.from(checkboxes).filter(c => c.checked).length;
if (selectCountSpan) selectCountSpan.textContent = checkedCount;
if (checkedCount > 0) {
bulkDeleteBtn.classList.remove('d-none');
} else {
bulkDeleteBtn.classList.add('d-none');
}
}
// Trigger Bulk Delete Submit (append checked IDs dynamically)
function submitBulkDelete() {
const checkedBoxes = Array.from(checkboxes).filter(c => c.checked);
if (checkedBoxes.length === 0) return;
if (confirm(`Bạn có chắc chắn muốn xóa ${checkedBoxes.length} lịch sử đã chọn không?`)) {
// Remove old dynamic ID inputs from form if any
const existingInputs = bulkDeleteForm.querySelectorAll('input[name="ids[]"]');
existingInputs.forEach(input => input.remove());
// Create and append dynamic input fields for each checked item ID
checkedBoxes.forEach(cb => {
const hiddenInput = document.createElement('input');
hiddenInput.type = 'hidden';
hiddenInput.name = 'ids[]';
hiddenInput.value = cb.value;
bulkDeleteForm.appendChild(hiddenInput);
});
bulkDeleteForm.submit();
}
}
// Trigger Single Delete
function deleteSingle(id) {
if (confirm('Bạn có chắc muốn xóa lịch sử chuyển đổi này không?')) {
singleDeleteForm.action = `/history/${id}`;
singleDeleteForm.submit();
}
}
// Clipboard copy helper
function copyToClipboard(text, button) {
navigator.clipboard.writeText(text).then(() => {
const icon = button.querySelector('i');
icon.className = 'bi bi-check-lg';
button.className = 'btn btn-success btn-sm py-0 px-1 border-0';
setTimeout(() => {
icon.className = 'bi bi-clipboard';
button.className = 'btn btn-outline-primary btn-sm py-0 px-1 border-0';
}, 1500);
}).catch(err => {
console.error('Không thể copy link:', err);
});
}
</script>
@endpush

View File

@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shopee Link Converter | @yield('title')</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@4.0.0-beta2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.min.css">
@stack('styles')
</head>
<body class="layout-fixed sidebar-expand-lg bg-body-tertiary">
<div class="app-wrapper">
<!-- Header -->
<nav class="app-header navbar navbar-expand bg-body">
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-lte-toggle="sidebar" href="#" role="button"><i class="bi bi-list"></i></a>
</li>
</ul>
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<form action="{{ route('logout') }}" method="POST" class="d-inline">
@csrf
<button type="submit" class="btn btn-link nav-link"><i class="bi bi-box-arrow-right"></i> Đăng xuất</button>
</form>
</li>
</ul>
</div>
</nav>
<!-- Sidebar -->
<aside class="app-sidebar bg-body-secondary shadow" data-bs-theme="dark">
<div class="sidebar-brand">
<a href="{{ route('dashboard') }}" class="brand-link">
<span class="brand-text fw-bold text-white"><i class="bi bi-rocket-takeoff-fill text-warning me-1"></i>Shopee Affiliate</span>
</a>
</div>
<div class="sidebar-wrapper">
<nav class="mt-2">
<ul class="nav sidebar-menu flex-column" data-lte-toggle="treeview" role="menu" data-accordion="false">
<li class="nav-item">
<a href="{{ route('dashboard') }}" class="nav-link {{ request()->routeIs('dashboard') ? 'active' : '' }}">
<i class="nav-icon bi bi-speedometer"></i>
<p>Dashboard</p>
</a>
</li>
<li class="nav-item">
<a href="{{ route('history.index') }}" class="nav-link {{ request()->routeIs('history.*') ? 'active' : '' }}">
<i class="nav-icon bi bi-clock-history"></i>
<p>History</p>
</a>
</li>
<li class="nav-item">
<a href="{{ route('zalo_channels.index') }}" class="nav-link {{ request()->routeIs('zalo_channels.*') ? 'active' : '' }}">
<i class="nav-icon bi bi-chat-left-dots"></i>
<p>Kênh Zalo</p>
</a>
</li>
<li class="nav-item">
<a href="{{ route('settings.index') }}" class="nav-link {{ request()->routeIs('settings.*') ? 'active' : '' }}">
<i class="nav-icon bi bi-gear"></i>
<p>Settings</p>
</a>
</li>
</ul>
</nav>
</div>
</aside>
<!-- Main content -->
<main class="app-main">
<div class="app-content-header">
<div class="container-fluid">
<div class="row">
<div class="col-sm-6">
<h3 class="mb-0">@yield('title')</h3>
</div>
</div>
</div>
</div>
<div class="app-content">
<div class="container-fluid">
@if(session('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('success') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif
@if($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<ul class="mb-0">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif
@yield('content')
</div>
</div>
</main>
</div>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@4.0.0-beta2/dist/js/adminlte.min.js"></script>
@stack('scripts')
</body>
</html>

View File

@ -0,0 +1,400 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rút Gọn Link Shopee Affiliate - Tạo Link Nhanh</title>
<!-- Fonts & Icons -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.min.css">
<style>
:root {
--bg-gradient: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
--accent-primary: #8b5cf6;
--accent-secondary: #ec4899;
--glass-bg: rgba(255, 255, 255, 0.03);
--glass-border: rgba(255, 255, 255, 0.08);
--text-main: #f8fafc;
--text-muted: #94a3b8;
}
body {
font-family: 'Inter', sans-serif;
background: var(--bg-gradient);
min-height: 100vh;
color: var(--text-main);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-x: hidden;
position: relative;
padding: 20px 0;
}
/* Underlay blurs */
.blur-sphere-1 {
position: absolute;
width: 400px;
height: 400px;
background: radial-gradient(circle, rgba(139, 92, 246, 0.15) 0%, rgba(0,0,0,0) 70%);
top: -100px;
left: -100px;
z-index: 0;
pointer-events: none;
}
.blur-sphere-2 {
position: absolute;
width: 450px;
height: 450px;
background: radial-gradient(circle, rgba(236, 72, 153, 0.15) 0%, rgba(0,0,0,0) 70%);
bottom: -150px;
right: -100px;
z-index: 0;
pointer-events: none;
}
.container {
position: relative;
z-index: 10;
max-width: 650px;
}
.brand-logo {
text-align: center;
margin-bottom: 2rem;
}
.brand-logo i {
font-size: 3rem;
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
margin-bottom: 0.5rem;
filter: drop-shadow(0 0 15px rgba(139, 92, 246, 0.3));
}
.brand-title {
font-size: 2.25rem;
font-weight: 800;
letter-spacing: -0.025em;
background: linear-gradient(to right, #ffffff, #c084fc);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.brand-subtitle {
color: var(--text-muted);
font-size: 1rem;
font-weight: 500;
}
/* Glass Card */
.glass-card {
background: var(--glass-bg);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 2.5rem;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.glass-card:hover {
border-color: rgba(255, 255, 255, 0.15);
box-shadow: 0 20px 45px rgba(139, 92, 246, 0.1);
}
/* Input styling */
.form-control-custom {
background: rgba(15, 23, 42, 0.6);
border: 1px solid var(--glass-border);
border-radius: 14px;
color: var(--text-main);
padding: 1rem 1.25rem;
font-size: 1rem;
transition: all 0.2s ease;
}
.form-control-custom:focus {
background: rgba(15, 23, 42, 0.8);
border-color: var(--accent-primary);
box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2);
color: var(--text-main);
outline: none;
}
.form-control-custom::placeholder {
color: #4b5563;
}
/* Button styling */
.btn-custom {
background: linear-gradient(135deg, var(--accent-primary), #7c3aed);
border: none;
border-radius: 14px;
color: #ffffff;
font-weight: 600;
padding: 1rem;
transition: all 0.2s ease;
box-shadow: 0 10px 20px -5px rgba(139, 92, 246, 0.4);
}
.btn-custom:hover {
transform: translateY(-2px);
box-shadow: 0 12px 22px -3px rgba(139, 92, 246, 0.5);
background: linear-gradient(135deg, #9333ea, #6d28d9);
}
.btn-custom:active {
transform: translateY(0);
}
/* Result Area */
.result-container {
background: rgba(139, 92, 246, 0.05);
border: 1px dashed rgba(139, 92, 246, 0.3);
border-radius: 16px;
padding: 1.5rem;
margin-top: 2rem;
animation: fadeIn 0.4s ease-out forwards;
}
.result-title {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--accent-primary);
font-weight: 700;
margin-bottom: 0.5rem;
}
.result-link-box {
display: flex;
align-items: center;
justify-content: space-between;
background: rgba(15, 23, 42, 0.4);
padding: 0.75rem 1rem;
border-radius: 10px;
border: 1px solid rgba(255, 255, 255, 0.05);
}
.result-link {
color: #34d399;
font-weight: 700;
text-decoration: none;
word-break: break-all;
margin-right: 1rem;
font-size: 1.1rem;
}
.btn-copy {
background: rgba(52, 211, 153, 0.1);
color: #34d399;
border: 1px solid rgba(52, 211, 153, 0.2);
border-radius: 8px;
padding: 0.5rem 1rem;
font-size: 0.9rem;
font-weight: 600;
transition: all 0.2s ease;
}
.btn-copy:hover {
background: #34d399;
color: #0f172a;
border-color: #34d399;
}
/* Loading Spinner */
.loading-overlay {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(15, 23, 42, 0.8);
border-radius: 24px;
z-index: 20;
justify-content: center;
align-items: center;
flex-direction: column;
backdrop-filter: blur(4px);
}
/* Animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
footer {
margin-top: 3rem;
color: #4b5563;
font-size: 0.85rem;
text-align: center;
z-index: 10;
}
footer a {
color: var(--text-muted);
text-decoration: none;
}
footer a:hover {
color: #ffffff;
}
</style>
</head>
<body>
<div class="blur-sphere-1"></div>
<div class="blur-sphere-2"></div>
<div class="container text-center">
<!-- Logo & Brand Header -->
<div class="brand-logo">
<i class="bi bi-rocket-takeoff-fill"></i>
<h1 class="brand-title">Shopee Affiliate Link</h1>
<p class="brand-subtitle">Rút gọn link kiếm tiền hoa hồng trong 1 nốt nhạc</p>
</div>
<!-- Conversion Card -->
<div class="glass-card text-start position-relative">
<!-- Loading Indicator -->
<div id="loading" class="loading-overlay">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;"></div>
<div class="mt-3 fw-bold text-white">Đang convert link Shopee...</div>
</div>
<!-- Error Alerts -->
@if(session('error'))
<div class="alert alert-danger border-0 bg-danger bg-opacity-10 text-danger rounded-4 px-4 py-3 mb-4" role="alert">
<i class="bi bi-exclamation-triangle-fill me-2"></i> {{ session('error') }}
</div>
@endif
<form action="{{ route('public_convert.process') }}" method="POST" onsubmit="showLoading()">
@csrf
<div class="mb-4">
<label for="url" class="form-label fw-semibold mb-2">Nhập link Shopee của bạn</label>
<input type="url" name="url" id="url" class="form-control form-control-custom"
placeholder="https://shopee.vn/product-name-i.1234567.891011"
value="{{ old('url', session('original_url')) }}" required autocomplete="off">
<div class="form-text mt-2 small" style="color: rgba(255, 255, 255, 0.45);">
Hỗ trợ link sản phẩm Shopee, link shop, link bộ sưu tập, hoặc link rút gọn s.shopee.vn.
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 mb-3 mb-md-0">
<label for="customer_name" class="form-label fw-semibold mb-2">Họ tên <span class="text-muted fw-normal">(Không bắt buộc)</span></label>
<input type="text" name="customer_name" id="customer_name" class="form-control form-control-custom"
placeholder="Ví dụ: Nguyễn Văn A" value="{{ old('customer_name') }}" autocomplete="off">
</div>
<div class="col-md-6">
<label for="customer_phone" class="form-label fw-semibold mb-2">Số điện thoại <span class="text-muted fw-normal">(Không bắt buộc)</span></label>
<input type="tel" name="customer_phone" id="customer_phone" class="form-control form-control-custom"
placeholder="Ví dụ: 0987654321" value="{{ old('customer_phone') }}" autocomplete="off">
</div>
</div>
<div class="mb-4 bg-white bg-opacity-5 p-3 rounded-3 border border-white border-opacity-10">
<div class="small text-muted" style="line-height: 1.5;">
<i class="bi bi-info-circle text-info me-1"></i>
<strong>Quyền lợi hoa hồng:</strong> Việc nhập Tên & Số điện thoại <strong>không bắt buộc</strong>. Tuy nhiên, nếu bạn điền thông tin, Admin sẽ dựa vào đó để đối soát đơn hàng <strong>chia lại tiền hoa hồng</strong> chiết khấu trực tiếp cho bạn!
</div>
</div>
<button type="submit" class="btn btn-custom w-100 fs-6"><i class="bi bi-magic me-1"></i> Rút Gọn Link Ngay</button>
<div class="text-center mt-3">
<a href="{{ route('customer_lookup.index') }}" class="text-decoration-none small text-muted"><i class="bi bi-search me-1"></i> Bạn muốn tra cứu số click & hoa hồng đã tích lũy? Bấm vào đây</a>
</div>
</form>
<!-- Result Box -->
@if(session('short_url'))
<div class="result-container">
@if(session('product_title'))
<div class="mb-3">
<div class="result-title">Sản phẩm:</div>
<div class="fw-bold text-white small"><i class="bi bi-box-seam me-1 text-warning"></i> {{ session('product_title') }}</div>
</div>
@endif
<div class="mb-3">
<div class="result-title">Link Affiliate của bạn:</div>
<div class="result-link-box">
<a href="{{ session('short_url') }}" target="_blank" class="result-link" id="short-link">{{ session('short_url') }}</a>
<button onclick="copyLink(this, '{{ session('short_url') }}')" class="btn btn-copy">
<i class="bi bi-copy me-1"></i> Copy
</button>
</div>
</div>
@if(session('estimated_commission') && session('estimated_commission') > 0)
<div class="mt-2 bg-success bg-opacity-10 border border-success border-opacity-20 rounded-3 p-3 text-start">
<div class="fw-bold text-success" style="font-size: 1.05rem;">
<i class="bi bi-cash-coin me-1"></i> Hoa hồng ước tính: ~{{ number_format(session('estimated_commission')) }}đ
</div>
<div class="small mt-1" style="color: rgba(255, 255, 255, 0.45); font-size: 0.8rem; line-height: 1.4;">
* Lưu ý: Số tiền hoa hồng hiển thị trên chỉ <strong>ước tính tham khảo</strong> dựa trên giá sản phẩm tại thời điểm tạo link. Hoa hồng thực tế nhận được thể chênh lệch tùy thuộc vào chính sách chiết khấu động của Shopee loại shop tại thời điểm người mua thanh toán đơn hàng thành công.
</div>
</div>
@endif
</div>
@endif
</div>
<!-- Zalo Community Group Card -->
@php
$zaloGroupUrl = app(\App\Services\SettingService::class)->get('zalo_group_join_url');
@endphp
@if($zaloGroupUrl)
<div class="glass-card text-center mt-4 p-4" style="border-radius: 20px;">
<h5 class="fw-bold text-success mb-2"><i class="bi bi-chat-dots-fill me-1"></i> Tham gia cộng đồng Zalo</h5>
<p class="text-muted small mb-3">Tham gia nhóm Zalo của chúng tôi để nhận tin tức giảm giá hot nhất được hỗ trợ 24/7 từ Admin!</p>
<a href="{{ $zaloGroupUrl }}" target="_blank" class="btn btn-outline-success btn-sm px-4 py-2 rounded-pill fw-bold text-white border-success bg-success bg-opacity-25" style="box-shadow: 0 5px 15px rgba(25, 135, 84, 0.2);">
<i class="bi bi-box-arrow-in-right me-1"></i> Tham gia nhóm Zalo ngay
</a>
</div>
@endif
<footer>
&copy; 2026 - Rút Gọn Link Shopee Affiliate.
</footer>
</div>
<!-- Script logic -->
<script>
function showLoading() {
document.getElementById('loading').style.display = 'flex';
}
function copyLink(button, text) {
navigator.clipboard.writeText(text).then(() => {
const originalText = button.innerHTML;
button.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
button.style.backgroundColor = '#34d399';
button.style.color = '#0f172a';
button.style.borderColor = '#34d399';
setTimeout(() => {
button.innerHTML = originalText;
button.style.backgroundColor = '';
button.style.color = '';
button.style.borderColor = '';
}, 2000);
}).catch(err => {
console.error('Không thể copy link:', err);
});
}
</script>
</body>
</html>

View File

@ -0,0 +1,171 @@
@extends('layouts.app')
@section('title', 'Settings')
@section('content')
<div class="row">
<!-- Left Card: Configurations -->
<div class="col-md-7">
<div class="card card-primary card-outline shadow mb-4">
<div class="card-header">
<h3 class="card-title font-weight-bold">Cấu hình hệ thống</h3>
</div>
<form action="{{ route('settings.update') }}" method="POST">
@csrf
<div class="card-body">
<div class="mb-3">
<label class="form-label font-weight-bold">Affiliate ID</label>
<input type="text" name="affiliate_id" class="form-control" value="{{ $settings['affiliate_id'] ?? '' }}" placeholder="e.g. 14354840000" required>
<small class="text-muted"> Affiliate ID của bạn (lấy từ thiết lập tài khoản Shopee Affiliate). Đây tham số bắt buộc để hệ thống tạo link chuyển hướng (an_redir) offline.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Zalo Bot Token</label>
<input type="text" name="zalo_bot_token" class="form-control" value="{{ $settings['zalo_bot_token'] ?? '' }}" placeholder="e.g. 397768738295918070:hUGit...">
<small class="text-muted"> Token HTTP API của Zalo Bot (lấy từ ứng dụng Bot Creator). Dùng để chatbot tự động gửi tin nhắn phản hồi.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Zalo Webhook Secret Token</label>
<input type="text" name="zalo_webhook_secret" class="form-control" value="{{ $settings['zalo_webhook_secret'] ?? '' }}" placeholder="e.g. your-chosen-secret-key">
<small class="text-muted"> khoá bảo mật tự chọn (điền ô Secret Token trên Zalo Bot Creator). Dùng để xác thực các request gửi từ Zalo về web của bạn an toàn. thể để trống nếu không dùng.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Short Link Domain Override (Public Domain)</label>
<input type="url" name="short_link_domain" class="form-control" value="{{ $settings['short_link_domain'] ?? '' }}" placeholder="https://your-domain.com">
<small class="text-muted">Tên miền công khai của bạn ( dụ: link ngrok hiện tại của bạn: <code>https://c2e9-....ngrok-free.app</code>). Dùng để các link rút gọn gửi đi tên miền click được từ xa. Để trống sẽ dùng mặc định localhost.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Link tham gia Nhóm Zalo (Cộng đồng)</label>
<input type="url" name="zalo_group_join_url" class="form-control" value="{{ $settings['zalo_group_join_url'] ?? '' }}" placeholder="https://zalo.me/g/xxxxxx">
<small class="text-muted">Đường dẫn tham gia nhóm Zalo chia sẻ/hỗ trợ của bạn. Đường dẫn này sẽ hiển thị trang tạo link công khai để người dùng truy cập.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Tỷ lệ hoa hồng ước tính cố định (%)</label>
<input type="number" step="0.1" name="commission_rate_override" class="form-control" value="{{ $settings['commission_rate_override'] ?? '' }}" placeholder="Để trống để tính tự động theo ngành hàng (từ 0.8% đến 7.4%)">
<small class="text-muted">Cấu hình tỷ lệ hoa hồng cố định hiển thị cho người dùng ( dụ: <code>5.0</code> đại diện cho 5%). Để trống hệ thống sẽ tự phân loại thông minh theo ngành hàng loại shop.</small>
</div>
<hr class="my-4">
<div class="mb-3 form-check form-switch">
<input type="checkbox" name="enable_auto_cleanup" id="enable_auto_cleanup" class="form-check-input" value="1" {{ ($settings['enable_auto_cleanup'] ?? '1') === '1' ? 'checked' : '' }}>
<label for="enable_auto_cleanup" class="form-check-label font-weight-bold text-danger">Kích hoạt Tự động dọn dẹp link hết hạn (Countdown)</label>
<div class="small text-muted mt-1">Hệ thống sẽ chạy ngầm hàng ngày để xóa bỏ các link quá hạn dùng nhằm giải phóng sở dữ liệu.</div>
</div>
<div class="card bg-light border-warning shadow-none mb-0">
<div class="card-body mt-0 pt-0 pb-0">
<h6 class="text-warning font-weight-bold mb-2"><i class="bi bi-shield-fill-exclamation me-1"></i> Cách tính Countdown dọn dẹp:</h6>
<ul class="small text-muted ps-3 mb-0">
<li class="mb-1"><strong>Sống bản:</strong> 30 ngày kể từ lúc tạo link.</li>
<li class="mb-1"><strong>Cộng thêm click:</strong> Mỗi 1 click (`clicks`) sẽ được cộng thêm <strong>3 ngày sống</strong>.</li>
<li><strong>Công thức:</strong> <code>Hạn dùng = Ngày tạo + 30 ngày + (Lượt click × 3 ngày)</code>.</li>
</ul>
</div>
</div>
</div>
<div class="card-footer text-end">
<button type="submit" class="btn btn-primary">Save Settings</button>
</div>
</form>
</div>
</div>
<!-- Right Card: Zalo User-Bot Status -->
<div class="col-md-5">
<div class="card card-info card-outline shadow mb-4">
<div class="card-header">
<h3 class="card-title font-weight-bold">Zalo Self-Bot (Tài khoản nhân)</h3>
</div>
<div class="card-body text-center">
@php
$status = $settings['zalo_bot_status'] ?? 'disconnected';
$user = $settings['zalo_bot_user'] ?? '';
@endphp
<div class="mb-4">
<span class="fs-6 d-block mb-2 text-muted">Trạng thái kết nối:</span>
@if($status === 'connected')
<span class="badge text-bg-success px-3 py-2 fs-6"><i class="bi bi-patch-check-fill me-1"></i> ĐÃ KẾT NỐI</span>
<div class="mt-3 font-weight-bold text-success fs-5">
<i class="bi bi-person-circle"></i> {{ $user ?: 'Tài khoản Zalo' }}
</div>
<p class="text-muted small mt-2">Bot đang chạy ngầm lắng nghe tin nhắn từ tài khoản này.</p>
<div class="mt-4">
<form action="{{ route('settings.zalo.stop') }}" method="POST">
@csrf
<button type="submit" class="btn btn-danger btn-sm"><i class="bi bi-stop-fill"></i> Tắt Bot</button>
</form>
</div>
@elseif($status === 'waiting_scan')
<div class="d-flex flex-column align-items-center justify-content-center">
<span class="badge text-bg-warning px-3 py-2 fs-6 text-dark mb-3"><i class="bi bi-qr-code-scan me-1"></i> CHỜ QUÉT QR</span>
<div class="p-3 border rounded bg-white d-inline-flex align-items-center justify-content-center shadow-sm" style="width: 250px; height: 250px; position: relative; min-height: 250px;">
<!-- Loading Spinner -->
<div id="qr-spinner" class="text-center" style="position: absolute; z-index: 1;">
<div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;"></div>
<div class="mt-2 text-muted small font-weight-bold">Đang tạo QR...</div>
</div>
<!-- QR Image (Hidden until loaded) -->
<img id="qr-image" src="/zalo/qr.png?v={{ time() }}" class="img-fluid d-none" style="max-height: 220px; position: absolute; z-index: 2;" alt="Zalo QR Login" onload="document.getElementById('qr-spinner').classList.add('d-none'); this.classList.remove('d-none');" onerror="setTimeout(() => { this.src = '/zalo/qr.png?v=' + Date.now(); }, 2000)">
</div>
</div>
<div class="mt-3 text-start small text-muted px-2">
<i class="bi bi-info-circle-fill text-warning"></i> <strong>Hướng dẫn quét :</strong>
<ol class="mt-1 mb-0 ps-3">
<li>Mở ứng dụng Zalo trên điện thoại (nên dùng nick phụ).</li>
<li>Mở tính năng <b>Quét QR</b> quét ảnh phía trên.</li>
<li>Xác nhận <b>Đăng nhập</b> trên điện thoại của bạn.</li>
</ol>
</div>
<div class="mt-4">
<form action="{{ route('settings.zalo.stop') }}" method="POST">
@csrf
<button type="submit" class="btn btn-secondary btn-sm"><i class="bi bi-stop-fill"></i> Hủy & Tắt Bot</button>
</form>
</div>
@else
<span class="badge text-bg-danger px-3 py-2 fs-6"><i class="bi bi-x-circle-fill me-1"></i> NGẮT KẾT NỐI</span>
<p class="text-muted small mt-3">Tài khoản Zalo nhân hiện chưa được liên kết.</p>
<div class="mt-4">
<form action="{{ route('settings.zalo.start') }}" method="POST">
@csrf
<button type="submit" class="btn btn-success"><i class="bi bi-play-fill"></i> Khởi động Bot Zalo</button>
</form>
</div>
@endif
</div>
@if($status !== 'disconnected')
<hr>
<div class="text-muted small text-start">
<i class="bi bi-lightbulb-fill text-info"></i> Để ngắt kết nối tài khoản hoặc đổi tài khoản khác: bạn hãy nhấn <code>Ctrl + C</code> Terminal chạy bot xóa file <code>zalo-userbot/session.json</code> (nếu ) hoặc đăng xuất phiên web trên app điện thoại.
</div>
@endif
</div>
</div>
</div>
</div>
@endsection
@push('scripts')
<script>
// Auto-poll status from Laravel to refresh page when connection state changes
@if(isset($status) && ($status === 'waiting_scan' || $status === 'connected'))
let currentStatus = '{{ $status }}';
setInterval(() => {
fetch('{{ route('settings.zalo.status_check') }}')
.then(response => response.json())
.then(data => {
if (data.status !== currentStatus) {
window.location.reload();
}
})
.catch(err => console.error("Error checking bot status:", err));
}, 3000);
@endif
</script>
@endpush

View File

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>{{ $history->product_title ?? 'Sản phẩm Shopee' }}</title>
<!-- Open Graph Meta Tags for Zalo / Facebook Link Preview -->
<meta property="og:title" content="{{ $history->product_title ?? 'Sản phẩm Shopee' }}">
<meta property="og:description" content="Giá bán: {{ $history->product_price > 0 ? number_format($history->product_price) . 'đ' : 'Xem chi tiết' }} | Click mua ngay trên Shopee!">
<meta property="og:url" content="{{ request()->url() }}">
@if($history->product_image)
<meta property="og:image" content="{{ $history->product_image }}">
@endif
<meta property="og:type" content="product">
<!-- Fallback Redirect Meta -->
<meta http-equiv="refresh" content="0; url={{ $history->affiliate_url }}">
</head>
<body>
<p>Đang chuyển hướng sang Shopee... Nếu không tự động chuyển hướng, vui lòng <a href="{{ $history->affiliate_url }}">bấm vào đây</a>.</p>
<script>
window.location.href = "{{ $history->affiliate_url }}";
</script>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,245 @@
@extends('layouts.app')
@section('title', 'Quản lý kênh Zalo')
@section('content')
<div class="row">
<!-- Form thêm kênh thủ công -->
<div class="col-md-4">
<div class="card shadow-sm mb-4">
<div class="card-header bg-primary text-white">
<h5 class="card-title mb-0 fs-6"><i class="bi bi-plus-circle me-1"></i> Thêm kênh thủ công</h5>
</div>
<div class="card-body">
<form action="{{ route('zalo_channels.store') }}" method="POST">
@csrf
<div class="mb-3">
<label class="form-label font-weight-bold">Zalo Thread ID (ID Nhóm / ID nhân)</label>
<input type="text" name="thread_id" class="form-control" placeholder="e.g. 7680455978439532859" required>
<small class="text-muted">Nhập ID cuộc trò chuyện lấy từ trang Lịch sử.</small>
</div>
<div class="mb-3">
<label class="form-label font-weight-bold">Tên Kênh gợi nhớ</label>
<input type="text" name="name" class="form-control" placeholder="e.g. Nhóm Săn Deal Shopee">
<small class="text-muted">Đặt tên bất kỳ để bạn dễ phân biệt kênh nào với kênh nào.</small>
</div>
<button type="submit" class="btn btn-primary w-100 font-weight-bold"><i class="bi bi-save me-1"></i> Lưu kênh</button>
</form>
</div>
</div>
<div class="card shadow-sm border-info">
<div class="card-body">
<h6 class="text-info font-weight-bold"><i class="bi bi-info-circle-fill me-1"></i> Cách hoạt động:</h6>
<ul class="small mb-0 text-muted ps-3">
<li class="mb-1"><strong>Chỉ chạy trên Whitelist:</strong> Bot sẽ <strong>CHỈ</strong> phản hồi những cuộc trò chuyện (nhóm hoặc nhân) đã được thêm vào danh sách bên cạnh trạng thái <strong>"Hoạt động"</strong>.</li>
<li><strong>Nếu danh sách trống hoặc bị chặn:</strong> Bot sẽ <strong>KHÔNG phản hồi</strong> bất kỳ tin nhắn nào để đảm bảo an toàn, tránh spam nhóm lạ.</li>
</ul>
</div>
</div>
</div>
<!-- Danh sách các kênh đã lưu -->
<div class="col-md-8">
<div class="card shadow-sm">
<div class="card-header bg-light d-flex justify-content-between align-items-center">
<h5 class="card-title mb-0 fs-6"><i class="bi bi-list-stars me-1"></i> Danh sách kênh được phép chạy Bot</h5>
<button type="button" id="btn-bulk-delete" class="btn btn-danger btn-sm fw-bold shadow-sm d-none" onclick="submitBulkDelete()">
<i class="bi bi-trash-fill"></i> Xóa mục đã chọn (<span id="selected-count">0</span>)
</button>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover align-middle text-nowrap">
<thead>
<tr>
<th style="width: 40px;" class="px-3">
<input type="checkbox" id="select-all" class="form-check-input">
</th>
<th>Tên Kênh</th>
<th>Thread ID</th>
<th>Trạng thái</th>
<th>Ngày thêm</th>
<th class="text-end px-3">Hành động</th>
</tr>
</thead>
<tbody>
@forelse($channels as $channel)
<tr>
<td class="px-3">
<input type="checkbox" value="{{ $channel->id }}" class="form-check-input channel-checkbox">
</td>
<td class="fw-bold text-primary">
<i class="bi bi-chat-dots-fill me-1"></i> {{ $channel->name }}
</td>
<td><code>{{ $channel->thread_id }}</code></td>
<td>
@if($channel->is_allowed)
<span class="badge text-bg-success"><i class="bi bi-check-circle me-1"></i> Hoạt động</span>
@else
<span class="badge text-bg-danger"><i class="bi bi-slash-circle me-1"></i> Đang chặn</span>
@endif
</td>
<td>{{ $channel->created_at->format('H:i d/m/Y') }}</td>
<td class="text-end px-3">
<!-- Toggle block/allow -->
<form action="{{ route('zalo_channels.toggle', $channel->id) }}" method="POST" class="d-inline">
@csrf
@if($channel->is_allowed)
<button type="submit" class="btn btn-outline-warning btn-sm py-1 px-2 border-0" title="Chặn kênh này">
<i class="bi bi-pause-fill"></i> Tạm dừng
</button>
@else
<button type="submit" class="btn btn-outline-success btn-sm py-1 px-2 border-0" title="Cho phép kênh này">
<i class="bi bi-play-fill"></i> Kích hoạt
</button>
@endif
</form>
<!-- Delete -->
<form action="{{ route('zalo_channels.destroy', $channel->id) }}" method="POST" onsubmit="return confirm('Bạn có chắc muốn xóa kênh này?')" class="d-inline">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-outline-danger btn-sm py-1 px-2 border-0" title="Xóa bỏ">
<i class="bi bi-trash"></i>
</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="5" class="text-center py-4 text-muted">Chưa cấu hình giới hạn kênh nào. Bot sẽ KHÔNG phản hồi trên nhóm chat nào!</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@if($channels->hasPages())
<div class="card-footer clearfix bg-light">
{{ $channels->appends(['groups_page' => $discoveredGroups->currentPage()])->links() }}
</div>
@endif
</div>
<!-- Nhóm Zalo đã tham gia (Chưa kích hoạt) -->
<div class="card shadow-sm mt-4">
<div class="card-header bg-light">
<h5 class="card-title mb-0 fs-6"><i class="bi bi-compass me-1"></i> Khám phá nhóm Zalo đã tham gia (Chưa kích hoạt)</h5>
</div>
<div class="card-body table-responsive p-0">
<table class="table table-hover align-middle text-nowrap">
<thead>
<tr>
<th>Tên nhóm</th>
<th>Thread ID</th>
<th class="text-end px-3">Hành động</th>
</tr>
</thead>
<tbody>
@forelse($discoveredGroups as $group)
<tr>
<td class="fw-bold text-secondary">
<i class="bi bi-chat-left-dots me-1"></i> {{ $group->name }}
</td>
<td><code>{{ $group->group_id }}</code></td>
<td class="text-end px-3">
<form action="{{ route('zalo_channels.quick_toggle') }}" method="POST" class="d-inline">
@csrf
<input type="hidden" name="thread_id" value="{{ $group->group_id }}">
<input type="hidden" name="name" value="{{ $group->name }}">
<button type="submit" class="btn btn-sm btn-success px-3 fw-bold text-white shadow-sm">
<i class="bi bi-plus-lg me-1"></i> Cho phép chạy Bot
</button>
</form>
</td>
</tr>
@empty
<tr>
<td colspan="3" class="text-center py-4 text-muted">
Không nhóm chưa kích hoạt nào. Bot sẽ tự động quét danh sách khi bạn kết nối Zalo.
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
@if($discoveredGroups->hasPages())
<div class="card-footer clearfix bg-light">
{{ $discoveredGroups->appends(['channels_page' => $channels->currentPage()])->links() }}
</div>
@endif
</div>
</div>
</div>
<!-- Hidden Form for Bulk Delete -->
<form id="bulk-delete-form" action="{{ route('zalo_channels.bulk_destroy') }}" method="POST" class="d-none">
@csrf
@method('DELETE')
<div id="bulk-delete-inputs"></div>
</form>
@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
const selectAllCheckbox = document.getElementById('select-all');
const channelCheckboxes = document.querySelectorAll('.channel-checkbox');
const btnBulkDelete = document.getElementById('btn-bulk-delete');
const selectedCountText = document.getElementById('selected-count');
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('change', function () {
channelCheckboxes.forEach(cb => {
cb.checked = this.checked;
});
updateBulkDeleteButton();
});
}
channelCheckboxes.forEach(cb => {
cb.addEventListener('change', function () {
if (!this.checked && selectAllCheckbox) {
selectAllCheckbox.checked = false;
} else if (Array.from(channelCheckboxes).every(c => c.checked) && selectAllCheckbox) {
selectAllCheckbox.checked = true;
}
updateBulkDeleteButton();
});
});
function updateBulkDeleteButton() {
const checkedBoxes = document.querySelectorAll('.channel-checkbox:checked');
const count = checkedBoxes.length;
if (count > 0) {
btnBulkDelete.classList.remove('d-none');
selectedCountText.textContent = count;
} else {
btnBulkDelete.classList.add('d-none');
selectedCountText.textContent = '0';
}
}
});
function submitBulkDelete() {
const checkedBoxes = document.querySelectorAll('.channel-checkbox:checked');
if (checkedBoxes.length === 0) return;
if (confirm(`Bạn có chắc chắn muốn xóa ${checkedBoxes.length} kênh Zalo đã chọn khỏi danh sách cho phép chạy Bot?`)) {
const inputsContainer = document.getElementById('bulk-delete-inputs');
inputsContainer.innerHTML = '';
checkedBoxes.forEach(cb => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'ids[]';
input.value = cb.value;
inputsContainer.appendChild(input);
});
document.getElementById('bulk-delete-form').submit();
}
}
</script>
@endpush
@endsection

14
routes/api.php Normal file
View File

@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\ConvertApiController;
use App\Http\Controllers\Api\ZaloWebhookController;
Route::post('/convert', [ConvertApiController::class, 'convert']);
Route::get('/history', [ConvertApiController::class, 'history']);
// Zalo Webhook
Route::post('/zalo/webhook', [ZaloWebhookController::class, 'handle']);
Route::post('/zalo/process-link', [ZaloWebhookController::class, 'processLink']);
Route::post('/zalo/status', [ZaloWebhookController::class, 'updateStatus']);
Route::post('/zalo/sync-groups', [ZaloWebhookController::class, 'syncGroups']);

11
routes/console.php Normal file
View File

@ -0,0 +1,11 @@
<?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
Schedule::command('app:cleanup-expired-links')->daily();

64
routes/web.php Normal file
View File

@ -0,0 +1,64 @@
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Web\DashboardController;
use App\Http\Controllers\Web\ConvertController;
use App\Http\Controllers\Web\HistoryController;
use App\Http\Controllers\Web\SettingController;
use App\Http\Controllers\Web\ShortLinkController;
use App\Http\Controllers\Web\Auth\LoginController;
use App\Http\Controllers\Web\ZaloChannelController;
use App\Http\Controllers\Web\PublicConvertController;
use App\Http\Controllers\Web\CustomerLookupController;
// Public Redirect Route
Route::get('/aff/s/{code}', [ShortLinkController::class, 'redirect'])->name('short_link.redirect');
// Public Link Generator
Route::get('/aff/taolink', [PublicConvertController::class, 'index'])->name('public_convert.index');
Route::post('/aff/taolink', [PublicConvertController::class, 'process'])->middleware('throttle:10,1')->name('public_convert.process');
// Customer Lookup Portal
Route::get('/aff/tra-cuu', [CustomerLookupController::class, 'index'])->name('customer_lookup.index');
Route::get('/aff/tra-cuu/search', [CustomerLookupController::class, 'search'])->name('customer_lookup.search');
// Root Redirect
Route::get('/', function () {
return redirect()->route('public_convert.index');
});
// Backend Routes (prefix: aff/shp/admin)
Route::prefix('aff/shp/admin')->group(function () {
// Auth Routes
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/register-admin', [LoginController::class, 'registerAdmin'])->name('register.admin');
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');
// Protected Routes
Route::middleware(['auth'])->group(function () {
Route::get('/', [DashboardController::class, 'index'])->name('dashboard');
// History
Route::get('/history', [HistoryController::class, 'index'])->name('history.index');
Route::delete('/history/bulk-destroy', [HistoryController::class, 'bulkDestroy'])->name('history.bulk_destroy');
Route::delete('/history/{id}', [HistoryController::class, 'destroy'])->name('history.destroy');
// Settings
Route::get('/settings', [SettingController::class, 'index'])->name('settings.index');
Route::post('/settings', [SettingController::class, 'update'])->name('settings.update');
Route::post('/settings/zalo/start', [SettingController::class, 'startBot'])->name('settings.zalo.start');
Route::post('/settings/zalo/stop', [SettingController::class, 'stopBot'])->name('settings.zalo.stop');
Route::get('/settings/zalo/status-check', [SettingController::class, 'checkBotStatus'])->name('settings.zalo.status_check');
// Zalo Channels Manager
Route::get('/zalo-channels', [ZaloChannelController::class, 'index'])->name('zalo_channels.index');
Route::post('/zalo-channels', [ZaloChannelController::class, 'store'])->name('zalo_channels.store');
Route::post('/zalo-channels/{id}/toggle', [ZaloChannelController::class, 'toggle'])->name('zalo_channels.toggle');
Route::post('/zalo-channels/quick-toggle', [ZaloChannelController::class, 'quickToggle'])->name('zalo_channels.quick_toggle');
Route::delete('/zalo-channels/bulk-destroy', [ZaloChannelController::class, 'bulkDestroy'])->name('zalo_channels.bulk_destroy');
Route::delete('/zalo-channels/{id}', [ZaloChannelController::class, 'destroy'])->name('zalo_channels.destroy');
});
});

4
storage/app/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*
!private/
!public/
!.gitignore

2
storage/app/private/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/app/public/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

9
storage/framework/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
compiled.php
config.php
down
events.scanned.php
maintenance.php
routes.php
routes.scanned.php
schedule-*
services.json

3
storage/framework/cache/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
*
!data/
!.gitignore

View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/sessions/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/testing/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/framework/views/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

2
storage/logs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*
!.gitignore

View File

@ -0,0 +1,19 @@
<?php
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

10
tests/TestCase.php Normal file
View File

@ -0,0 +1,10 @@
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
//
}

View File

@ -0,0 +1,16 @@
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_that_true_is_true(): void
{
$this->assertTrue(true);
}
}

18
vite.config.js Normal file
View File

@ -0,0 +1,18 @@
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
tailwindcss(),
],
server: {
watch: {
ignored: ['**/storage/framework/views/**'],
},
},
});

0
zalo-userbot/bot.log Normal file
View File

1
zalo-userbot/bot.pid Normal file
View File

@ -0,0 +1 @@
15988

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