1) user invitation 2) app access control 3) txn quota guard
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$reports = new FinancialReports($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$reports = new FinancialReports($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$reports = new FinancialReports($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$limit = max(1, min(50, (int)($data['limit'] ?? 10)));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$months = max(1, min(24, (int)($data['months'] ?? 6)));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$as_of_date = trim((string)($data['as_of_date'] ?? ($data['as_of_period'] ?? date('Y-m-d'))));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$account_code = trim((string)($data['account_code'] ?? ''));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$from_date = trim((string)($data['from_date'] ?? ($data['from_period'] ?? date('Y-m-d'))));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes_ac/FinancialReports.php';
|
||||
|
||||
$from_date = trim((string)($data['from_date'] ?? ($data['from_period'] ?? date('Y-m-d'))));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes_ac/TaxReportManager.php';
|
||||
|
||||
$from_date = trim((string)($data['from_date'] ?? ($data['from_period'] ?? date('Y-m-d'))));
|
||||
|
||||
@@ -820,6 +820,20 @@ function ajax_request(options) {
|
||||
throw xhr;
|
||||
}
|
||||
|
||||
// Usage limit reached — show upgrade notice instead of generic error
|
||||
if (xhr?.status === 402) {
|
||||
const d = xhr?.responseJSON ?? {};
|
||||
const daily = d.daily_limit > 0 ? `Daily: <strong>${d.daily_count} / ${d.daily_limit}</strong>` : null;
|
||||
const weekly = d.weekly_limit > 0 ? `Weekly: <strong>${d.weekly_count} / ${d.weekly_limit}</strong>` : null;
|
||||
const detail = [daily, weekly].filter(Boolean).join(' | ');
|
||||
bootbox.alert(
|
||||
`<strong>Usage limit reached.</strong><br>${detail}<br><br>` +
|
||||
`Reports are locked until the quota resets. Upgrade your package for higher limits.`
|
||||
);
|
||||
options.onError?.(xhr, 'limit_reached');
|
||||
throw xhr;
|
||||
}
|
||||
|
||||
// Extract server's error message from JSON response
|
||||
let serverMessage = xhr?.responseJSON?.message;
|
||||
|
||||
|
||||
@@ -149,6 +149,16 @@ class ContactManager {
|
||||
public function saveContactType(array $data, array $logging): void
|
||||
{
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
$name = (string)($data['contact_type'] ?? '');
|
||||
|
||||
$dupSth = $this->pdo->prepare(
|
||||
"SELECT id FROM md_contact_type
|
||||
WHERE company_id = :cid AND contact_type = :name" . ($id > 0 ? " AND id != :id" : "") . " LIMIT 1"
|
||||
);
|
||||
$dupParams = [':cid' => $this->company_id, ':name' => $name];
|
||||
if ($id > 0) $dupParams[':id'] = $id;
|
||||
$dupSth->execute($dupParams);
|
||||
if ($dupSth->fetchColumn()) throw new Exception("A contact type with this name already exists.");
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT `log` FROM md_contact_type
|
||||
|
||||
@@ -155,6 +155,16 @@ class ProductManager {
|
||||
public function saveCategory(array $data, array $logging): void
|
||||
{
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
$slug = (string)($data['slug'] ?? '');
|
||||
|
||||
$dupSth = $this->pdo->prepare(
|
||||
"SELECT id FROM md_product_category
|
||||
WHERE company_id = :cid AND slug = :slug" . ($id > 0 ? " AND id != :id" : "") . " LIMIT 1"
|
||||
);
|
||||
$dupParams = [':cid' => $this->company_id, ':slug' => $slug];
|
||||
if ($id > 0) $dupParams[':id'] = $id;
|
||||
$dupSth->execute($dupParams);
|
||||
if ($dupSth->fetchColumn()) throw new Exception("A category with this slug already exists.");
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT `log` FROM md_product_category
|
||||
@@ -356,6 +366,16 @@ class ProductManager {
|
||||
public function saveProduct(array $data, array $logging, string $product_image): void
|
||||
{
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
$sku = (string)($data['sku'] ?? '');
|
||||
|
||||
$dupSth = $this->pdo->prepare(
|
||||
"SELECT id FROM md_product
|
||||
WHERE company_id = :cid AND sku = :sku" . ($id > 0 ? " AND id != :id" : "") . " LIMIT 1"
|
||||
);
|
||||
$dupParams = [':cid' => $this->company_id, ':sku' => $sku];
|
||||
if ($id > 0) $dupParams[':id'] = $id;
|
||||
$dupSth->execute($dupParams);
|
||||
if ($dupSth->fetchColumn()) throw new Exception("A product with this SKU already exists.");
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT `log` FROM md_product
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
class UsageGuard {
|
||||
|
||||
private PDO $pdo;
|
||||
private int $company_id;
|
||||
private array $pkg;
|
||||
|
||||
public function __construct(PDO $pdo1, int $company_id, array $packages) {
|
||||
$this->pdo = $pdo1;
|
||||
$this->company_id = $company_id;
|
||||
$this->pkg = $this->resolvePackage($packages);
|
||||
}
|
||||
|
||||
private function resolvePackage(array $packages): array {
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT package FROM company_list WHERE company_id = :cid LIMIT 1"
|
||||
);
|
||||
$sth->execute([':cid' => $this->company_id]);
|
||||
$name = $sth->fetchColumn() ?: 'starter';
|
||||
return $packages[$name] ?? $packages['starter'] ?? [
|
||||
'daily_limit' => 30,
|
||||
'weekly_limit' => 100,
|
||||
'lock_on_limit' => ['dashboard'],
|
||||
];
|
||||
}
|
||||
|
||||
public function increment(): void {
|
||||
$today = date('Y-m-d');
|
||||
$this->pdo->prepare(
|
||||
"INSERT INTO company_usage (company_id, day_date, daily_count)
|
||||
VALUES (:cid, :today, 1)
|
||||
ON DUPLICATE KEY UPDATE daily_count = daily_count + 1"
|
||||
)->execute([':cid' => $this->company_id, ':today' => $today]);
|
||||
}
|
||||
|
||||
public function assertFeatureAccessible(string $feature): void {
|
||||
$lock_on = $this->pkg['lock_on_limit'] ?? [];
|
||||
if (!in_array($feature, $lock_on, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$status = $this->getStatus();
|
||||
$daily_limit = (int)($this->pkg['daily_limit'] ?? 0);
|
||||
$weekly_limit = (int)($this->pkg['weekly_limit'] ?? 0);
|
||||
|
||||
$over_daily = $daily_limit > 0 && $status['daily_count'] >= $daily_limit;
|
||||
$over_weekly = $weekly_limit > 0 && $status['weekly_count'] >= $weekly_limit;
|
||||
|
||||
if ($over_daily || $over_weekly) {
|
||||
http_response_code(402);
|
||||
exit(json_encode([
|
||||
'success' => 0,
|
||||
'message' => 'Usage limit reached. Upgrade your package to access reports.',
|
||||
'limit_reached' => true,
|
||||
'daily_count' => $status['daily_count'],
|
||||
'daily_limit' => $status['daily_limit'],
|
||||
'weekly_count' => $status['weekly_count'],
|
||||
'weekly_limit' => $status['weekly_limit'],
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
public function getStatus(): array {
|
||||
$today = date('Y-m-d');
|
||||
$day_of_week = (int)date('N');
|
||||
$week_start = date('Y-m-d', strtotime('-' . ($day_of_week - 1) . ' days'));
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT daily_count FROM company_usage
|
||||
WHERE company_id = :cid AND day_date = :today LIMIT 1"
|
||||
);
|
||||
$sth->execute([':cid' => $this->company_id, ':today' => $today]);
|
||||
$daily_count = (int)($sth->fetchColumn() ?: 0);
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT COALESCE(SUM(daily_count), 0) FROM company_usage
|
||||
WHERE company_id = :cid AND day_date BETWEEN :wstart AND :today"
|
||||
);
|
||||
$sth->execute([
|
||||
':cid' => $this->company_id,
|
||||
':wstart'=> $week_start,
|
||||
':today' => $today,
|
||||
]);
|
||||
$weekly_count = (int)$sth->fetchColumn();
|
||||
|
||||
$daily_limit = (int)($this->pkg['daily_limit'] ?? 0);
|
||||
$weekly_limit = (int)($this->pkg['weekly_limit'] ?? 0);
|
||||
|
||||
return [
|
||||
'daily_count' => $daily_count,
|
||||
'weekly_count' => $weekly_count,
|
||||
'daily_limit' => $daily_limit,
|
||||
'weekly_limit' => $weekly_limit,
|
||||
'daily_pct' => $daily_limit > 0 ? min(100, (int)round($daily_count / $daily_limit * 100)) : 0,
|
||||
'weekly_pct' => $weekly_limit > 0 ? min(100, (int)round($weekly_count / $weekly_limit * 100)) : 0,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -118,9 +118,10 @@ class UserManager {
|
||||
public function getCompanyAccess(int $company_id): ?array
|
||||
{
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT company_id, role
|
||||
FROM company_map_user
|
||||
WHERE company_id = :company_id AND user_id = :user_id
|
||||
"SELECT m.company_id, m.role, m.app_access, u.license, u.app_access AS user_app_access
|
||||
FROM company_map_user m
|
||||
JOIN user u ON u.user_id = m.user_id
|
||||
WHERE m.company_id = :company_id AND m.user_id = :user_id
|
||||
LIMIT 1"
|
||||
);
|
||||
$sth->execute([':company_id' => $company_id, ':user_id' => $this->user_id]);
|
||||
@@ -146,13 +147,16 @@ class UserManager {
|
||||
"SELECT
|
||||
m.map_id,
|
||||
m.role,
|
||||
CASE WHEN u.license = 'owner' THEN u.app_access ELSE m.app_access END AS app_access,
|
||||
m.created_at,
|
||||
u.user_id,
|
||||
u.username,
|
||||
u.name,
|
||||
u.surname,
|
||||
u.email,
|
||||
u.profile_picture
|
||||
u.profile_picture,
|
||||
u.status,
|
||||
(m.invite_token IS NOT NULL) AS is_pending_invite
|
||||
FROM company_map_user m
|
||||
JOIN user u ON u.user_id = m.user_id
|
||||
WHERE m.company_id = :company_id
|
||||
@@ -194,17 +198,18 @@ class UserManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a registered user to the current company by email.
|
||||
* Add a user to the current company by email.
|
||||
*
|
||||
* Validates email format, role, and that the target account exists.
|
||||
* Blocks inviting self or someone already mapped to the company.
|
||||
* If the email is already registered: maps them to this company directly.
|
||||
* If the email is not registered: creates a pending account (license='user',
|
||||
* default_company = this company) and returns an invite token so the caller
|
||||
* can email them a link to invited_onboarding.php to complete registration.
|
||||
* The invited user inherits this company's SMTP for OTP login.
|
||||
*
|
||||
* @param string $email Email address of the user to invite.
|
||||
* @param string $role Role to assign: 'admin', 'staff', or 'viewer'.
|
||||
* @return string The invited user's email, for use in the success message.
|
||||
* @return array ['new_user' => bool, 'email' => string, 'token' => string|null]
|
||||
* @throws Exception On any validation or constraint failure.
|
||||
*/
|
||||
public function inviteUser(string $email, string $role): string {
|
||||
public function inviteUser(string $email, string $role, string $app_access): array {
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
throw new Exception('Invalid email address.');
|
||||
}
|
||||
@@ -220,10 +225,7 @@ class UserManager {
|
||||
$sth->execute([':email' => $email]);
|
||||
$target = $sth->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$target) {
|
||||
throw new Exception('No registered account found with that email address.');
|
||||
}
|
||||
|
||||
if ($target) {
|
||||
$target_user_id = (int)$target['user_id'];
|
||||
|
||||
if ($target_user_id === $this->user_id) {
|
||||
@@ -241,15 +243,96 @@ class UserManager {
|
||||
}
|
||||
|
||||
$this->pdo->prepare(
|
||||
"INSERT INTO company_map_user (company_id, user_id, role, created_at)
|
||||
VALUES (:company_id, :user_id, :role, NOW())"
|
||||
"INSERT INTO company_map_user (company_id, user_id, role, app_access, created_at)
|
||||
VALUES (:company_id, :user_id, :role, :app_access, NOW())"
|
||||
)->execute([
|
||||
':company_id' => $this->company_id,
|
||||
':user_id' => $target_user_id,
|
||||
':role' => $role,
|
||||
':app_access' => $app_access,
|
||||
]);
|
||||
|
||||
return $target['email'];
|
||||
return ['new_user' => false, 'email' => $target['email'], 'token' => null];
|
||||
}
|
||||
|
||||
// Email not in system — create a pending invited account
|
||||
$invite_token = bin2hex(random_bytes(32));
|
||||
$expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
|
||||
$temp_username = 'invited_' . bin2hex(random_bytes(8));
|
||||
|
||||
$this->pdo->prepare(
|
||||
"INSERT INTO user
|
||||
(username, name, surname, email, password, status, license, default_company,
|
||||
profile_picture, verify_token, verify_expires_at)
|
||||
VALUES
|
||||
(:username, '', '', :email, '', 'pending', 'user', :default_company,
|
||||
'', :token, :expires)"
|
||||
)->execute([
|
||||
':username' => $temp_username,
|
||||
':email' => $email,
|
||||
':default_company' => $this->company_id,
|
||||
':token' => $invite_token,
|
||||
':expires' => $expires_at,
|
||||
]);
|
||||
$new_user_id = (int)$this->pdo->lastInsertId();
|
||||
|
||||
$this->pdo->prepare(
|
||||
"INSERT INTO company_map_user (company_id, user_id, role, app_access, invite_token, created_at)
|
||||
VALUES (:company_id, :user_id, :role, :app_access, :token, NOW())"
|
||||
)->execute([
|
||||
':company_id' => $this->company_id,
|
||||
':user_id' => $new_user_id,
|
||||
':role' => $role,
|
||||
':app_access' => $app_access,
|
||||
':token' => $invite_token,
|
||||
]);
|
||||
|
||||
return ['new_user' => true, 'email' => $email, 'token' => $invite_token];
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate an invite token for a pending invited user and return it.
|
||||
*
|
||||
* Only works on license='user' + status='pending' accounts that still have
|
||||
* an invite_token in company_map_user. Owner-pending accounts (mid-onboarding)
|
||||
* are never touched.
|
||||
*
|
||||
* @param int $map_id The company_map_user.map_id of the pending member.
|
||||
* @return array ['email' => string, 'token' => string]
|
||||
* @throws Exception If the member is not found or is not a pending invite.
|
||||
*/
|
||||
public function resendInvite(int $map_id): array {
|
||||
if (!$map_id) throw new Exception('Invalid request.');
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT u.user_id, u.email, u.status, u.license, m.invite_token
|
||||
FROM company_map_user m
|
||||
JOIN user u ON u.user_id = m.user_id
|
||||
WHERE m.map_id = :map_id AND m.company_id = :company_id
|
||||
LIMIT 1"
|
||||
);
|
||||
$sth->execute([':map_id' => $map_id, ':company_id' => $this->company_id]);
|
||||
$row = $sth->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$row) throw new Exception('User not found.');
|
||||
if ($row['license'] !== 'user') throw new Exception('Cannot resend invite to an owner account.');
|
||||
if ($row['status'] !== 'pending') throw new Exception('User has already accepted the invitation.');
|
||||
if (!$row['invite_token']) throw new Exception('No pending invitation found for this user.');
|
||||
|
||||
$new_token = bin2hex(random_bytes(32));
|
||||
$expires_at = date('Y-m-d H:i:s', strtotime('+7 days'));
|
||||
|
||||
$this->pdo->prepare(
|
||||
"UPDATE user SET verify_token = :token, verify_expires_at = :expires
|
||||
WHERE user_id = :uid"
|
||||
)->execute([':token' => $new_token, ':expires' => $expires_at, ':uid' => (int)$row['user_id']]);
|
||||
|
||||
$this->pdo->prepare(
|
||||
"UPDATE company_map_user SET invite_token = :token
|
||||
WHERE map_id = :map_id AND company_id = :company_id"
|
||||
)->execute([':token' => $new_token, ':map_id' => $map_id, ':company_id' => $this->company_id]);
|
||||
|
||||
return ['email' => $row['email'], 'token' => $new_token];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -290,6 +373,45 @@ class UserManager {
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the app_access of a non-owner company member.
|
||||
*
|
||||
* Owner's app_access is managed via user.app_access (their license); it
|
||||
* cannot be changed here. Caller must have already validated the value is
|
||||
* within the owner's license.
|
||||
*
|
||||
* @param int $map_id The company_map_user.map_id to update.
|
||||
* @param string $app_access New value: 'wms', 'accounting', or 'all'.
|
||||
* @throws Exception If the member is not found or is the owner.
|
||||
*/
|
||||
public function updateAppAccess(int $map_id, string $app_access): void {
|
||||
if (!$map_id || $app_access === '') {
|
||||
throw new Exception('Invalid request.');
|
||||
}
|
||||
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT u.license FROM company_map_user m
|
||||
JOIN user u ON u.user_id = m.user_id
|
||||
WHERE m.map_id = :map_id AND m.company_id = :company_id
|
||||
LIMIT 1"
|
||||
);
|
||||
$sth->execute([':map_id' => $map_id, ':company_id' => $this->company_id]);
|
||||
$license = $sth->fetchColumn();
|
||||
|
||||
if ($license === false) throw new Exception('User not found.');
|
||||
if ($license === 'owner') throw new Exception('Owner app access is determined by their license.');
|
||||
|
||||
$this->pdo->prepare(
|
||||
"UPDATE company_map_user
|
||||
SET app_access = :app_access
|
||||
WHERE map_id = :map_id AND company_id = :company_id"
|
||||
)->execute([
|
||||
':app_access' => $app_access,
|
||||
':map_id' => $map_id,
|
||||
':company_id' => $this->company_id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a user from the current company.
|
||||
*
|
||||
@@ -318,5 +440,17 @@ class UserManager {
|
||||
"DELETE FROM company_map_user
|
||||
WHERE map_id = :map_id AND company_id = :company_id"
|
||||
)->execute([':map_id' => $map_id, ':company_id' => $this->company_id]);
|
||||
|
||||
// If this was a pending invited account that was never activated, delete
|
||||
// the placeholder user row so the email is free for future invitations.
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT license, status FROM user WHERE user_id = :uid LIMIT 1"
|
||||
);
|
||||
$sth->execute([':uid' => (int)$row['user_id']]);
|
||||
$u = $sth->fetch(PDO::FETCH_ASSOC);
|
||||
if ($u && $u['license'] === 'user' && $u['status'] === 'pending') {
|
||||
$this->pdo->prepare("DELETE FROM user WHERE user_id = :uid")
|
||||
->execute([':uid' => (int)$row['user_id']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* Lifecycle:
|
||||
* post() — first-time GL creation; throws if a record already exists.
|
||||
* replace() — snapshot current lines into td_gl.history, then delete + re-insert.
|
||||
* delete() — hard-delete both td_gl and all its td_gl_item rows (used on void).
|
||||
* delete() — create a reversal journal entry (audit trail), then hard-delete the original.
|
||||
*/
|
||||
class GlManager
|
||||
{
|
||||
@@ -213,7 +213,8 @@ class GlManager
|
||||
public function delete(string $source_type, int $source_id): void
|
||||
{
|
||||
$sth = $this->pdo->prepare(
|
||||
"SELECT id, journal_date, period FROM td_gl
|
||||
"SELECT id, reference, description, journal_date, period, formula_id
|
||||
FROM td_gl
|
||||
WHERE company_id = :cid
|
||||
AND source_type = :source_type
|
||||
AND source_id = :source_id
|
||||
@@ -229,7 +230,40 @@ class GlManager
|
||||
if (!$gl_id) return;
|
||||
|
||||
$journal_date = $this->resolveJournalDate($gl['journal_date'] ?? null, (string)($gl['period'] ?? ''));
|
||||
$this->assertPostingWindow($journal_date, 'GL posting deletion');
|
||||
$this->assertPostingWindow($journal_date, 'GL void');
|
||||
|
||||
$original_lines = $this->getLines($gl_id);
|
||||
|
||||
if (!empty($original_lines)) {
|
||||
$reversal_lines = array_map(fn($line) => [
|
||||
'account_code' => $line['account_code'],
|
||||
'department_id' => (int)$line['department_id'],
|
||||
'debit' => (float)$line['credit'],
|
||||
'credit' => (float)$line['debit'],
|
||||
'description' => 'VOID: ' . $line['description'],
|
||||
], $original_lines);
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$this->pdo->prepare(
|
||||
"INSERT INTO td_gl
|
||||
(company_id, source_type, source_id, reference, description, journal_date,
|
||||
formula_id, period, current_version, history, created_at, updated_at)
|
||||
VALUES
|
||||
(:cid, 'reversal', :source_id, :reference, :description, :journal_date,
|
||||
:formula_id, :period, 1, '[]', :created_at, :updated_at)"
|
||||
)->execute([
|
||||
':cid' => $this->companyId,
|
||||
':source_id' => $gl_id,
|
||||
':reference' => 'VOID/' . ($gl['reference'] ?? ''),
|
||||
':description' => 'Void: ' . ($gl['description'] ?? ''),
|
||||
':journal_date' => $journal_date,
|
||||
':formula_id' => (int)($gl['formula_id'] ?? 0),
|
||||
':period' => $gl['period'] ?? '',
|
||||
':created_at' => $now,
|
||||
':updated_at' => $now,
|
||||
]);
|
||||
$this->insertLines((int)$this->pdo->lastInsertId(), $reversal_lines);
|
||||
}
|
||||
|
||||
$this->pdo->prepare(
|
||||
"DELETE FROM td_gl_item WHERE company_id = :cid AND gl_id = :gl_id"
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('dashboard');
|
||||
|
||||
$report = new ReportManager($pdo2, $company_id);
|
||||
|
||||
$answer['output'] = array_merge(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/PaymentManager.php';
|
||||
|
||||
try {
|
||||
@@ -50,6 +51,7 @@
|
||||
$answer['success'] = 1;
|
||||
$answer['new_id'] = $new_id;
|
||||
$answer['message'] = 'Payment posted.';
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/ReceiptManager.php';
|
||||
|
||||
try {
|
||||
@@ -50,6 +51,7 @@
|
||||
$answer['success'] = 1;
|
||||
$answer['new_id'] = $new_id;
|
||||
$answer['message'] = 'Receipt posted.';
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
|
||||
@@ -29,6 +30,7 @@
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['auto_approved'] = $auto_approve;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$answer['success'] = 0;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
|
||||
@@ -29,6 +30,7 @@
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['auto_approved'] = $auto_approve;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$answer['success'] = 0;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
|
||||
@@ -30,6 +31,7 @@
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['auto_approved'] = $auto_approve;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$answer['success'] = 0;
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<footer class="text-center py-2 mt-6 text-secondary ">
|
||||
<p class="mb-0">Copyright © 2026 MN3WMS. Developed by <a href="https://codescandy.com/"
|
||||
target="_blank" class="text-primary">TR3</a> </p>
|
||||
<p class="mb-0">Copyright © 2026 MN3 WMS. All rights reserved.</p>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Stock rows modal (shared across all list pages) -->
|
||||
<!-- Stock rows modal — used by: order/order.php, order/return.php, po/po.php, po/supplier_returns.php (via show_stock_rows() in custom.js) -->
|
||||
<div class="modal fade" id="stock_rows_modal" tabindex="-1">
|
||||
<div class="modal-dialog modal-lg modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/config.php';
|
||||
require_once __DIR__ . '/dbconn.php';
|
||||
require_once __DIR__ . '/assets/utils/classes/UsageGuard.php';
|
||||
|
||||
// Redirect to login if the user has not completed full authentication.
|
||||
// login_company_id is only written by login_confirm.php after OTP is verified —
|
||||
// using it (not "otp") ensures half-logged-in sessions are also redirected.
|
||||
@@ -47,6 +51,11 @@ if (empty($_SESSION['login_current_app'])) {
|
||||
|
||||
$topbar_show_wms = in_array($topbar_app_access, ['all', 'wms']);
|
||||
$topbar_show_accounting = in_array($topbar_app_access, ['all', 'accounting']);
|
||||
|
||||
$_usage = (new UsageGuard($pdo1, (int)$_SESSION['login_company_id'], $packages))->getStatus();
|
||||
$_usage_max_pct = max($_usage['daily_pct'], $_usage['weekly_pct']);
|
||||
$_usage_warn = $_usage_max_pct >= 80 && $_usage_max_pct < 100;
|
||||
$_usage_full = $_usage_max_pct >= 100;
|
||||
?>
|
||||
|
||||
<?php if (($_SESSION['login_current_app'] ?? 'wms') === 'accounting'): ?>
|
||||
@@ -183,6 +192,22 @@ $topbar_show_accounting = in_array($topbar_app_access, ['all', 'accounting']);
|
||||
</li>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- Usage limit warning -->
|
||||
<?php if ($_usage_full || $_usage_warn): ?>
|
||||
<li>
|
||||
<span class="badge <?php echo $_usage_full ? 'bg-danger' : 'bg-warning text-dark'; ?> d-flex align-items-center gap-1 px-2 py-1"
|
||||
style="font-size:11px; cursor:default;"
|
||||
title="Daily: <?php echo $_usage['daily_count']; ?>/<?php echo $_usage['daily_limit'] ?: '∞'; ?> | Weekly: <?php echo $_usage['weekly_count']; ?>/<?php echo $_usage['weekly_limit'] ?: '∞'; ?>">
|
||||
<i class="ti <?php echo $_usage_full ? 'ti-circle-x' : 'ti-alert-triangle'; ?>"></i>
|
||||
<?php if ($_usage_full): ?>
|
||||
Limit reached — reports locked
|
||||
<?php else: ?>
|
||||
<?php echo $_usage_max_pct; ?>% usage
|
||||
<?php endif; ?>
|
||||
</span>
|
||||
</li>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- User dropdown -->
|
||||
<li class="ms-3 dropdown">
|
||||
<a class="position-relative btn-icon btn-sm btn-primary btn rounded-circle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
require_role($user_role, ['owner', 'admin']);
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
/**
|
||||
* invited_onboarding.php — Complete account setup for an invited user.
|
||||
*
|
||||
* Called by: invited_onboarding.php page AJAX after the user fills in
|
||||
* their name, username, and password.
|
||||
*
|
||||
* The invited user was created with license='user', status='pending', and
|
||||
* default_company = the inviting company. This endpoint activates the account
|
||||
* so they can log in using the inviting company's SMTP for OTP delivery.
|
||||
*
|
||||
* Full flow:
|
||||
* 1. Session guard — rejects if 'invited_user_id' is missing.
|
||||
* 2. CSRF check.
|
||||
* 3. Re-validate token against DB (expiry + status='pending' + license='user').
|
||||
* 4. Validate and sanitise input fields.
|
||||
* 5. Username format and uniqueness check.
|
||||
* 6. Password match and strength check.
|
||||
* 7. Hash password.
|
||||
* 8. UPDATE user: name, surname, username, password, status='active',
|
||||
* verify_token=NULL, verify_expires_at=NULL.
|
||||
* 9. UPDATE company_map_user: invite_token=NULL.
|
||||
* 10. Return { success: 1 }.
|
||||
*/
|
||||
|
||||
require '../../session.php';
|
||||
require '../../config.php';
|
||||
require '../../preset.php';
|
||||
define('UNAUTHENTICATED_ROUTE', true);
|
||||
require '../../assets/utils/db_auth.php';
|
||||
require '../../assets/utils/classes/PasswordManager.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
$answer = ['success' => 0, 'message' => ''];
|
||||
|
||||
// ── Step 1: Session guard ─────────────────────────────────────────────────────
|
||||
if (empty($_SESSION['invited_user_id']) || empty($_SESSION['invited_token'])) {
|
||||
$answer['message'] = 'Invalid session. Please use your invitation link.';
|
||||
http_response_code(403);
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
|
||||
$user_id = (int)$_SESSION['invited_user_id'];
|
||||
$token = $_SESSION['invited_token'];
|
||||
|
||||
// ── Step 2: CSRF check ────────────────────────────────────────────────────────
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$csrf = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
|
||||
if (empty($csrf) || $csrf !== ($_SESSION['csrf_token'] ?? '')) {
|
||||
http_response_code(403);
|
||||
$answer['message'] = 'Invalid request.';
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
}
|
||||
|
||||
$data = json_decode($_POST['json'] ?? '{}', true) ?: [];
|
||||
|
||||
try {
|
||||
|
||||
// ── Step 3: Re-validate token ─────────────────────────────────────────────
|
||||
$sth = $pdo1->prepare(
|
||||
"SELECT user_id FROM user
|
||||
WHERE user_id = :uid
|
||||
AND verify_token = :token
|
||||
AND status = 'pending'
|
||||
AND license = 'user'
|
||||
AND verify_expires_at > NOW()
|
||||
LIMIT 1"
|
||||
);
|
||||
$sth->execute([':uid' => $user_id, ':token' => $token]);
|
||||
if (!$sth->fetchColumn()) {
|
||||
$answer['message'] = 'Invitation has expired or already been used. Please request a new invitation.';
|
||||
http_response_code(403);
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
|
||||
// ── Step 4: Sanitise and validate input ───────────────────────────────────
|
||||
$name = trim($data['name'] ?? '');
|
||||
$surname = trim($data['surname'] ?? '');
|
||||
$username = strtolower(trim($data['username'] ?? ''));
|
||||
$password = $data['password'] ?? '';
|
||||
$confirm = $data['confirm_password'] ?? '';
|
||||
|
||||
if (!$name || !$surname || !$username || !$password || !$confirm) {
|
||||
throw new Exception('All fields are required.');
|
||||
}
|
||||
|
||||
// ── Step 5: Username format and uniqueness ────────────────────────────────
|
||||
if (!preg_match('/^[a-z0-9_]+$/', $username)) {
|
||||
throw new Exception('Username may only contain lowercase letters, numbers and underscores.');
|
||||
}
|
||||
|
||||
$sth = $pdo1->prepare("SELECT user_id FROM user WHERE username = :u AND user_id != :uid LIMIT 1");
|
||||
$sth->execute([':u' => $username, ':uid' => $user_id]);
|
||||
if ($sth->fetchColumn()) {
|
||||
throw new Exception('Username is already taken. Please choose another.');
|
||||
}
|
||||
|
||||
// ── Step 6: Password match and strength ───────────────────────────────────
|
||||
if ($password !== $confirm) {
|
||||
throw new Exception('Passwords do not match.');
|
||||
}
|
||||
|
||||
$pm = new PasswordManager($pdo1, $include_url);
|
||||
$result = $pm->checkStrength($password, [$name, $surname, $username]);
|
||||
if ($result['score'] < PasswordManager::MIN_SCORE) {
|
||||
$msg = $result['warning'] ?: ($result['suggestions'][0] ?? 'Please choose a stronger password.');
|
||||
throw new Exception('Password is too weak. ' . $msg);
|
||||
}
|
||||
|
||||
// ── Step 7–8: Hash and activate account ──────────────────────────────────
|
||||
$hashed = password_hash($password, PASSWORD_BCRYPT);
|
||||
|
||||
$pdo1->prepare(
|
||||
"UPDATE user
|
||||
SET name = :name,
|
||||
surname = :surname,
|
||||
username = :username,
|
||||
password = :password,
|
||||
status = 'active',
|
||||
verify_token = NULL,
|
||||
verify_expires_at = NULL
|
||||
WHERE user_id = :uid"
|
||||
)->execute([
|
||||
':name' => $name,
|
||||
':surname' => $surname,
|
||||
':username' => $username,
|
||||
':password' => $hashed,
|
||||
':uid' => $user_id,
|
||||
]);
|
||||
|
||||
// ── Step 9: Clear invite token from company_map_user ─────────────────────
|
||||
$pdo1->prepare(
|
||||
"UPDATE company_map_user SET invite_token = NULL WHERE user_id = :uid"
|
||||
)->execute([':uid' => $user_id]);
|
||||
|
||||
// ── Step 10: Clear session invite keys ────────────────────────────────────
|
||||
unset($_SESSION['invited_user_id'], $_SESSION['invited_token']);
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = 'Account setup complete.';
|
||||
|
||||
} catch (Exception $e) {
|
||||
$answer['message'] = $e->getMessage();
|
||||
http_response_code(400);
|
||||
}
|
||||
|
||||
exit(json_encode($answer));
|
||||
@@ -124,10 +124,13 @@ $_SESSION["login_name"] = $temp["name"];
|
||||
$_SESSION["login_surname"] = $temp["surname"];
|
||||
$_SESSION["login_company_id"] = $temp["default_company"];
|
||||
$_SESSION["login_profile_picture"] = $temp["profile_picture"] ?? '';
|
||||
$_SESSION["login_license"] = $temp["license"] ?? 'user';
|
||||
// license='owner' means the user holds their own subscription — use user.app_access.
|
||||
// license='user' means they were invited — use company_map_user.app_access instead.
|
||||
$_SESSION["login_app_access"] = $temp["app_access"] ?? 'wms';
|
||||
|
||||
$role_sth = $pdo1->prepare(
|
||||
"SELECT role FROM company_map_user
|
||||
"SELECT role, app_access FROM company_map_user
|
||||
WHERE company_id = :company_id AND user_id = :user_id
|
||||
LIMIT 1"
|
||||
);
|
||||
@@ -135,7 +138,12 @@ $role_sth->execute([
|
||||
':company_id' => $_SESSION["login_company_id"],
|
||||
':user_id' => $_SESSION["login_user_id"],
|
||||
]);
|
||||
$_SESSION["login_role"] = $role_sth->fetchColumn() ?: 'viewer';
|
||||
$map_row = $role_sth->fetch(PDO::FETCH_ASSOC);
|
||||
$_SESSION["login_role"] = $map_row['role'] ?? 'viewer';
|
||||
|
||||
if (($temp['license'] ?? 'owner') !== 'owner') {
|
||||
$_SESSION["login_app_access"] = $map_row['app_access'] ?? 'wms';
|
||||
}
|
||||
|
||||
// ── Step 6: Respond ───────────────────────────────────────────────────────────
|
||||
$answer["success"] = 1;
|
||||
|
||||
@@ -191,11 +191,17 @@ try {
|
||||
// ── Step 11: Map user as company owner ───────────────────────────────────
|
||||
// company_map_user is the many-to-many table between users and companies.
|
||||
// 'owner' role grants full admin access within the company.
|
||||
// app_access mirrors the owner's license (user.app_access) so the column
|
||||
// is never NULL and switch_branch reads consistent data.
|
||||
$sth = $pdo1->prepare("SELECT app_access FROM user WHERE user_id = :u LIMIT 1");
|
||||
$sth->execute([':u' => $user_id]);
|
||||
$owner_app_access = $sth->fetchColumn() ?: 'wms';
|
||||
|
||||
$sth = $pdo1->prepare("
|
||||
INSERT INTO company_map_user (company_id, user_id, role, created_at)
|
||||
VALUES (:company_id, :user_id, 'owner', NOW())
|
||||
INSERT INTO company_map_user (company_id, user_id, role, app_access, created_at)
|
||||
VALUES (:company_id, :user_id, 'owner', :app_access, NOW())
|
||||
");
|
||||
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id]);
|
||||
$sth->execute([':company_id' => $company_id, ':user_id' => $user_id, ':app_access' => $owner_app_access]);
|
||||
db_check($sth, $answer);
|
||||
|
||||
// ── Step 12: Activate user account and set default company ───────────────
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
require '../session.php';
|
||||
require '../config.php';
|
||||
require '../dbconn.php';
|
||||
|
||||
$token = trim($_GET['token'] ?? '');
|
||||
|
||||
if (!$token) {
|
||||
header('Location: ' . $server_url . 'login/index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// Validate token — must match a pending invited user (license='user') that has not expired
|
||||
$sth = $pdo1->prepare(
|
||||
"SELECT u.user_id, u.email, u.verify_expires_at, c.company_name
|
||||
FROM user u
|
||||
JOIN company_map_user m ON m.user_id = u.user_id
|
||||
JOIN company_list c ON c.company_id = m.company_id
|
||||
WHERE u.verify_token = :token
|
||||
AND u.status = 'pending'
|
||||
AND u.license = 'user'
|
||||
LIMIT 1"
|
||||
);
|
||||
$sth->execute([':token' => $token]);
|
||||
$row = $sth->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// Determine error state: cancelled (no row) or expired (row found but past expiry)
|
||||
$invite_error = null;
|
||||
if (!$row) {
|
||||
$invite_error = 'cancelled';
|
||||
} elseif (strtotime($row['verify_expires_at']) <= time()) {
|
||||
$invite_error = 'expired';
|
||||
}
|
||||
|
||||
if ($invite_error) {
|
||||
require '../include_header.php';
|
||||
$msg = $invite_error === 'expired'
|
||||
? ['icon' => 'ti-clock-x', 'title' => 'Invitation Expired',
|
||||
'body' => 'This invitation link has expired. Please contact your administrator to send a new invitation.']
|
||||
: ['icon' => 'ti-user-x', 'title' => 'Invitation Cancelled',
|
||||
'body' => 'This invitation has been cancelled. Please contact your administrator if you believe this is a mistake.'];
|
||||
?>
|
||||
<body>
|
||||
<div class="container py-5" style="max-width:480px;">
|
||||
<div class="text-center mb-5">
|
||||
<a href="<?php echo $server_url?>login/index.php" class="d-inline-block mb-4">
|
||||
<img src="<?php echo $server_url?>assets/images/favicon.png" alt="" width="40"/>
|
||||
<span class="ms-2"><img src="<?php echo $server_url?>assets/images/logo.svg" alt=""></span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="card text-center">
|
||||
<div class="card-body p-5">
|
||||
<i class="ti <?php echo $msg['icon']; ?> text-danger mb-3" style="font-size:3rem;"></i>
|
||||
<h2 class="fs-4 mb-2"><?php echo $msg['title']; ?></h2>
|
||||
<p class="text-muted mb-4"><?php echo $msg['body']; ?></p>
|
||||
<a href="<?php echo $server_url?>login/index.php" class="btn btn-primary">
|
||||
Back to Sign In
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
<?php
|
||||
exit;
|
||||
}
|
||||
|
||||
$_SESSION['invited_user_id'] = (int)$row['user_id'];
|
||||
$_SESSION['invited_token'] = $token;
|
||||
|
||||
if (empty($_SESSION['csrf_token'])) {
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
$company_name = htmlspecialchars($row['company_name']);
|
||||
$invite_email = htmlspecialchars($row['email']);
|
||||
|
||||
require '../include_header.php';
|
||||
?>
|
||||
|
||||
<body>
|
||||
|
||||
<div class="container py-5" style="max-width:520px;">
|
||||
|
||||
<div class="text-center mb-5">
|
||||
<a href="<?php echo $server_url?>login/index.php" class="d-inline-block mb-4">
|
||||
<img src="<?php echo $server_url?>assets/images/favicon.png" alt="" width="40"/>
|
||||
<span class="ms-2"><img src="<?php echo $server_url?>assets/images/logo.svg" alt=""></span>
|
||||
</a>
|
||||
<h1 class="h4 mb-1">You've been invited!</h1>
|
||||
<p class="text-muted">Complete your account setup to join <strong><?php echo $company_name ?></strong>.</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body p-5">
|
||||
<h2 class="fs-5 mb-1"><i class="ti ti-user-check me-2"></i>Account Setup</h2>
|
||||
<p class="text-muted small mb-4">Your email: <strong><?php echo $invite_email ?></strong></p>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">First Name <span class="text-danger">*</span></label>
|
||||
<input type="text" class="form-control" id="name" placeholder="First name">
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Last Name <span class="text-danger">*</span></label>
|
||||
<input type="text" class="form-control" id="surname" placeholder="Last name">
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Username <span class="text-danger">*</span></label>
|
||||
<input type="text" class="form-control" id="username" placeholder="Lowercase letters, numbers, underscores">
|
||||
<div class="form-text">Used to log in. Cannot be changed later.</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Password <span class="text-danger">*</span></label>
|
||||
<div class="input-group">
|
||||
<input type="password" class="form-control" id="password" placeholder="Choose a strong password">
|
||||
<button class="btn btn-outline-secondary toggle-pw" type="button" data-target="password">
|
||||
<i class="ti ti-eye"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Confirm Password <span class="text-danger">*</span></label>
|
||||
<div class="input-group">
|
||||
<input type="password" class="form-control" id="confirm_password" placeholder="Repeat your password">
|
||||
<button class="btn btn-outline-secondary toggle-pw" type="button" data-target="confirm_password">
|
||||
<i class="ti ti-eye"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-end mt-4">
|
||||
<button class="btn btn-primary px-5" id="btn_finish" onclick="finish_setup()">
|
||||
<i class="ti ti-rocket me-1"></i>Complete Setup
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
$(function () {
|
||||
$(document).on('click', '.toggle-pw', function () {
|
||||
const $input = $('#' + $(this).data('target'));
|
||||
const isText = $input.attr('type') === 'text';
|
||||
$input.attr('type', isText ? 'password' : 'text');
|
||||
$(this).find('i').toggleClass('ti-eye ti-eye-off');
|
||||
});
|
||||
});
|
||||
|
||||
function finish_setup() {
|
||||
const name = $('#name').val().trim();
|
||||
const surname = $('#surname').val().trim();
|
||||
const username = $('#username').val().trim();
|
||||
const password = $('#password').val();
|
||||
const confirm = $('#confirm_password').val();
|
||||
|
||||
if (!name || !surname || !username || !password || !confirm) {
|
||||
bootbox.alert('All fields are required.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirm) {
|
||||
bootbox.alert('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
|
||||
const $btn = $('#btn_finish');
|
||||
$btn.prop('disabled', true).html('<i class="ti ti-loader-2 me-1"></i>Setting up…');
|
||||
|
||||
ajax_request({
|
||||
url: '<?php echo $server_url?>login/api/engine/invited_onboarding.php',
|
||||
autoPrepare: false,
|
||||
data: { json: JSON.stringify({ name, surname, username, password, confirm_password: confirm }) },
|
||||
onSuccess: function () {
|
||||
bootbox.alert('Account setup complete! Please sign in.', function () {
|
||||
window.location.href = '<?php echo $server_url?>login/index.php';
|
||||
});
|
||||
},
|
||||
onError: function () {
|
||||
$btn.prop('disabled', false).html('<i class="ti ti-rocket me-1"></i>Complete Setup');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -6,7 +6,7 @@
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/InvoiceManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
require '../../../assets/utils/classes/ReturnManager.php';
|
||||
require '../../../assets/utils/classes/InvoiceManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/InvoiceManager.php';
|
||||
|
||||
try {
|
||||
@@ -17,12 +18,17 @@
|
||||
exit(json_encode($answer));
|
||||
}
|
||||
|
||||
$is_new = !(int)($data['id'] ?? 0);
|
||||
|
||||
dbTransaction($pdo2, function($pdo) use ($data, $company_id, $logging) {
|
||||
$inv = new InvoiceManager($pdo, $company_id);
|
||||
$inv->saveInvoice($data, $logging);
|
||||
});
|
||||
|
||||
$answer['success'] = 1;
|
||||
if ($is_new) {
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$answer['message'] = 'Database error, please try again.';
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/OrderManager.php';
|
||||
|
||||
// Decode items JSON string back to array
|
||||
@@ -25,6 +26,7 @@
|
||||
$answer['success'] = 1;
|
||||
if ($new_id) {
|
||||
$answer['new_id'] = $new_id;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/InvoiceManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
require '../../../assets/utils/classes/SupplierReturnManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/InvoiceManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
$return_id = (int)($data['id'] ?? 0);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/PurchaseOrderManager.php';
|
||||
|
||||
$data['items'] = json_decode($data['items'] ?? '[]', true) ?: [];
|
||||
@@ -17,6 +18,7 @@
|
||||
$answer['success'] = 1;
|
||||
if ($new_id) {
|
||||
$answer['new_id'] = $new_id;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
require '../../../assets/utils/classes/PurchaseOrderManager.php';
|
||||
require '../../../assets/utils/classes/StockManager.php';
|
||||
require '../../../assets/utils/classes/WarehouseManager.php';
|
||||
require '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
require_once '../../../assets/utils/classes/CompanySettingManager.php';
|
||||
|
||||
$id = (int)($data['id'] ?? 0);
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
session_start();
|
||||
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$report = new ReportManager($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$report = new ReportManager($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$report = new ReportManager($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$rack_id = (int)($data['rack_id'] ?? 0);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$report = new ReportManager($pdo2, $company_id);
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$data = json_decode($_POST['json'] ?? '{}', true) ?: [];
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->assertFeatureAccessible('reports');
|
||||
require '../../../assets/utils/classes/ReportManager.php';
|
||||
|
||||
$data = json_decode($_POST['json'] ?? '{}', true) ?: [];
|
||||
|
||||
@@ -349,7 +349,7 @@
|
||||
$('#summary_note').text('');
|
||||
|
||||
// Reset UI
|
||||
$('#tbl_body').html('<tr><td colspan="9" class="text-center py-4 text-muted">Loading…</td></tr>');
|
||||
$('#tbl_body').html('<tr><td colspan="13" class="text-center py-4 text-muted">Loading…</td></tr>');
|
||||
$('#lazy_sentinel').hide();
|
||||
$('#lazy_loader').hide();
|
||||
$('#lazy_done').hide();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/OrderManager.php';
|
||||
|
||||
$action = $data['action'] ?? '';
|
||||
@@ -41,6 +42,7 @@ try {
|
||||
$answer['message'] = $action === 'create' ? 'Sales order created' : 'Sales order updated';
|
||||
if ($new_id) {
|
||||
$answer['new_id'] = $new_id;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
session_start();
|
||||
require '../../../assets/utils/db_auth.php';
|
||||
require '../../../assets/utils/classes/UsageGuard.php';
|
||||
require '../../../assets/utils/classes/QuotationManager.php';
|
||||
|
||||
$action = $data['action'] ?? '';
|
||||
@@ -16,6 +17,7 @@ try {
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = 'Quotation created.';
|
||||
$answer['new_id'] = $new_id;
|
||||
(new UsageGuard($pdo1, $company_id, $packages))->increment();
|
||||
} elseif ($action === 'update') {
|
||||
require_role($user_role, ['owner', 'admin', 'staff']);
|
||||
$qm->save(array_merge($data, ['id' => $id, 'items' => $items]), $logging);
|
||||
|
||||
@@ -10,21 +10,109 @@
|
||||
|
||||
try {
|
||||
|
||||
// All valid app_access values: every registered app key + 'all'
|
||||
$all_app_keys = array_keys($app_registry);
|
||||
$all_valid_apps = array_merge($all_app_keys, ['all']);
|
||||
|
||||
// What the current owner's license permits assigning to others
|
||||
$owner_access = $_SESSION['login_app_access'] ?? 'wms';
|
||||
$owner_allowed_access = $owner_access === 'all' ? $all_valid_apps : [$owner_access];
|
||||
|
||||
if ($action === 'create') {
|
||||
$email = strtolower(trim($data['invite_email'] ?? ''));
|
||||
$role = trim($data['invite_role'] ?? '');
|
||||
$app_access = trim($data['invite_app_access'] ?? '');
|
||||
|
||||
if (!in_array($app_access, $owner_allowed_access, true)) {
|
||||
throw new Exception('App access selection exceeds your license.');
|
||||
}
|
||||
|
||||
$result = $um->inviteUser($email, $role, $app_access);
|
||||
|
||||
if ($result['new_user']) {
|
||||
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
|
||||
. '://' . $_SERVER['HTTP_HOST'] . rtrim($server_url, '/');
|
||||
$invite_url = $base_url . '/login/invited_onboarding.php?token=' . $result['token'];
|
||||
|
||||
require_once '../../../assets/utils/module/mailer.php';
|
||||
$mailer = new mailer(['pdo1' => $pdo1]);
|
||||
$mailer->send_email([
|
||||
'company_id' => $company_id,
|
||||
'to' => $result['email'],
|
||||
'subject' => 'You have been invited to join the team',
|
||||
'message' => implode("\n", [
|
||||
"You have been invited to join the team.",
|
||||
"",
|
||||
"Click the button below to set up your account:",
|
||||
"",
|
||||
"<a href=\"{$invite_url}\" style=\"display:inline-block;padding:12px 28px;background:#E66239;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;\">Accept Invitation</a>",
|
||||
"",
|
||||
"Or copy and paste this link into your browser:",
|
||||
"<a href=\"{$invite_url}\">{$invite_url}</a>",
|
||||
"",
|
||||
"This link will expire in 7 days.",
|
||||
"",
|
||||
"If you did not expect this invitation, you can ignore this email.",
|
||||
]),
|
||||
'channel_name' => 'WMS',
|
||||
'key' => $pinkey,
|
||||
]);
|
||||
$answer['message'] = htmlspecialchars($result['email']) . ' has been invited. An email has been sent to complete their registration.';
|
||||
} else {
|
||||
$answer['message'] = htmlspecialchars($result['email']) . ' has been added to your company.';
|
||||
}
|
||||
|
||||
$invited_email = $um->inviteUser($email, $role);
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = htmlspecialchars($invited_email) . ' has been added to your company.';
|
||||
|
||||
} elseif ($action === 'update') {
|
||||
$map_id = (int)($data['map_id'] ?? 0);
|
||||
$role = trim($data['role'] ?? '');
|
||||
$app_access = trim($data['app_access'] ?? '');
|
||||
|
||||
$um->updateRole($map_id, $role);
|
||||
|
||||
if ($app_access !== '') {
|
||||
if (!in_array($app_access, $owner_allowed_access, true)) {
|
||||
throw new Exception('App access selection exceeds your license.');
|
||||
}
|
||||
$um->updateAppAccess($map_id, $app_access);
|
||||
}
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = 'Role updated successfully.';
|
||||
$answer['message'] = 'Access updated successfully.';
|
||||
|
||||
} elseif ($action === 'resend') {
|
||||
$map_id = (int)($data['map_id'] ?? 0);
|
||||
$result = $um->resendInvite($map_id);
|
||||
|
||||
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
|
||||
. '://' . $_SERVER['HTTP_HOST'] . rtrim($server_url, '/');
|
||||
$invite_url = $base_url . '/login/invited_onboarding.php?token=' . $result['token'];
|
||||
|
||||
require_once '../../../assets/utils/module/mailer.php';
|
||||
$mailer = new mailer(['pdo1' => $pdo1]);
|
||||
$mailer->send_email([
|
||||
'company_id' => $company_id,
|
||||
'to' => $result['email'],
|
||||
'subject' => 'Your invitation link has been resent',
|
||||
'message' => implode("\n", [
|
||||
"Your invitation link has been refreshed.",
|
||||
"",
|
||||
"Click the button below to set up your account:",
|
||||
"",
|
||||
"<a href=\"{$invite_url}\" style=\"display:inline-block;padding:12px 28px;background:#E66239;color:#ffffff;text-decoration:none;border-radius:6px;font-weight:600;\">Accept Invitation</a>",
|
||||
"",
|
||||
"Or copy and paste this link into your browser:",
|
||||
"<a href=\"{$invite_url}\">{$invite_url}</a>",
|
||||
"",
|
||||
"This link will expire in 7 days.",
|
||||
]),
|
||||
'channel_name' => 'WMS',
|
||||
'key' => $pinkey,
|
||||
]);
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = 'Invitation resent to ' . htmlspecialchars($result['email']) . '.';
|
||||
|
||||
} elseif ($action === 'delete') {
|
||||
$map_id = (int)($data['map_id'] ?? 0);
|
||||
|
||||
@@ -39,6 +39,12 @@ if ($action === 'update') {
|
||||
$_SESSION['login_company_id'] = $target_company_id;
|
||||
$_SESSION['login_role'] = $target_map['role'] ?? 'viewer';
|
||||
|
||||
if (($_SESSION['login_license'] ?? 'user') === 'owner') {
|
||||
$_SESSION['login_app_access'] = $target_map['user_app_access'] ?? 'wms';
|
||||
} else {
|
||||
$_SESSION['login_app_access'] = $target_map['app_access'] ?? 'wms';
|
||||
}
|
||||
|
||||
$answer['success'] = 1;
|
||||
$answer['message'] = 'Switched successfully.';
|
||||
exit(json_encode($answer));
|
||||
|
||||
+117
-31
@@ -68,13 +68,14 @@
|
||||
<th class="ps-4">User</th>
|
||||
<th>Email</th>
|
||||
<th>Role</th>
|
||||
<th>App Access</th>
|
||||
<th>Joined</th>
|
||||
<th class="text-end pe-4">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="users_tbody">
|
||||
<tr>
|
||||
<td colspan="5" class="text-center py-5 text-muted">
|
||||
<td colspan="6" class="text-center py-5 text-muted">
|
||||
<i class="ti ti-loader-2 fs-2 d-block mb-2"></i>Loading…
|
||||
</td>
|
||||
</tr>
|
||||
@@ -118,6 +119,13 @@
|
||||
<option value="viewer">Viewer — read-only access</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">App Access <span class="text-danger">*</span></label>
|
||||
<select class="form-select" id="invite_app_access"></select>
|
||||
<div id="invite_app_access_note" class="form-text text-warning mt-1" style="display:none;">
|
||||
<i class="ti ti-info-circle me-1"></i>Single app license — access is limited to <strong id="invite_app_access_label"></strong>.
|
||||
</div>
|
||||
</div>
|
||||
<div class="alert alert-light border small mb-0">
|
||||
<div class="fw-semibold mb-1">Role permissions</div>
|
||||
<ul class="mb-0 ps-3">
|
||||
@@ -139,13 +147,13 @@
|
||||
|
||||
|
||||
<!-- ═══════════════════════════════════════════════
|
||||
EDIT ROLE MODAL
|
||||
EDIT ACCESS MODAL
|
||||
═══════════════════════════════════════════════ -->
|
||||
<div class="modal fade" id="editRoleModal" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="ti ti-shield-half me-2"></i>Change Role</h5>
|
||||
<h5 class="modal-title"><i class="ti ti-shield-half me-2"></i>Edit Access</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@@ -166,6 +174,13 @@
|
||||
<option value="viewer">Viewer</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">App Access</label>
|
||||
<select class="form-select" id="edit_app_access"></select>
|
||||
<div id="edit_app_access_note" class="form-text text-warning mt-1" style="display:none;">
|
||||
<i class="ti ti-info-circle me-1"></i>Single app license — access is limited to <strong id="edit_app_access_label"></strong>.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-ghost-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
@@ -185,7 +200,9 @@
|
||||
const api = '<?php echo $server_url?>setting/api/engine/';
|
||||
const img_base = '<?php echo $server_url?>uploads/profile/';
|
||||
const avatar_ph = '<?php echo $server_url?>assets/images/logo.svg';
|
||||
let _users_data = []; // full list from server
|
||||
const owner_app_access = '<?php echo htmlspecialchars($_SESSION['login_app_access'] ?? 'wms', ENT_QUOTES); ?>';
|
||||
const APP_REGISTRY = <?php echo json_encode($app_registry); ?>;
|
||||
let _users_data = [];
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
@@ -222,7 +239,7 @@
|
||||
if (!rows.length) {
|
||||
tbody.html(`
|
||||
<tr>
|
||||
<td colspan="5" class="text-center py-5 text-muted">
|
||||
<td colspan="6" class="text-center py-5 text-muted">
|
||||
<i class="ti ti-users-group fs-2 d-block mb-2"></i>No users found.
|
||||
</td>
|
||||
</tr>`);
|
||||
@@ -236,20 +253,34 @@
|
||||
style="width:36px;height:36px;font-size:13px;">${initials(u.name, u.surname)}</span>`;
|
||||
|
||||
const role_badge = role_html(u.role);
|
||||
const access_badge = app_access_html(u.app_access);
|
||||
|
||||
const joined = u.created_at
|
||||
? new Date(u.created_at).toLocaleDateString('en-GB', {day:'2-digit', month:'short', year:'numeric'})
|
||||
: '—';
|
||||
|
||||
// Build action buttons — owner cannot be edited or removed
|
||||
const is_pending = u.status === 'pending' && u.is_pending_invite == 1;
|
||||
|
||||
let actions = '';
|
||||
if (u.role !== 'owner') {
|
||||
if (u.role === 'owner') {
|
||||
// owner — no actions
|
||||
} else if (is_pending) {
|
||||
actions += `
|
||||
<button class="btn btn-sm btn-ghost-secondary" title="Change role"
|
||||
<button class="btn btn-sm btn-ghost-secondary" title="Resend invitation"
|
||||
onclick="resend_invite(${u.map_id}, '${esc(u.email)}')">
|
||||
<i class="ti ti-send"></i>
|
||||
</button>`;
|
||||
actions += `
|
||||
<button class="btn btn-sm btn-ghost-danger" title="Cancel invitation"
|
||||
onclick="remove_user(${u.map_id}, '${esc(u.email)}')">
|
||||
<i class="ti ti-user-minus"></i>
|
||||
</button>`;
|
||||
} else {
|
||||
actions += `
|
||||
<button class="btn btn-sm btn-ghost-secondary" title="Edit access"
|
||||
onclick="open_edit_modal(${u.map_id})">
|
||||
<i class="ti ti-shield-half"></i>
|
||||
</button>`;
|
||||
|
||||
actions += `
|
||||
<button class="btn btn-sm btn-ghost-danger" title="Remove user"
|
||||
onclick="remove_user(${u.map_id}, '${esc(u.name)} ${esc(u.surname)}')">
|
||||
@@ -257,6 +288,10 @@
|
||||
</button>`;
|
||||
}
|
||||
|
||||
const display_role = is_pending
|
||||
? `<span class="badge bg-warning text-dark"><i class="ti ti-clock me-1"></i>Pending Invite</span>`
|
||||
: role_badge;
|
||||
|
||||
return `
|
||||
<tr data-role="${u.role}"
|
||||
data-search="${esc(u.name)} ${esc(u.surname)} ${esc(u.email)}">
|
||||
@@ -264,13 +299,14 @@
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
${avatar}
|
||||
<div>
|
||||
<div class="fw-semibold lh-sm">${esc(u.name)} ${esc(u.surname)}</div>
|
||||
<div class="small" style="color:#6c757d;">@${esc(u.username)}</div>
|
||||
<div class="fw-semibold lh-sm">${is_pending ? '—' : esc(u.name) + ' ' + esc(u.surname)}</div>
|
||||
<div class="small" style="color:#6c757d;">${is_pending ? esc(u.email) : '@' + esc(u.username)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td style="color:#495057;">${esc(u.email)}</td>
|
||||
<td>${role_badge}</td>
|
||||
<td>${display_role}</td>
|
||||
<td>${is_pending ? '—' : access_badge}</td>
|
||||
<td style="color:#495057;">${joined}</td>
|
||||
<td class="text-end pe-4">
|
||||
<div class="d-flex justify-content-end gap-1">${actions}</div>
|
||||
@@ -305,26 +341,20 @@
|
||||
function open_invite_modal() {
|
||||
$('#invite_email').val('').removeClass('is-invalid is-valid');
|
||||
$('#invite_role').val('').removeClass('is-invalid');
|
||||
build_app_access_select('invite_app_access', 'invite_app_access_note', 'invite_app_access_label', null);
|
||||
$('#inviteModal').modal('show');
|
||||
}
|
||||
|
||||
function send_invite() {
|
||||
const email = $('#invite_email').val().trim();
|
||||
const role = $('#invite_role').val();
|
||||
const app_access = $('#invite_app_access').val();
|
||||
let valid = true;
|
||||
|
||||
if (!email) {
|
||||
$('#invite_email').addClass('is-invalid');
|
||||
valid = false;
|
||||
} else {
|
||||
$('#invite_email').removeClass('is-invalid');
|
||||
}
|
||||
if (!role) {
|
||||
$('#invite_role').addClass('is-invalid');
|
||||
valid = false;
|
||||
} else {
|
||||
$('#invite_role').removeClass('is-invalid');
|
||||
}
|
||||
if (!email) { $('#invite_email').addClass('is-invalid'); valid = false; }
|
||||
else { $('#invite_email').removeClass('is-invalid'); }
|
||||
if (!role) { $('#invite_role').addClass('is-invalid'); valid = false; }
|
||||
else { $('#invite_role').removeClass('is-invalid'); }
|
||||
if (!valid) return;
|
||||
|
||||
ajax_request({
|
||||
@@ -332,20 +362,18 @@
|
||||
autoPrepare: true,
|
||||
checkRequired: 0,
|
||||
action: 'create',
|
||||
data: { invite_email: email, invite_role: role },
|
||||
data: { invite_email: email, invite_role: role, invite_app_access: app_access },
|
||||
onSuccess: function (r) {
|
||||
$('#inviteModal').modal('hide');
|
||||
bootbox.alert(r.message || 'Invitation sent.');
|
||||
bootbox.alert(r.message || 'User added.');
|
||||
load_users();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
// Edit role
|
||||
// Edit access
|
||||
// ═══════════════════════════════════════════════
|
||||
function open_edit_modal(map_id) {
|
||||
const u = _users_data.find(x => x.map_id == map_id);
|
||||
@@ -356,6 +384,7 @@
|
||||
$('#edit_email_display').text(u.email);
|
||||
$('#edit_role').val(u.role);
|
||||
$('#edit_avatar').attr('src', u.profile_picture ? img_base + u.profile_picture : avatar_ph);
|
||||
build_app_access_select('edit_app_access', 'edit_app_access_note', 'edit_app_access_label', u.app_access);
|
||||
|
||||
$('#editRoleModal').modal('show');
|
||||
}
|
||||
@@ -366,10 +395,10 @@
|
||||
autoPrepare: true,
|
||||
checkRequired: 0,
|
||||
action: 'update',
|
||||
data: { map_id: $('#edit_map_id').val(), role: $('#edit_role').val() },
|
||||
data: { map_id: $('#edit_map_id').val(), role: $('#edit_role').val(), app_access: $('#edit_app_access').val() },
|
||||
onSuccess: function (r) {
|
||||
$('#editRoleModal').modal('hide');
|
||||
bootbox.alert(r.message || 'Role updated.');
|
||||
bootbox.alert(r.message || 'Access updated.');
|
||||
load_users();
|
||||
},
|
||||
});
|
||||
@@ -397,6 +426,26 @@
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
// Resend invite
|
||||
// ═══════════════════════════════════════════════
|
||||
function resend_invite(map_id, email) {
|
||||
bootbox.confirm(`Resend invitation to <strong>${esc(email)}</strong>?`, function (ok) {
|
||||
if (!ok) return;
|
||||
ajax_request({
|
||||
url: api + 'manage_users.php',
|
||||
autoPrepare: true,
|
||||
checkRequired: 0,
|
||||
action: 'resend',
|
||||
data: { map_id: map_id },
|
||||
onSuccess: function (r) {
|
||||
bootbox.alert(r.message || 'Invitation resent.');
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
// Helpers
|
||||
// ═══════════════════════════════════════════════
|
||||
@@ -422,6 +471,43 @@
|
||||
return `<span class="badge ${cls}"><i class="ti ${icon} me-1"></i>${label}</span>`;
|
||||
}
|
||||
|
||||
function app_access_label(access) {
|
||||
if (access === 'all') return 'All Apps';
|
||||
return APP_REGISTRY[access]?.label || access;
|
||||
}
|
||||
|
||||
function app_access_html(access) {
|
||||
if (access === 'all') {
|
||||
return `<span class="badge bg-secondary"><i class="ti ti-apps me-1"></i>All Apps</span>`;
|
||||
}
|
||||
const app = APP_REGISTRY[access];
|
||||
if (!app) return `<span class="badge bg-label-secondary">${access || '—'}</span>`;
|
||||
return `<span class="badge ${app.color}"><i class="ti ${app.icon} me-1"></i>${app.label}</span>`;
|
||||
}
|
||||
|
||||
// Populate and lock/unlock an app_access <select> based on the owner's license.
|
||||
// Disabled with a notice when owner has a single-app license; enabled when 'all'.
|
||||
// Adding a new app to $app_registry in config.php automatically appears here.
|
||||
function build_app_access_select(select_id, note_id, label_id, current_val) {
|
||||
const $sel = $('#' + select_id);
|
||||
const $note = $('#' + note_id);
|
||||
const $lbl = $('#' + label_id);
|
||||
|
||||
if (owner_app_access === 'all') {
|
||||
const options = Object.entries(APP_REGISTRY)
|
||||
.map(([key, app]) => `<option value="${key}">${app.label}</option>`)
|
||||
.join('') + `<option value="all">All Apps</option>`;
|
||||
$sel.prop('disabled', false).html(options).val(current_val || Object.keys(APP_REGISTRY)[0]);
|
||||
$note.hide();
|
||||
} else {
|
||||
$sel.prop('disabled', true)
|
||||
.html(`<option value="${owner_app_access}">${app_access_label(owner_app_access)}</option>`)
|
||||
.val(owner_app_access);
|
||||
$lbl.text(app_access_label(owner_app_access));
|
||||
$note.show();
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user