Compare commits

..

12 Commits

Author SHA1 Message Date
Ollama
0ea3ced674 fix: Rename Plugin_config methods to avoid conflict with CodeIgniter Model::set()
The PluginConfig class extends CodeIgniter\Model which has its own set() method
for query building. Renaming get()/set() to getValue()/setValue() avoids this conflict.

Also fixed:
- batchSave() to use setValue() instead of set()
- Updated all callers in PluginManager and BasePlugin to use renamed methods
2026-03-24 08:07:18 +00:00
Ollama
896ed87797 fix: Address CodeRabbit AI review comments
- Move plugin discovery to pre_system in Events.php (allows events to be registered before they fire)
- Add plugin existence check in disablePlugin()
- Add is_subclass_of check before instantiating plugin classes
- Fix str_replace prefix removal in getPluginSettings using str_starts_with + substr
- Add down() migration to drop table on rollback
- Fix saveSettings to JSON-encode arrays/objects
- Update README to use MailchimpPlugin as reference implementation
- Remove CasposPlugin examples from documentation
2026-03-22 19:47:09 +00:00
Ollama
eb264ad76d refactor: Address review comments - PSR-12 naming and plugin cleanup
- Rename Plugin_config to PluginConfig (PSR-12 class naming)
- Remove non-functioning CasposPlugin example
- Remove ExamplePlugin (MailchimpPlugin serves as example)
- Fix privacy issue: Don't log customer email in MailchimpPlugin
- Remove unnecessary PHPDocs
- Fix PSR-12 brace placement
2026-03-22 19:40:36 +00:00
Ollama
10a64e7af9 refactor: Remove redundant isEnabled() checks from callback methods
The PluginManager only registers events for enabled plugins, so
callbacks are never invoked for disabled plugins. This makes
$this->isEnabled() checks in callbacks redundant.

Changes:
- Remove redundant isEnabled() checks from all plugin callbacks
- Clarify in README that isEnabled() checks are not needed
- Use log_message() instead of log() in plugins (PSR-12)
- Fix PSR-12 brace placement in CasposPlugin
2026-03-20 19:48:27 +00:00
Ollama
6e99f05d63 refactor: Update MailchimpPlugin as proper example plugin
- Reword docblock to remove 'Example' - it's a functioning plugin
- Rename 'Mailchimp Integration' to 'Mailchimp' (context makes it clear)
- Use lang() method for translatable strings with self-contained language file
- Use log_message() instead of log() for PSR-12 consistency
- Add missing language strings: mailchimp_description, mailchimp_api_key_required
- Add getPluginDir() method for language helper
2026-03-20 18:32:42 +00:00
Ollama
c430c7afb5 refactor: Move mailchimp language strings to self-contained plugin directory
- Create app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php
- Remove mailchimp strings from core app/Language/en/Plugins.php
- Plugin language files are now self-contained per the documentation
2026-03-19 18:24:48 +00:00
Ollama
519347f4f5 refactor: Fix PSR-12 and documentation issues
- Consolidate duplicate documentation sections
- Move Internationalization section after Plugin Views
- Remove redundant Example Plugin Structure and View Hooks sections
- Fix PSR-12 brace style in plugin_helper.php
- Fix PSR-12 brace style in PluginInterface.php (remove unnecessary PHPdocs)
- Fix PSR-12 brace style in BasePlugin.php (remove unnecessary PHPdocs)
- Use log_message() instead of error_log() in migration
- Add IF NOT EXISTS to plugin_config table creation for resilience
- Convert snake_case to camelCase for class names throughout docs
2026-03-19 18:20:05 +00:00
Ollama
62d84411b2 docs: Fix documentation consistency issues
- Add Language folder to all plugin structure examples
- Convert snake_case to camelCase for class names (PSR-12)
- Add Language folder to initial plugin structure diagram
- Add Language folder to Complex Plugin structure
- Update all namespace references to use camelCase
2026-03-18 22:06:09 +00:00
Ollama
6bd4bb545d docs: Add internationalization section showing self-contained plugin language files
Adds documentation example showing how plugins can embed their own
language files within the plugin directory structure, keeping plugins
fully self-contained without modifying core language files.
2026-03-17 14:36:13 +00:00
Ollama
66f7d70749 feat(plugins): add view hooks for injecting plugin content into core views
Add event-based view hook system allowing plugins to inject UI elements
into core views without modifying core files. Includes helper functions
and example CasposPlugin demonstrating the pattern.
2026-03-12 10:13:12 +00:00
Ollama
bd8b4fa6c1 feat(plugins): Support self-contained plugin directories
- PluginManager now recursively scans app/Plugins/ to discover plugins
- Supports both single-file plugins (MyPlugin.php) and directory plugins (MyPlugin/MyPlugin.php)
- Plugins can contain their own Models, Controllers, Views, Libraries, Helpers
- Uses PSR-4 namespacing: App\Plugins\PluginName for files, App\Plugins\PluginName\Subdir for subdirectories
- Users can install plugins by simply dropping a folder into app/Plugins/
- Updated README with comprehensive documentation on both plugin formats

This makes plugin installation much easier - just drop the plugin folder and it works.
2026-03-09 21:58:53 +01:00
Ollama
a9669ddf19 feat(plugins): Implement modular plugin system with self-registering events
This implements a clean plugin architecture based on PR #4255 discussion:

Core Components:
- PluginInterface: Standard contract all plugins must implement
- BasePlugin: Abstract class with common functionality
- PluginManager: Discovers and loads plugins from app/Plugins/
- Plugin_config: Model for plugin settings storage

Architecture:
- Each plugin registers its own event listeners via registerEvents()
- No hardcoded plugin dependencies in core Events.php
- Generic event triggers (item_sale, item_change, etc.) remain in core code
- Plugins can be enabled/disabled via database settings
- Clean separation: plugin orchestrators vs MVC components

Example Implementations:
- ExamplePlugin: Simple plugin demonstrating event logging
- MailchimpPlugin: Integration with Mailchimp for customer sync

Admin UI:
- Plugin management controller at Controllers/Plugins/Manage.php
- Plugin management view at Views/plugins/manage.php

Database:
- ospos_plugin_config table for plugin settings (key-value store)
- Migration creates table with timestamps

Documentation:
- Comprehensive README with architecture patterns
- Simple vs complex plugin examples
- MVC directory structure guidance
2026-03-09 21:58:53 +01:00
24 changed files with 1573 additions and 1111 deletions

View File

@@ -1,72 +0,0 @@
name: Update Issue Templates
on:
release:
types: [published]
workflow_dispatch:
schedule:
- cron: '0 0 * * 0'
jobs:
update-templates:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Fetch releases and update templates
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Fetch releases from GitHub API
RELEASES=$(gh api repos/${{ github.repository }}/releases --jq '.[].tag_name' | head -n 10)
# Create temporary file with options
OPTIONS_FILE=$(mktemp)
echo " - development (unreleased)" >> "$OPTIONS_FILE"
while IFS= read -r release; do
echo " - opensourcepos $release" >> "$OPTIONS_FILE"
done <<< "$RELEASES"
update_template() {
local template="$1"
local template_path=".github/ISSUE_TEMPLATE/$template"
# Find the line numbers for the OpensourcePOS Version dropdown
start_line=$(grep -n "label: OpensourcePOS Version" "$template_path" | cut -d: -f1)
if [ -z "$start_line" ]; then
echo "Could not find OpensourcePOS Version in $template"
return 1
fi
# Find the options section and default line
options_start=$((start_line + 3))
default_line=$(grep -n "default:" "$template_path" | awk -F: -v opts="$options_start" '$1 > opts {print $1; exit}')
# Create new template file
head -n $((options_start - 1)) "$template_path" > "${template_path}.new"
cat "$OPTIONS_FILE" >> "${template_path}.new"
tail -n +$default_line "$template_path" >> "${template_path}.new"
mv "${template_path}.new" "$template_path"
echo "Updated $template"
}
update_template "bug report.yml"
update_template "feature_request.yml"
- name: Commit and push changes
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add .github/ISSUE_TEMPLATE/*.yml
if git diff --staged --quiet; then
echo "No changes to commit"
else
git commit -m "Update issue templates with latest releases [skip ci]"
git push
fi

View File

@@ -1,9 +1,9 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
- [Security Policy](#security-policy)
- [Supported Versions](#supported-versions)
- [Security Advisories](#security-advisories)
- [Reporting a Vulnerability](#reporting-a-vulnerability)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
@@ -12,35 +12,14 @@
## Supported Versions
We release patches for security vulnerabilities.
We release patches for security vulnerabilities. Which versions are eligible to receive such patches depend on the CVSS v3.0 Rating:
| Version | Supported |
| --------- | ------------------ |
| >= 3.4.2 | :white_check_mark: |
| < 3.4.2 | :x: |
## Security Advisories
The following security vulnerabilities have been published:
### High Severity
| CVE | Vulnerability | CVSS | Published | Fixed In | Credit |
|-----|--------------|------|-----------|----------|--------|
| [CVE-2025-68434](https://github.com/opensourcepos/opensourcepos/security/advisories/GHSA-wjm4-hfwg-5w5r) | CSRF leading to Admin Creation | 8.8 | 2025-12-17 | 3.4.2 | @Nixon-H, @jekkos |
| [CVE-2025-68147](https://github.com/opensourcepos/opensourcepos/security/advisories/GHSA-xgr7-7pvw-fpmh) | Stored XSS in Return Policy | 8.1 | 2025-12-17 | 3.4.2 | @Nixon-H, @jekkos |
| [CVE-2025-66924](https://github.com/opensourcepos/opensourcepos/security/advisories/GHSA-gv8j-f6gq-g59m) | Stored XSS in Item Kits | 7.2 | 2026-03-04 | 3.4.2 | @hungnqdz, @omkaryepre |
### Medium Severity
| CVE | Vulnerability | CVSS | Published | Fixed In | Credit |
|-----|--------------|------|-----------|----------|--------|
| [CVE-2025-68658](https://github.com/opensourcepos/opensourcepos/security/advisories/GHSA-32r8-8r9r-9chw) | Stored XSS in Company Name | 4.3 | 2026-01-13 | 3.4.2 | @hungnqdz |
For a complete list including draft advisories, see our [GitHub Security Advisories page](https://github.com/opensourcepos/opensourcepos/security/advisories).
| CVSS v3.0 | Supported Versions |
| --------- | -------------------------------------------------- |
| 7.3 | 3.3.5 |
| 9.8 | 3.3.6 |
| 6.8 | 3.4.2 |
## Reporting a Vulnerability
Please report (suspected) security vulnerabilities to **[jeroen@steganos.dev](mailto:jeroen@steganos.dev)**.
You will receive a response from us within 48 hours. If the issue is confirmed, we will release a patch as soon as possible depending on complexity but historically within a few days.
Please report (suspected) security vulnerabilities to **[jeroen@steganos.dev](mailto:jeroen@steganos.dev)**. You will receive a response from us within 48 hours. If the issue is confirmed, we will release a patch as soon as possible depending on complexity but historically within a few days.

View File

@@ -205,6 +205,7 @@ class Autoload extends AutoloadConfig
'cookie',
'tabular',
'locale',
'security'
'security',
'plugin'
];
}

View File

@@ -8,23 +8,7 @@ use CodeIgniter\HotReloader\HotReloader;
use App\Events\Db_log;
use App\Events\Load_config;
use App\Events\Method;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
use App\Libraries\Plugins\PluginManager;
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
@@ -39,22 +23,19 @@ Events::on('pre_system', static function (): void {
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
$pluginManager = new PluginManager();
$pluginManager->discoverPlugins();
$pluginManager->registerPluginEvents();
});
$config = new Load_config();
@@ -64,4 +45,4 @@ $db_log = new Db_log();
Events::on('DBQuery', [$db_log, 'db_log_queries']);
$method = new Method();
Events::on('pre_controller', [$method, 'validate_method']);
Events::on('pre_controller', [$method, 'validate_method']);

View File

@@ -0,0 +1,99 @@
<?php
namespace App\Controllers\Plugins;
use App\Controllers\Secure_Controller;
use App\Libraries\Plugins\PluginManager;
use CodeIgniter\HTTP\ResponseInterface;
class Manage extends Secure_Controller
{
private PluginManager $pluginManager;
public function __construct()
{
parent::__construct('plugins');
$this->pluginManager = new PluginManager();
$this->pluginManager->discoverPlugins();
}
public function getIndex(): string
{
$plugins = $this->pluginManager->getAllPlugins();
$enabledPlugins = $this->pluginManager->getEnabledPlugins();
$pluginData = [];
foreach ($plugins as $pluginId => $plugin) {
$pluginData[$pluginId] = [
'id' => $plugin->getPluginId(),
'name' => $plugin->getPluginName(),
'description' => $plugin->getPluginDescription(),
'version' => $plugin->getVersion(),
'enabled' => isset($enabledPlugins[$pluginId]),
'has_config' => $plugin->getConfigView() !== null,
];
}
echo view('plugins/manage', ['plugins' => $pluginData]);
return '';
}
public function postEnable(string $pluginId): ResponseInterface
{
if ($this->pluginManager->enablePlugin($pluginId)) {
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_enabled')]);
}
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_enable_failed')]);
}
public function postDisable(string $pluginId): ResponseInterface
{
if ($this->pluginManager->disablePlugin($pluginId)) {
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_disabled')]);
}
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_disable_failed')]);
}
public function postUninstall(string $pluginId): ResponseInterface
{
if ($this->pluginManager->uninstallPlugin($pluginId)) {
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.plugin_uninstalled')]);
}
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_uninstall_failed')]);
}
public function getConfig(string $pluginId): ResponseInterface
{
$plugin = $this->pluginManager->getPlugin($pluginId);
if (!$plugin) {
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_not_found')]);
}
$configView = $plugin->getConfigView();
if (!$configView) {
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_no_config')]);
}
$settings = $plugin->getSettings();
echo view($configView, ['settings' => $settings, 'plugin' => $plugin]);
return $this->response;
}
public function postSaveConfig(string $pluginId): ResponseInterface
{
$plugin = $this->pluginManager->getPlugin($pluginId);
if (!$plugin) {
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.plugin_not_found')]);
}
$settings = $this->request->getPost();
unset($settings['_method'], $settings['csrf_token_name']);
if ($plugin->saveSettings($settings)) {
return $this->response->setJSON(['success' => true, 'message' => lang('Plugins.settings_saved')]);
}
return $this->response->setJSON(['success' => false, 'message' => lang('Plugins.settings_save_failed')]);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class PluginConfigTableCreate extends Migration
{
public function up(): void
{
log_message('info', 'Migrating plugin_config table started');
execute_script(APPPATH . 'Database/Migrations/sqlscripts/3.4.1_PluginConfigTableCreate.sql');
}
public function down(): void
{
$this->forge->dropTable('plugin_config', true);
}
}

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS `ospos_plugin_config` (
`key` varchar(100) NOT NULL,
`value` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@@ -1,15 +0,0 @@
<?php
namespace App\Enums;
/**
* Reward operation types for customer points adjustments.
*
* Used by Reward_lib to perform type-safe reward point operations.
*/
enum RewardOperation: string
{
case Deduct = 'deduct';
case Restore = 'restore';
case Adjust = 'adjust';
}

View File

@@ -0,0 +1,24 @@
<?php
use CodeIgniter\Events\Events;
if (!function_exists('plugin_content')) {
function plugin_content(string $section, array $data = []): string
{
$results = Events::trigger("view:{$section}", $data);
if (is_array($results)) {
return implode('', array_filter($results, fn($r) => is_string($r)));
}
return is_string($results) ? $results : '';
}
}
if (!function_exists('plugin_content_exists')) {
function plugin_content_exists(string $section): bool
{
$observers = Events::listRegistered("view:{$section}");
return !empty($observers);
}
}

View File

@@ -0,0 +1,27 @@
<?php
return [
// Plugin Management
"plugins" => "Plugins",
"plugin_management" => "Plugin Management",
"plugin_name" => "Plugin Name",
"plugin_description" => "Description",
"plugin_version" => "Version",
"plugin_status" => "Status",
"plugin_enabled" => "Plugin enabled successfully",
"plugin_enable_failed" => "Failed to enable plugin",
"plugin_disabled" => "Plugin disabled successfully",
"plugin_disable_failed" => "Failed to disable plugin",
"plugin_uninstalled" => "Plugin uninstalled successfully",
"plugin_uninstall_failed" => "Failed to uninstall plugin",
"plugin_not_found" => "Plugin not found",
"plugin_no_config" => "This plugin has no configuration options",
"settings_saved" => "Plugin settings saved successfully",
"settings_save_failed" => "Failed to save plugin settings",
"enable" => "Enable",
"disable" => "Disable",
"configure" => "Configure",
"uninstall" => "Uninstall",
"no_plugins_found" => "No plugins found",
"active" => "Active",
"inactive" => "Inactive",
];

View File

@@ -0,0 +1,70 @@
<?php
namespace App\Libraries\Plugins;
use App\Models\PluginConfig;
abstract class BasePlugin implements PluginInterface
{
protected PluginConfig $configModel;
public function __construct()
{
$this->configModel = new PluginConfig();
}
public function install(): bool
{
return true;
}
public function uninstall(): bool
{
return true;
}
public function isEnabled(): bool
{
$enabled = $this->configModel->getValue("{$this->getPluginId()}_enabled");
return $enabled === '1' || $enabled === 'true';
}
protected function getSetting(string $key, mixed $default = null): mixed
{
$value = $this->configModel->getValue("{$this->getPluginId()}_{$key}");
return $value ?? $default;
}
protected function setSetting(string $key, mixed $value): bool
{
$stringValue = is_array($value) || is_object($value)
? json_encode($value)
: (string)$value;
return $this->configModel->setValue("{$this->getPluginId()}_{$key}", $stringValue);
}
public function getSettings(): array
{
return $this->configModel->getPluginSettings($this->getPluginId());
}
public function saveSettings(array $settings): bool
{
$prefixedSettings = [];
foreach ($settings as $key => $value) {
if (is_array($value) || is_object($value)) {
$prefixedSettings["{$this->getPluginId()}_{$key}"] = json_encode($value);
} else {
$prefixedSettings["{$this->getPluginId()}_{$key}"] = (string)$value;
}
}
return $this->configModel->batchSave($prefixedSettings);
}
protected function log(string $level, string $message): void
{
log_message($level, "[Plugin:{$this->getPluginName()}] {$message}");
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Libraries\Plugins;
interface PluginInterface
{
public function getPluginId(): string;
public function getPluginName(): string;
public function getPluginDescription(): string;
public function getVersion(): string;
/**
* Register event listeners for this plugin.
*
* Use Events::on() to register callbacks for OSPOS events.
* This method is called when the plugin is loaded and enabled.
*
* Example:
* Events::on('item_sale', [$this, 'onItemSale']);
* Events::on('item_change', [$this, 'onItemChange']);
*/
public function registerEvents(): void;
/**
* Install the plugin.
*
* Called when the plugin is first enabled. Use this to create database tables,
* set default configuration values, and run any setup required.
*/
public function install(): bool;
/**
* Uninstall the plugin.
*
* Called when the plugin is being removed. Use this to remove database tables,
* clean up configuration, etc.
*/
public function uninstall(): bool;
public function isEnabled(): bool;
/**
* Get the path to the plugin's configuration view file.
* Returns null if the plugin has no configuration UI.
*
* Example: 'Plugins/mailchimp/config'
*/
public function getConfigView(): ?string;
public function getSettings(): array;
public function saveSettings(array $settings): bool;
}

View File

@@ -0,0 +1,174 @@
<?php
namespace App\Libraries\Plugins;
use App\Models\PluginConfig;
use CodeIgniter\Events\Events;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class PluginManager
{
private array $plugins = [];
private array $enabledPlugins = [];
private PluginConfig $configModel;
private string $pluginsPath;
public function __construct()
{
$this->configModel = new PluginConfig();
$this->pluginsPath = APPPATH . 'Plugins';
}
public function discoverPlugins(): void
{
if (!is_dir($this->pluginsPath)) {
log_message('debug', 'Plugins directory does not exist: ' . $this->pluginsPath);
return;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($this->pluginsPath, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
if ($file->isDir() || $file->getExtension() !== 'php') {
continue;
}
$className = $this->getClassNameFromFile($file->getPathname());
if (!$className) {
continue;
}
if (!class_exists($className)) {
continue;
}
if (!is_subclass_of($className, PluginInterface::class)) {
continue;
}
$plugin = new $className();
$this->plugins[$plugin->getPluginId()] = $plugin;
log_message('debug', "Discovered plugin: {$plugin->getPluginName()}");
}
}
private function getClassNameFromFile(string $pathname): ?string
{
$relativePath = str_replace($this->pluginsPath . DIRECTORY_SEPARATOR, '', $pathname);
$relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
$className = 'App\\Plugins\\' . str_replace('.php', '', $relativePath);
return $className;
}
public function registerPluginEvents(): void
{
foreach ($this->plugins as $pluginId => $plugin) {
if ($this->isPluginEnabled($pluginId)) {
$this->enabledPlugins[$pluginId] = $plugin;
$plugin->registerEvents();
log_message('debug', "Registered events for plugin: {$plugin->getPluginName()}");
}
}
}
public function getAllPlugins(): array
{
return $this->plugins;
}
public function getEnabledPlugins(): array
{
return $this->enabledPlugins;
}
public function getPlugin(string $pluginId): ?PluginInterface
{
return $this->plugins[$pluginId] ?? null;
}
public function isPluginEnabled(string $pluginId): bool
{
$enabled = $this->configModel->getValue($this->getEnabledKey($pluginId));
return $enabled === '1' || $enabled === 'true';
}
public function enablePlugin(string $pluginId): bool
{
$plugin = $this->getPlugin($pluginId);
if (!$plugin) {
log_message('error', "Plugin not found: {$pluginId}");
return false;
}
if (!$this->configModel->exists($this->getInstalledKey($pluginId))) {
if (!$plugin->install()) {
log_message('error', "Failed to install plugin: {$pluginId}");
return false;
}
$this->configModel->setValue($this->getInstalledKey($pluginId), '1');
}
$this->configModel->setValue($this->getEnabledKey($pluginId), '1');
log_message('info', "Plugin enabled: {$pluginId}");
return true;
}
public function disablePlugin(string $pluginId): bool
{
if (!$this->getPlugin($pluginId)) {
log_message('error', "Plugin not found: {$pluginId}");
return false;
}
$this->configModel->setValue($this->getEnabledKey($pluginId), '0');
log_message('info', "Plugin disabled: {$pluginId}");
return true;
}
public function uninstallPlugin(string $pluginId): bool
{
$plugin = $this->getPlugin($pluginId);
if (!$plugin) {
log_message('error', "Plugin not found: {$pluginId}");
return false;
}
if (!$plugin->uninstall()) {
log_message('error', "Failed to uninstall plugin: {$pluginId}");
return false;
}
$this->configModel->deleteAllStartingWith($pluginId . '_');
return true;
}
public function getSetting(string $pluginId, string $key, mixed $default = null): mixed
{
return $this->configModel->getValue("{$pluginId}_{$key}") ?? $default;
}
public function setSetting(string $pluginId, string $key, mixed $value): bool
{
return $this->configModel->setValue("{$pluginId}_{$key}", $value);
}
private function getEnabledKey(string $pluginId): string
{
return "{$pluginId}_enabled";
}
private function getInstalledKey(string $pluginId): string
{
return "{$pluginId}_installed";
}
}

View File

@@ -1,191 +0,0 @@
<?php
namespace App\Libraries;
use App\Enums\RewardOperation;
use App\Models\Customer;
/**
* Reward library
*
* Handles customer reward points business logic for sales transactions.
* Extracted from Sale model to provide centralized reward management.
*/
class Reward_lib
{
private Customer $customer;
public function __construct()
{
$this->customer = model(Customer::class);
}
/**
* Calculates reward points earned for a purchase.
*
* @param float $totalAmount Total sale amount
* @param float $pointsPercent Points percentage from customer reward package
* @return float Points earned
*/
public function calculatePointsEarned(float $totalAmount, float $pointsPercent): float
{
return $totalAmount * $pointsPercent / 100;
}
/**
* Adjusts customer reward points for a sale transaction.
* Handles new sales, sale updates, and sale cancellations.
* Prevents negative balances by validating sufficient points before deduction.
*
* @param int|null $customerId Customer ID (null for walk-in customers)
* @param float $rewardAmount Amount to deduct from points (for new/updated sales)
* @param RewardOperation $operation Operation type (Deduct, Restore, or Adjust)
* @return bool Success status (false if insufficient points for deduct/adjust)
*/
public function adjustRewardPoints(?int $customerId, float $rewardAmount, RewardOperation $operation): bool
{
if (empty($customerId) || $rewardAmount == 0) {
return false;
}
$currentPoints = $this->customer->get_info($customerId)->points ?? 0;
switch ($operation) {
case RewardOperation::Deduct:
case RewardOperation::Adjust:
if ($currentPoints < $rewardAmount) {
log_message(
'warning',
'Reward_lib::adjustRewardPoints insufficient points customer_id=' . $customerId
. ' current=' . $currentPoints . ' requested=' . $rewardAmount
);
return false;
}
$this->customer->update_reward_points_value($customerId, $currentPoints - $rewardAmount);
return true;
case RewardOperation::Restore:
$this->customer->update_reward_points_value($customerId, $currentPoints + $rewardAmount);
return true;
default:
return false;
}
}
/**
* Handles reward point adjustment when customer changes on a sale.
* Restores points to previous customer, deducts from new customer.
* Prevents negative balances by capping deduction at available points.
*
* @param int|null $previousCustomerId Previous customer ID
* @param int|null $newCustomerId New customer ID
* @param float $previousRewardUsed Reward points used by previous customer
* @param float $newRewardUsed Reward points to be used by new customer
* @return array ['restored' => float, 'charged' => float, 'insufficient' => bool] Amounts restored/charged
*/
public function handleCustomerChange(?int $previousCustomerId, ?int $newCustomerId, float $previousRewardUsed, float $newRewardUsed): array
{
$result = ['restored' => 0.0, 'charged' => 0.0, 'insufficient' => false];
if ($previousCustomerId === $newCustomerId) {
return $result;
}
if (!empty($previousCustomerId) && $previousRewardUsed != 0) {
$previousPoints = $this->customer->get_info($previousCustomerId)->points ?? 0;
$this->customer->update_reward_points_value($previousCustomerId, $previousPoints + $previousRewardUsed);
$result['restored'] = $previousRewardUsed;
}
if (!empty($newCustomerId) && $newRewardUsed != 0) {
$newPoints = $this->customer->get_info($newCustomerId)->points ?? 0;
if ($newPoints < $newRewardUsed) {
log_message(
'warning',
'Reward_lib::handleCustomerChange insufficient points new_customer_id=' . $newCustomerId
. ' available=' . $newPoints . ' requested=' . $newRewardUsed
);
$result['insufficient'] = true;
}
$actualCharged = min($newPoints, $newRewardUsed);
$this->customer->update_reward_points_value($newCustomerId, max(0, $newPoints - $newRewardUsed));
$result['charged'] = $actualCharged;
}
return $result;
}
/**
* Adjusts reward points delta for same customer (e.g., payment amount changed).
* Prevents negative balances by validating sufficient points before adjustment.
*
* @param int|null $customerId Customer ID
* @param float $rewardAdjustment Difference between new and previous reward usage (positive = more used)
* @return bool Success status (false if insufficient points)
*/
public function adjustRewardDelta(?int $customerId, float $rewardAdjustment): bool
{
if (empty($customerId) || $rewardAdjustment == 0) {
return false;
}
$currentPoints = $this->customer->get_info($customerId)->points ?? 0;
if ($rewardAdjustment > 0 && $currentPoints < $rewardAdjustment) {
log_message(
'warning',
'Reward_lib::adjustRewardDelta insufficient points customer_id=' . $customerId
. ' current=' . $currentPoints . ' adjustment=' . $rewardAdjustment
);
return false;
}
$this->customer->update_reward_points_value($customerId, $currentPoints - $rewardAdjustment);
return true;
}
/**
* Validates if a customer has sufficient reward points for a purchase.
*
* @param int $customerId Customer ID
* @param float $requiredPoints Points required for purchase
* @return bool True if customer has sufficient points
*/
public function hasSufficientPoints(int $customerId, float $requiredPoints): bool
{
$currentPoints = $this->customer->get_info($customerId)->points ?? 0;
return $currentPoints >= $requiredPoints;
}
/**
* Gets current reward points for a customer.
*
* @param int $customerId Customer ID
* @return float Current points balance
*/
public function getPointsBalance(int $customerId): float
{
return $this->customer->get_info($customerId)->points ?? 0;
}
/**
* Calculates reward payment amount from a payments array.
*
* @param array $payments Array of payment data
* @param array $rewardLabels Array of valid reward payment labels (localized)
* @return float Total reward payment amount
*/
public function calculateRewardPaymentAmount(array $payments, array $rewardLabels): float
{
$totalRewardAmount = 0;
foreach ($payments as $payment) {
if (in_array($payment['payment_type'] ?? '', $rewardLabels, true)) {
$totalRewardAmount += floatval($payment['payment_amount'] ?? 0);
}
}
return $totalRewardAmount;
}
}

107
app/Models/PluginConfig.php Normal file
View File

@@ -0,0 +1,107 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class PluginConfig extends Model
{
protected $table = 'plugin_config';
protected $primaryKey = 'key';
protected $useAutoIncrement = false;
protected $useSoftDeletes = false;
protected $allowedFields = [
'key',
'value'
];
public function exists(string $key): bool
{
$builder = $this->db->table('plugin_config');
$builder->where('key', $key);
return ($builder->get()->getNumRows() === 1);
}
public function getValue(string $key): ?string
{
$builder = $this->db->table('plugin_config');
$query = $builder->getWhere(['key' => $key], 1);
if ($query->getNumRows() === 1) {
return $query->getRow()->value;
}
return null;
}
public function setValue(string $key, string $value): bool
{
$builder = $this->db->table('plugin_config');
if ($this->exists($key)) {
return $builder->update(['value' => $value], ['key' => $key]);
}
return $builder->insert(['key' => $key, 'value' => $value]);
}
public function getPluginSettings(string $pluginId): array
{
$builder = $this->db->table('plugin_config');
$builder->like('key', $pluginId . '_', 'after');
$query = $builder->get();
$settings = [];
$prefix = $pluginId . '_';
foreach ($query->getResult() as $row) {
$key = str_starts_with($row->key, $prefix)
? substr($row->key, strlen($prefix))
: $row->key;
$settings[$key] = $row->value;
}
return $settings;
}
public function deleteKey(string $key): bool
{
$builder = $this->db->table('plugin_config');
return $builder->delete(['key' => $key]);
}
public function deleteAllStartingWith(string $prefix): bool
{
$builder = $this->db->table('plugin_config');
$builder->like('key', $prefix, 'after');
return $builder->delete();
}
public function batchSave(array $data): bool
{
$success = true;
$this->db->transStart();
foreach ($data as $key => $value) {
$success &= $this->setValue($key, $value);
}
$this->db->transComplete();
return $success && $this->db->transStatus();
}
public function getAll(): array
{
$builder = $this->db->table('plugin_config');
$query = $builder->get();
$configs = [];
foreach ($query->getResult() as $row) {
$configs[$row->key] = $row->value;
}
return $configs;
}
}

View File

@@ -6,7 +6,6 @@ use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\ResultInterface;
use CodeIgniter\Model;
use App\Libraries\Sale_lib;
use App\Libraries\Reward_lib;
use Config\OSPOS;
use ReflectionException;
@@ -437,165 +436,63 @@ class Sale extends Model
*/
public function update($sale_id = null, $sale_data = null): bool
{
$previousCustomerRow = $this->db->table('sales')
->select('customer_id')
->where('sale_id', $sale_id)
->get()
->getRow();
$previousCustomerId = $previousCustomerRow ? $previousCustomerRow->customer_id : null;
log_message(
'debug',
'Sale::update start sale_id=' . $sale_id . ' previous_customer_id=' . ($previousCustomerId ?? 'null')
);
$updateData = $sale_data;
unset($updateData['payments']);
$newCustomerId = array_key_exists('customer_id', $updateData)
? $updateData['customer_id']
: $previousCustomerId;
$customer = model(Customer::class);
$currentPayments = $this->get_sale_payments($sale_id)->getResultArray();
$currentRewardUsed = 0;
foreach ($currentPayments as $payment) {
if ($this->isRewardPayment($payment['payment_type'])) {
$currentRewardUsed += $payment['payment_amount'];
}
}
log_message(
'debug',
'Sale::update current rewards sale_id=' . $sale_id
. ' current_reward_used=' . $currentRewardUsed
. ' payment_count=' . count($currentPayments)
);
$newRewardUsed = 0;
if (!empty($sale_data['payments'])) {
foreach ($sale_data['payments'] as $payment) {
if ($this->isRewardPayment($payment['payment_type'])) {
$newRewardUsed += $payment['payment_amount'];
}
}
} else {
$newRewardUsed = $currentRewardUsed;
}
log_message(
'debug',
'Sale::update new rewards sale_id=' . $sale_id
. ' new_reward_used=' . $newRewardUsed
. ' payment_count=' . count($sale_data['payments'] ?? [])
);
$this->db->transStart();
$builder = $this->db->table('sales');
$builder->where('sale_id', $sale_id);
$success = $builder->update($updateData);
$update_data = $sale_data;
unset($update_data['payments']);
$success = $builder->update($update_data);
// Touch payment only if update sale is successful and there is a payments object otherwise the result would be to delete all the payments associated to the sale
if ($success && !empty($sale_data['payments'])) {
// Run these queries as a transaction, we want to make sure we do all or nothing
$this->db->transStart();
$builder = $this->db->table('sales_payments');
// Add new payments
foreach ($sale_data['payments'] as $payment) {
$paymentId = $payment['payment_id'];
$paymentType = $payment['payment_type'];
$paymentAmount = $payment['payment_amount'];
$cashRefund = $payment['cash_refund'];
$cashAdjustment = $payment['cash_adjustment'];
$employeeId = $payment['employee_id'];
$payment_id = $payment['payment_id'];
$payment_type = $payment['payment_type'];
$payment_amount = $payment['payment_amount'];
$cash_refund = $payment['cash_refund'];
$cash_adjustment = $payment['cash_adjustment'];
$employee_id = $payment['employee_id'];
if ($paymentId == NEW_ENTRY && $paymentAmount != 0) {
$salesPaymentsData = [
if ($payment_id == NEW_ENTRY && $payment_amount != 0) {
// Add a new payment transaction
$sales_payments_data = [
'sale_id' => $sale_id,
'payment_type' => $paymentType,
'payment_amount' => $paymentAmount,
'cash_refund' => $cashRefund,
'cash_adjustment' => $cashAdjustment,
'employee_id' => $employeeId
'payment_type' => $payment_type,
'payment_amount' => $payment_amount,
'cash_refund' => $cash_refund,
'cash_adjustment' => $cash_adjustment,
'employee_id' => $employee_id
];
$success = $builder->insert($salesPaymentsData);
} elseif ($paymentId != NEW_ENTRY) {
if ($paymentAmount != 0) {
$salesPaymentsData = [
'payment_type' => $paymentType,
'payment_amount' => $paymentAmount,
'cash_refund' => $cashRefund,
'cash_adjustment' => $cashAdjustment
$success = $builder->insert($sales_payments_data);
} elseif ($payment_id != NEW_ENTRY) {
if ($payment_amount != 0) {
// Update existing payment transactions (payment_type only)
$sales_payments_data = [
'payment_type' => $payment_type,
'payment_amount' => $payment_amount,
'cash_refund' => $cash_refund,
'cash_adjustment' => $cash_adjustment
];
$builder->where('payment_id', $paymentId);
$success = $builder->update($salesPaymentsData);
$builder->where('payment_id', $payment_id);
$success = $builder->update($sales_payments_data);
} else {
$success = $builder->delete(['payment_id' => $paymentId]);
// Remove existing payment transactions with a payment amount of zero
$success = $builder->delete(['payment_id' => $payment_id]);
}
}
}
$this->db->transComplete();
$success &= $this->db->transStatus();
}
if ($success) {
log_message(
'debug',
'Sale::update reward adjust sale_id=' . $sale_id
. ' previous_customer_id=' . ($previousCustomerId ?? 'null')
. ' new_customer_id=' . ($newCustomerId ?? 'null')
. ' current_reward_used=' . $currentRewardUsed
. ' new_reward_used=' . $newRewardUsed
);
if ($previousCustomerId != $newCustomerId) {
if (!empty($previousCustomerId) && $currentRewardUsed != 0) {
$previousPoints = $customer->get_info($previousCustomerId)->points ?? 0;
$customer->update_reward_points_value($previousCustomerId, $previousPoints + $currentRewardUsed);
log_message(
'debug',
'Sale::update reward restore previous_customer_id=' . $previousCustomerId
. ' previous_points=' . $previousPoints
. ' restored=' . $currentRewardUsed
);
}
if (!empty($newCustomerId) && $newRewardUsed != 0) {
$newPoints = $customer->get_info($newCustomerId)->points ?? 0;
if ($newPoints < $newRewardUsed) {
log_message(
'warning',
'Sale::update insufficient points new_customer_id=' . $newCustomerId
. ' available=' . $newPoints . ' requested=' . $newRewardUsed
);
}
$customer->update_reward_points_value($newCustomerId, max(0, $newPoints - $newRewardUsed));
log_message(
'debug',
'Sale::update reward charge new_customer_id=' . $newCustomerId
. ' new_points=' . $newPoints
. ' charged=' . $newRewardUsed
);
}
} else {
$rewardAdjustment = $newRewardUsed - $currentRewardUsed;
if ($rewardAdjustment != 0 && !empty($newCustomerId)) {
$currentPoints = $customer->get_info($newCustomerId)->points ?? 0;
if ($rewardAdjustment > 0 && $currentPoints < $rewardAdjustment) {
log_message(
'warning',
'Sale::update insufficient points customer_id=' . $newCustomerId
. ' current=' . $currentPoints . ' adjustment=' . $rewardAdjustment
);
}
$customer->update_reward_points_value($newCustomerId, $currentPoints - $rewardAdjustment);
log_message(
'debug',
'Sale::update reward delta new_customer_id=' . $newCustomerId
. ' current_points=' . $currentPoints
. ' reward_adjustment=' . $rewardAdjustment
);
}
}
}
$this->db->transComplete();
return $success && $this->db->transStatus();
return $success;
}
/**
@@ -635,7 +532,7 @@ class Sale extends Model
return -1; // TODO: Replace -1 with a constant
}
$salesData = [
$sales_data = [
'sale_time' => date('Y-m-d H:i:s'),
'customer_id' => $customer->exists($customer_id) ? $customer_id : null,
'employee_id' => $employee_id,
@@ -648,30 +545,35 @@ class Sale extends Model
'sale_type' => $sale_type
];
// Run these queries as a transaction, we want to make sure we do all or nothing
$this->db->transStart();
if ($sale_id == NEW_ENTRY) {
$builder = $this->db->table('sales');
$builder->insert($salesData);
$builder->insert($sales_data);
$sale_id = $this->db->insertID();
} else {
$builder = $this->db->table('sales');
$builder->where('sale_id', $sale_id);
$builder->update($salesData);
$builder->update($sales_data);
}
$totalAmount = 0;
$totalAmountUsed = 0;
$total_amount = 0;
$total_amount_used = 0;
foreach ($payments as $payment) {
$totalAmountUsed += $this->processPaymentType(
$payment,
$customer_id,
$customer,
$giftcard
);
foreach ($payments as $payment_id => $payment) {
if (!empty(strstr($payment['payment_type'], lang('Sales.giftcard')))) {
// We have a gift card, and we have to deduct the used value from the total value of the card.
$splitpayment = explode(':', $payment['payment_type']); // TODO: this variable doesn't follow our naming conventions. Probably should be refactored to split_payment.
$cur_giftcard_value = $giftcard->get_giftcard_value($splitpayment[1]); // TODO: this should be refactored to $current_giftcard_value
$giftcard->update_giftcard_value($splitpayment[1], $cur_giftcard_value - $payment['payment_amount']);
} elseif (!empty(strstr($payment['payment_type'], lang('Sales.rewards')))) {
$cur_rewards_value = $customer->get_info($customer_id)->points;
$customer->update_reward_points_value($customer_id, $cur_rewards_value - $payment['payment_amount']);
$total_amount_used = floatval($total_amount_used) + floatval($payment['payment_amount']);
}
$salesPaymentsData = [
$sales_payments_data = [
'sale_id' => $sale_id,
'payment_type' => $payment['payment_type'],
'payment_amount' => $payment['payment_amount'],
@@ -681,71 +583,74 @@ class Sale extends Model
];
$builder = $this->db->table('sales_payments');
$builder->insert($salesPaymentsData);
$builder->insert($sales_payments_data);
$totalAmount = floatval($totalAmount) + floatval($payment['payment_amount']) - floatval($payment['cash_refund']);
$total_amount = floatval($total_amount) + floatval($payment['payment_amount']) - floatval($payment['cash_refund']);
}
$this->save_customer_rewards($customer_id, $sale_id, $totalAmount, $totalAmountUsed);
$this->save_customer_rewards($customer_id, $sale_id, $total_amount, $total_amount_used);
$customer = $customer->get_info($customer_id);
foreach ($items as $itemData) {
$currentItemInfo = $item->get_info($itemData['item_id']);
foreach ($items as $line => $item_data) {
$cur_item_info = $item->get_info($item_data['item_id']);
if ($itemData['price'] == 0.00) {
$itemData['discount'] = 0.00;
if ($item_data['price'] == 0.00) {
$item_data['discount'] = 0.00;
}
$salesItemsData = [
$sales_items_data = [
'sale_id' => $sale_id,
'item_id' => $itemData['item_id'],
'line' => $itemData['line'],
'description' => character_limiter($itemData['description'], 255),
'serialnumber' => character_limiter($itemData['serialnumber'], 30),
'quantity_purchased' => $itemData['quantity'],
'discount' => $itemData['discount'],
'discount_type' => $itemData['discount_type'],
'item_cost_price' => $itemData['cost_price'],
'item_unit_price' => $itemData['price'],
'item_location' => $itemData['item_location'],
'print_option' => $itemData['print_option']
'item_id' => $item_data['item_id'],
'line' => $item_data['line'],
'description' => character_limiter($item_data['description'], 255),
'serialnumber' => character_limiter($item_data['serialnumber'], 30),
'quantity_purchased' => $item_data['quantity'],
'discount' => $item_data['discount'],
'discount_type' => $item_data['discount_type'],
'item_cost_price' => $item_data['cost_price'],
'item_unit_price' => $item_data['price'],
'item_location' => $item_data['item_location'],
'print_option' => $item_data['print_option']
];
$builder = $this->db->table('sales_items');
$builder->insert($salesItemsData);
$builder->insert($sales_items_data);
if ($currentItemInfo->stock_type == HAS_STOCK && $sale_status == COMPLETED) {
$itemQuantityData = $item_quantity->get_item_quantity($itemData['item_id'], $itemData['item_location']);
if ($cur_item_info->stock_type == HAS_STOCK && $sale_status == COMPLETED) { // TODO: === ?
// Update stock quantity if item type is a standard stock item and the sale is a standard sale
$item_quantity_data = $item_quantity->get_item_quantity($item_data['item_id'], $item_data['item_location']);
$item_quantity->save_value(
[
'quantity' => $itemQuantityData->quantity - $itemData['quantity'],
'item_id' => $itemData['item_id'],
'location_id' => $itemData['item_location']
'quantity' => $item_quantity_data->quantity - $item_data['quantity'],
'item_id' => $item_data['item_id'],
'location_id' => $item_data['item_location']
],
$itemData['item_id'],
$itemData['item_location']
$item_data['item_id'],
$item_data['item_location']
);
if ($itemData['quantity'] < 0) {
$item->undelete($itemData['item_id']);
// If an items was deleted but later returned it's restored with this rule
if ($item_data['quantity'] < 0) {
$item->undelete($item_data['item_id']);
}
$saleRemarks = 'POS ' . $sale_id;
$inventoryData = [
// Inventory Count Details
$sale_remarks = 'POS ' . $sale_id; // TODO: Use string interpolation here.
$inv_data = [
'trans_date' => date('Y-m-d H:i:s'),
'trans_items' => $itemData['item_id'],
'trans_items' => $item_data['item_id'],
'trans_user' => $employee_id,
'trans_location' => $itemData['item_location'],
'trans_comment' => $saleRemarks,
'trans_inventory' => -$itemData['quantity']
'trans_location' => $item_data['item_location'],
'trans_comment' => $sale_remarks,
'trans_inventory' => -$item_data['quantity']
];
$inventory->insert($inventoryData, false);
$inventory->insert($inv_data, false);
}
$attribute->copy_attribute_links($itemData['item_id'], 'sale_id', $sale_id);
$attribute->copy_attribute_links($item_data['item_id'], 'sale_id', $sale_id);
}
if ($customer_id == NEW_ENTRY || $customer->taxable) {
@@ -874,71 +779,45 @@ class Sale extends Model
*/
public function delete($sale_id = null, bool $purge = false, bool $update_inventory = true, $employee_id = null): bool
{
// Start a transaction to assure data integrity
$this->db->transStart();
$sale_status = $this->get_sale_status($sale_id);
if ($update_inventory && $sale_status == COMPLETED) {
// Defect, not all item deletions will be undone?
// Get array with all the items involved in the sale to update the inventory tracking
$inventory = model('Inventory');
$item = model(Item::class);
$itemQuantity = model(Item_quantity::class);
$item_quantity = model(Item_quantity::class);
$items = $this->get_sale_items($sale_id)->getResultArray();
foreach ($items as $itemData) {
$currentItemInfo = $item->get_info($itemData['item_id']);
foreach ($items as $item_data) {
$cur_item_info = $item->get_info($item_data['item_id']);
if ($currentItemInfo->stock_type == HAS_STOCK) {
$inventoryData = [
if ($cur_item_info->stock_type == HAS_STOCK) {
// Create query to update inventory tracking
$inv_data = [
'trans_date' => date('Y-m-d H:i:s'),
'trans_items' => $itemData['item_id'],
'trans_items' => $item_data['item_id'],
'trans_user' => $employee_id,
'trans_comment' => 'Deleting sale ' . $sale_id,
'trans_location' => $itemData['item_location'],
'trans_inventory' => $itemData['quantity_purchased']
'trans_location' => $item_data['item_location'],
'trans_inventory' => $item_data['quantity_purchased']
];
$inventory->insert($inventoryData, false);
// Update inventory
$inventory->insert($inv_data, false);
$itemQuantity->change_quantity($itemData['item_id'], $itemData['item_location'], $itemData['quantity_purchased']);
}
}
}
if ($sale_status !== CANCELED) {
$payments = $this->get_sale_payments($sale_id)->getResultArray();
$rewardUsed = 0;
foreach ($payments as $payment) {
if ($this->isRewardPayment($payment['payment_type'])) {
$rewardUsed += $payment['payment_amount'];
}
}
log_message(
'debug',
'Sale::delete reward usage sale_id=' . $sale_id
. ' reward_used=' . $rewardUsed
. ' payment_count=' . count($payments)
);
if ($rewardUsed > 0) {
$customerObj = $this->get_customer($sale_id);
if (empty($customerObj) || empty($customerObj->person_id)) {
log_message('error', 'Sale::delete cannot restore rewards - no customer for sale_id=' . $sale_id);
} else {
$customerId = $customerObj->person_id;
$customer = model(Customer::class);
$currentPoints = $customer->get_info($customerId)->points ?? 0;
$customer->update_reward_points_value($customerId, $currentPoints + $rewardUsed);
log_message(
'debug',
'Sale::delete reward restore customer_id=' . $customerId
. ' current_points=' . $currentPoints
. ' restored=' . $rewardUsed
);
// Update quantities
$item_quantity->change_quantity($item_data['item_id'], $item_data['item_location'], $item_data['quantity_purchased']);
}
}
}
$this->update_sale_status($sale_id, CANCELED);
// Execute transaction
$this->db->transComplete();
return $this->db->transStatus();
@@ -1508,94 +1387,6 @@ class Sale extends Model
}
}
/**
* Determines if the payment type represents a rewards payment across locales.
*/
private function isRewardPayment(string $payment_type): bool
{
if ($payment_type === '') {
return false;
}
foreach ($this->getRewardPaymentLabels() as $label) {
if ($payment_type === $label) {
return true;
}
}
return false;
}
/**
* Returns unique localized labels for the rewards payment type.
*/
private function getRewardPaymentLabels(): array
{
static $labels = null;
if ($labels !== null) {
return $labels;
}
$labels = [lang('Sales.rewards')];
$languagePaths = glob(APPPATH . 'Language/*/Sales.php');
if (!empty($languagePaths)) {
foreach ($languagePaths as $salesFile) {
if (!is_file($salesFile)) {
continue;
}
$translations = require $salesFile;
if (is_array($translations) && !empty($translations['rewards'])) {
$labels[] = $translations['rewards'];
}
}
}
$labels = array_map('trim', $labels);
$labels = array_filter($labels, static fn($label) => $label !== '');
$labels = array_values(array_unique($labels));
return $labels;
}
/**
* Processes payment type for giftcard and reward deductions during sale creation.
* Returns the amount used for rewards (0 for giftcards).
*/
private function processPaymentType(array $payment, int $customerId, object $customer, object $giftcard): float
{
$paymentType = $payment['payment_type'];
$paymentAmount = $payment['payment_amount'];
if (!empty(strstr($paymentType, lang('Sales.giftcard')))) {
$splitPayment = explode(':', $paymentType);
if (count($splitPayment) < 2 || empty($splitPayment[1])) {
log_message('error', 'Sale::processPaymentType invalid giftcard format: ' . $paymentType);
return 0;
}
$giftcardNumber = $splitPayment[1];
$currentGiftcardValue = $giftcard->get_giftcard_value($giftcardNumber);
$giftcard->update_giftcard_value($giftcardNumber, $currentGiftcardValue - $paymentAmount);
return 0;
}
if ($this->isRewardPayment($paymentType)) {
$currentRewardsValue = $customer->get_info($customerId)->points ?? 0;
if ($currentRewardsValue < $paymentAmount) {
log_message(
'warning',
'Sale::processPaymentType insufficient points customer_id=' . $customerId
. ' available=' . $currentRewardsValue . ' requested=' . $paymentAmount
);
}
$customer->update_reward_points_value($customerId, max(0, $currentRewardsValue - $paymentAmount));
return floatval($paymentAmount);
}
return 0;
}
/**
* Creates a temporary table to store the sales_payments data
*

View File

@@ -0,0 +1,193 @@
<?php
namespace App\Plugins;
use App\Libraries\Plugins\BasePlugin;
use App\Libraries\Mailchimp_lib;
use CodeIgniter\Events\Events;
/**
* Plugin that integrates OSPOS with Mailchimp for customer newsletter subscriptions.
*/
class MailchimpPlugin extends BasePlugin
{
private ?Mailchimp_lib $mailchimpLib = null;
public function getPluginId(): string
{
return 'mailchimp';
}
public function getPluginName(): string
{
return 'Mailchimp';
}
public function getPluginDescription(): string
{
return $this->lang('mailchimp_description');
}
public function getVersion(): string
{
return '1.0.0';
}
public function registerEvents(): void
{
Events::on('customer_saved', [$this, 'onCustomerSaved']);
Events::on('customer_deleted', [$this, 'onCustomerDeleted']);
log_message('debug', 'Mailchimp plugin events registered');
}
public function install(): bool
{
log_message('info', 'Installing Mailchimp plugin');
$this->setSetting('api_key', '');
$this->setSetting('list_id', '');
$this->setSetting('sync_on_save', '1');
$this->setSetting('enabled', '0');
return true;
}
public function uninstall(): bool
{
log_message('info', 'Uninstalling Mailchimp plugin');
return true;
}
public function getConfigView(): ?string
{
return 'Plugins/mailchimp/config';
}
public function getSettings(): array
{
return [
'api_key' => $this->getSetting('api_key', ''),
'list_id' => $this->getSetting('list_id', ''),
'sync_on_save' => $this->getSetting('sync_on_save', '1'),
'enabled' => $this->getSetting('enabled', '0'),
];
}
public function saveSettings(array $settings): bool
{
if (isset($settings['api_key'])) {
$this->setSetting('api_key', $settings['api_key']);
}
if (isset($settings['list_id'])) {
$this->setSetting('list_id', $settings['list_id']);
}
if (isset($settings['sync_on_save'])) {
$this->setSetting('sync_on_save', $settings['sync_on_save'] ? '1' : '0');
}
return true;
}
public function onCustomerSaved(array $customerData): void
{
if (!$this->shouldSyncOnSave()) {
return;
}
log_message('debug', "Customer saved event received for ID: {$customerData['person_id']}");
try {
$this->subscribeCustomer($customerData);
} catch (\Exception $e) {
log_message('error', "Failed to sync customer to Mailchimp: {$e->getMessage()}");
}
}
public function onCustomerDeleted(int $customerId): void
{
log_message('debug', "Customer deleted event received for ID: {$customerId}");
}
private function subscribeCustomer(array $customerData): bool
{
$apiKey = $this->getSetting('api_key');
$listId = $this->getSetting('list_id');
if (empty($apiKey) || empty($listId)) {
log_message('warning', 'Mailchimp API key or List ID not configured');
return false;
}
if (empty($customerData['email'])) {
log_message('debug', 'Customer has no email, skipping Mailchimp sync');
return false;
}
$mailchimp = $this->getMailchimpLib(['api_key' => $apiKey]);
$result = $mailchimp->addOrUpdateMember(
$listId,
$customerData['email'],
$customerData['first_name'] ?? '',
$customerData['last_name'] ?? '',
'subscribed'
);
if ($result) {
log_message('info', "Successfully subscribed customer ID {$customerData['person_id']} to Mailchimp");
return true;
}
return false;
}
private function shouldSyncOnSave(): bool
{
return $this->getSetting('sync_on_save', '1') === '1';
}
private function getMailchimpLib(array $params = []): Mailchimp_lib
{
if ($this->mailchimpLib === null) {
$this->mailchimpLib = new Mailchimp_lib($params);
}
return $this->mailchimpLib;
}
public function testConnection(): array
{
$apiKey = $this->getSetting('api_key');
if (empty($apiKey)) {
return ['success' => false, 'message' => $this->lang('mailchimp_api_key_required')];
}
$mailchimp = $this->getMailchimpLib(['api_key' => $apiKey]);
$result = $mailchimp->getLists();
if ($result && isset($result['lists'])) {
return [
'success' => true,
'message' => $this->lang('mailchimp_key_successfully'),
'lists' => $result['lists']
];
}
return ['success' => false, 'message' => $this->lang('mailchimp_key_unsuccessfully')];
}
protected function lang(string $key, array $data = []): string
{
$language = \Config\Services::language();
$language->addLanguagePath(APPPATH . 'Plugins/MailchimpPlugin/Language/');
return $language->getLine($key, $data);
}
protected function getPluginDir(): string
{
return 'MailchimpPlugin';
}
}

View File

@@ -0,0 +1,13 @@
<?php
return [
'mailchimp' => 'Mailchimp',
'mailchimp_description' => 'Integrate with Mailchimp to sync customers to mailing lists when they are created or updated.',
'mailchimp_api_key' => 'Mailchimp API Key',
'mailchimp_api_key_required' => 'API key not configured',
'mailchimp_configuration' => 'Mailchimp Configuration',
'mailchimp_key_successfully' => 'API Key is valid.',
'mailchimp_key_unsuccessfully' => 'API Key is invalid.',
'mailchimp_lists' => 'Mailchimp List(s)',
'mailchimp_tooltip' => 'Click the icon for an API Key.',
];

528
app/Plugins/README.md Normal file
View File

@@ -0,0 +1,528 @@
# OSPOS Plugin System
## Overview
The OSPOS Plugin System allows third-party integrations to extend the application's functionality without modifying core code. Plugins can listen to events, add configuration settings, and integrate with external services.
## Installation
### Self-Contained Plugin Packages
Plugins are self-contained packages that can be installed by simply dropping the plugin folder into `app/Plugins/`:
```
app/Plugins/
├── MailchimpPlugin/ # Plugin directory (self-contained)
│ ├── MailchimpPlugin.php # Main plugin class (required - must match directory name)
│ ├── Language/ # Plugin-specific translations (self-contained)
│ │ ├── en/
│ │ │ └── MailchimpPlugin.php
│ │ └── es-ES/
│ │ └── MailchimpPlugin.php
│ └── Views/ # Plugin-specific views
│ └── config.php
```
### Installation Steps
1. **Download the plugin** - Copy the plugin folder/file to `app/Plugins/`
2. **Auto-discovery** - The plugin will be automatically discovered on next page load
3. **Enable** - Enable it from the admin interface (Plugins menu)
4. **Configure** - Configure plugin settings if needed
### Plugin Discovery
The PluginManager recursively scans `app/Plugins/` directory:
- **Single-file plugins**: `app/Plugins/MyPlugin.php` with namespace `App\Plugins\MyPlugin`
- **Directory plugins**: `app/Plugins/MyPlugin/MyPlugin.php` with namespace `App\Plugins\MyPlugin\MyPlugin`
Both formats are supported, but directory plugins allow for self-contained packages with their own components.
## Architecture
### Plugin Interface
All plugins must implement `App\Libraries\Plugins\PluginInterface`:
```php
interface PluginInterface
{
public function getPluginId(): string; // Unique identifier
public function getPluginName(): string; // Display name
public function getPluginDescription(): string;
public function getVersion(): string;
public function registerEvents(): void; // Register event listeners
public function install(): bool; // First-time setup
public function uninstall(): bool; // Cleanup
public function isEnabled(): bool;
public function getConfigView(): ?string; // Configuration view path
public function getSettings(): array;
public function saveSettings(array $settings): bool;
}
```
### Base Plugin Class
Extend `App\Libraries\Plugins\BasePlugin` for common functionality:
```php
class MyPlugin extends BasePlugin
{
public function getPluginId(): string { return 'my_plugin'; }
public function getPluginName(): string { return 'My Plugin'; }
// ... implement other methods
}
```
### Plugin Manager
The `PluginManager` class handles:
- Plugin discovery from `app/Plugins/` directory (recursive scan)
- Loading and registering enabled plugins
- Managing plugin settings
**Important:** The PluginManager only calls `registerEvents()` for enabled plugins. Disabled plugins never have their event callbacks registered with `Events::on()`. This means **you do not need to check `$this->isEnabled()` in your callback methods** - if the callback is registered, the plugin is enabled.
## Available Events
OSPOS fires these events that plugins can listen to:
| Event | Arguments | Description |
|-------|-----------|-------------|
| `item_sale` | `array $saleData` | Fired when a sale is completed |
| `item_return` | `array $returnData` | Fired when a return is processed |
| `item_change` | `int $itemId` | Fired when an item is created/updated/deleted |
| `item_inventory` | `array $inventoryData` | Fired on inventory changes |
| `items_csv_import` | `array $importData` | Fired after items CSV import |
| `customers_csv_import` | `array $importData` | Fired after customers CSV import |
## View Hooks (Injecting Plugin Content into Views)
Plugins can inject UI elements into core views using the event-based view hook system. This allows plugins to add buttons, tabs, or other content without modifying core view files.
### How It Works
1. **Core views define hook points** using the `plugin_content()` helper
2. **Plugins register listeners** for these view hooks in `registerEvents()`
3. **Content is rendered** only when the plugin is enabled
### Step 1: Adding Hook Points in Core Views
In your core view files, use the `plugin_content()` helper to define injection points:
```php
// In app/Views/sales/receipt.php
<div class="receipt-actions">
<!-- Existing buttons -->
<?= plugin_content('receipt_actions', ['sale' => $sale]) ?>
</div>
// In app/Views/customers/form.php
<ul class="nav nav-tabs">
<!-- Existing tabs -->
<?= plugin_content('customer_tabs', ['customer' => $customer]) ?>
</ul>
```
### Step 2: Plugin Registers View Hook
In your plugin class, register a listener that returns HTML content:
```php
class MailchimpPlugin extends BasePlugin
{
public function registerEvents(): void
{
Events::on('customer_saved', [$this, 'onCustomerSaved']);
// View hooks - inject content into core views
Events::on('view:customer_tabs', [$this, 'injectCustomerTab']);
}
public function injectCustomerTab(array $data): string
{
return view('Plugins/MailchimpPlugin/Views/customer_tab', $data);
}
}
```
### Plugin View Files
The plugin's view files are self-contained within the plugin directory:
```php
// app/Plugins/MailchimpPlugin/Views/customer_tab.php
<li>
<a href="#mailchimp_panel" data-toggle="tab">
<span class="glyphicon glyphicon-envelope">&nbsp;</span>
Mailchimp
</a>
</li>
```
### Helper Functions
The `plugin_helper.php` provides two functions:
```php
// Render plugin content for a hook point
plugin_content(string $section, array $data = []): string
// Check if any plugin has registered for a hook (for conditional rendering)
plugin_content_exists(string $section): bool
```
### Standard Hook Points
Core views should define these standard hook points:
| Hook Name | Location | Usage |
|-----------|----------|-------|
| `view:receipt_actions` | Receipt view action buttons | Add receipt-related buttons |
| `view:customer_tabs` | Customer form tabs | Add customer-related tabs |
| `view:item_form_buttons` | Item form action buttons | Add item-related buttons |
| `view:sales_complete` | Sale complete screen | Post-sale integration UI |
| `view:reports_menu` | Reports menu | Add custom report links |
### Benefits
- **Self-Contained**: Plugin UI stays in plugin directory
- **Conditional**: Only renders when plugin is enabled
- **Data Access**: Pass context (sale, customer, etc.) to plugin views
- **Multiple Plugins**: Multiple plugins can hook the same location
- **Clean Separation**: Core views remain unmodified
## Creating a Plugin
### Simple Plugin (Single File)
For plugins that only need to listen to events without complex UI or database tables:
```php
<?php
// app/Plugins/MyPlugin.php
namespace App\Plugins;
use App\Libraries\Plugins\BasePlugin;
use CodeIgniter\Events\Events;
class MyPlugin extends BasePlugin
{
public function getPluginId(): string
{
return 'my_plugin';
}
public function getPluginName(): string
{
return 'My Integration Plugin';
}
public function getPluginDescription(): string
{
return 'Integrates OSPOS with external service';
}
public function getVersion(): string
{
return '1.0.0';
}
public function registerEvents(): void
{
Events::on('item_sale', [$this, 'onItemSale']);
Events::on('item_change', [$this, 'onItemChange']);
}
public function onItemSale(array $saleData): void
{
log_message('info', "Processing sale: {$saleData['sale_id_num']}");
}
public function onItemChange(int $itemId): void
{
log_message('info', "Item changed: {$itemId}");
}
public function install(): bool
{
$this->setSetting('api_key', '');
$this->setSetting('enabled', '0');
return true;
}
public function getConfigView(): ?string
{
return 'Plugins/my_plugin/config';
}
}
```
### Complex Plugin (Self-Contained Directory)
For plugins that need database tables, controllers, models, and views:
```
app/Plugins/
└── MailchimpPlugin/ # Plugin directory
├── MailchimpPlugin.php # Main class - namespace: App\Plugins\MailchimpPlugin\MailchimpPlugin
├── Models/ # Plugin models
│ └── MailchimpData.php
├── Controllers/ # Plugin controllers
│ └── Dashboard.php
├── Views/ # Plugin views
│ ├── config.php
│ └── dashboard.php
├── Language/ # Plugin translations (self-contained)
│ ├── en/
│ │ └── MailchimpPlugin.php
│ └── es-ES/
│ └── MailchimpPlugin.php
└── Libraries/ # Plugin libraries
└── ApiClient.php
```
**Main Plugin Class:**
```php
<?php
// app/Plugins/MailchimpPlugin/MailchimpPlugin.php
namespace App\Plugins\MailchimpPlugin;
use App\Libraries\Plugins\BasePlugin;
use App\Plugins\MailchimpPlugin\Models\MailchimpData;
use CodeIgniter\Events\Events;
class MailchimpPlugin extends BasePlugin
{
private ?MailchimpData $dataModel = null;
public function getPluginId(): string
{
return 'mailchimp';
}
public function getPluginName(): string
{
return 'Mailchimp';
}
public function getPluginDescription(): string
{
return 'Integrate with Mailchimp to sync customers to mailing lists.';
}
public function getVersion(): string
{
return '1.0.0';
}
public function registerEvents(): void
{
Events::on('customer_saved', [$this, 'onCustomerSaved']);
Events::on('customer_deleted', [$this, 'onCustomerDeleted']);
}
private function getDataModel(): MailchimpData
{
if ($this->dataModel === null) {
$this->dataModel = new MailchimpData();
}
return $this->dataModel;
}
public function onCustomerSaved(array $customerData): void
{
if (!$this->shouldSyncOnSave()) {
return;
}
$this->getDataModel()->syncCustomer($customerData);
}
public function install(): bool
{
$this->setSetting('api_key', '');
$this->setSetting('list_id', '');
$this->setSetting('sync_on_save', '1');
return true;
}
public function uninstall(): bool
{
$this->getDataModel()->dropTable();
return true;
}
public function getConfigView(): ?string
{
return 'Plugins/MailchimpPlugin/Views/config';
}
protected function lang(string $key, array $data = []): string
{
$language = \Config\Services::language();
$language->addLanguagePath(APPPATH . 'Plugins/MailchimpPlugin/Language/');
return $language->getLine($key, $data);
}
protected function getPluginDir(): string
{
return 'MailchimpPlugin';
}
}
```
## Internationalization (Language Files)
Plugins can include their own language files, making them completely self-contained. This allows plugins to provide translations without modifying core language files.
### Plugin Language Directory Structure
```
app/Plugins/
└── MailchimpPlugin/
├── MailchimpPlugin.php
├── Language/
│ ├── en/
│ │ └── MailchimpPlugin.php # English translations
│ ├── es-ES/
│ │ └── MailchimpPlugin.php # Spanish translations
│ └── de-DE/
│ └── MailchimpPlugin.php # German translations
└── Views/
└── config.php
```
### Language File Format
Each language file returns an array of translation strings:
```php
<?php
// app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php
return [
'mailchimp' => 'Mailchimp',
'mailchimp_description' => 'Integrate with Mailchimp to sync customers to mailing lists.',
'mailchimp_api_key' => 'Mailchimp API Key',
'mailchimp_configuration' => 'Mailchimp Configuration',
'mailchimp_key_successfully' => 'API Key is valid.',
'mailchimp_key_unsuccessfully' => 'API Key is invalid.',
];
```
### Loading Language Strings in Plugins
The `BasePlugin` class can provide a helper method to load plugin-specific language strings:
```php
protected function lang(string $key, array $data = []): string
{
$language = \Config\Services::language();
$language->addLanguagePath(APPPATH . 'Plugins/' . $this->getPluginDir() . '/Language/');
return $language->getLine($key, $data);
}
protected function getPluginDir(): string
{
return 'MailchimpPlugin';
}
```
### Benefits of Self-Contained Language Files
1. **Plugin Independence**: No need to modify core language files
2. **Easy Distribution**: Plugin zip includes all translations
3. **Fallback Support**: Missing translations fall back to English
4. **User Contributions**: Users can add translations to `Language/{locale}/` in the plugin directory
## Plugin Settings
Store plugin-specific settings using:
```php
// Get setting
$value = $this->getSetting('setting_key', 'default_value');
// Set setting
$this->setSetting('setting_key', 'value');
// Get all plugin settings
$settings = $this->getSettings();
// Save multiple settings
$this->saveSettings(['key1' => 'value1', 'key2' => 'value2']);
```
Settings are prefixed with the plugin ID (e.g., `mailchimp_api_key`) and stored in `ospos_plugin_config` table.
## Namespace Reference
| File Location | Namespace |
|--------------|-----------|
| `app/Plugins/MyPlugin.php` | `App\Plugins\MyPlugin` |
| `app/Plugins/MailchimpPlugin/MailchimpPlugin.php` | `App\Plugins\MailchimpPlugin\MailchimpPlugin` |
| `app/Plugins/MailchimpPlugin/Models/MailchimpData.php` | `App\Plugins\MailchimpPlugin\Models\MailchimpData` |
| `app/Plugins/MailchimpPlugin/Controllers/Dashboard.php` | `App\Plugins\MailchimpPlugin\Controllers\Dashboard` |
| `app/Plugins/MailchimpPlugin/Libraries/ApiClient.php` | `App\Plugins\MailchimpPlugin\Libraries\ApiClient` |
| `app/Plugins/MailchimpPlugin/Language/en/MailchimpPlugin.php` | *(Language file - returns array, no namespace)* |
## Database
Plugin settings are stored in the `ospos_plugin_config` table:
```sql
CREATE TABLE IF NOT EXISTS `ospos_plugin_config` (
`key` varchar(100) NOT NULL,
`value` text NOT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
For custom tables, plugins can create them during `install()` and drop them during `uninstall()`.
## Event Flow
1. Application triggers event: `Events::trigger('item_sale', $data)`
2. PluginManager recursively scans `app/Plugins/` directory
3. Each enabled plugin registers its listeners via `registerEvents()`
4. Events::on() callbacks are invoked automatically
## Testing
Enable plugin logging to debug:
```php
log_message('debug', 'Debug message');
log_message('info', 'Info message');
log_message('error', 'Error message');
```
Check logs in `writable/logs/`.
## Distributing Plugins
Plugin developers can package their plugins as zip files:
```
MailchimpPlugin-1.0.0.zip
└── MailchimpPlugin/
├── MailchimpPlugin.php
├── Models/
├── Controllers/
├── Views/
├── Language/
│ ├── en/
│ │ └── MailchimpPlugin.php
│ └── es-ES/
│ └── MailchimpPlugin.php
└── README.md # Plugin documentation
```
Users extract the zip to `app/Plugins/` and the plugin is ready to use.

View File

@@ -0,0 +1,119 @@
<?= view('partial/header') ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<span class="glyphicon glyphicon-puzzle"></span> <?= lang('Plugins.plugin_management') ?>
</h3>
</div>
<div class="panel-body">
<?php if (empty($plugins)): ?>
<div class="alert alert-info">
<?= lang('Plugins.no_plugins_found') ?>
</div>
<?php else: ?>
<table class="table table-striped table-hover">
<thead>
<tr>
<th><?= lang('Plugins.plugin_name') ?></th>
<th><?= lang('Plugins.plugin_description') ?></th>
<th><?= lang('Plugins.plugin_version') ?></th>
<th><?= lang('Plugins.plugin_status') ?></th>
<th><?= lang('Common.actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($plugins as $pluginId => $plugin): ?>
<tr id="plugin-row-<?= esc($pluginId) ?>">
<td>
<strong><?= esc($plugin['name']) ?></strong>
<br><small class="text-muted"><?= esc($plugin['id']) ?></small>
</td>
<td><?= esc($plugin['description']) ?></td>
<td><span class="label label-default"><?= esc($plugin['version']) ?></span></td>
<td>
<?php if ($plugin['enabled']): ?>
<span class="label label-success"><?= lang('Plugins.active') ?></span>
<?php else: ?>
<span class="label label-default"><?= lang('Plugins.inactive') ?></span>
<?php endif; ?>
</td>
<td>
<?php if ($plugin['enabled']): ?>
<button class="btn btn-warning btn-xs plugin-action"
data-action="disable"
data-plugin-id="<?= esc($pluginId) ?>">
<span class="glyphicon glyphicon-pause"></span> <?= lang('Plugins.disable') ?>
</button>
<?php else: ?>
<button class="btn btn-success btn-xs plugin-action"
data-action="enable"
data-plugin-id="<?= esc($pluginId) ?>">
<span class="glyphicon glyphicon-play"></span> <?= lang('Plugins.enable') ?>
</button>
<?php endif; ?>
<?php if ($plugin['has_config'] && $plugin['enabled']): ?>
<button class="btn btn-primary btn-xs plugin-config"
data-plugin-id="<?= esc($pluginId) ?>">
<span class="glyphicon glyphicon-cog"></span> <?= lang('Plugins.configure') ?>
</button>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
<!-- Plugin Config Modal -->
<div class="modal fade" id="plugin-config-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title"><?= lang('Plugins.plugins') ?></h4>
</div>
<div class="modal-body" id="plugin-config-content">
<!-- Config form loaded dynamically -->
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.plugin-action').on('click', function() {
var btn = $(this);
var action = btn.data('action');
var pluginId = btn.data('plugin-id');
$.post('plugins/manage/' + action + '/' + pluginId, {
<?= esc(csrf_token()) ?>: '<?= esc(csrf_hash()) ?>'
}, function(response) {
if (response.success) {
$.notify({ message: response.message }, { type: 'success' });
setTimeout(function() { location.reload(); }, 1000);
} else {
$.notify({ message: response.message }, { type: 'danger' });
}
}, 'json');
});
$('.plugin-config').on('click', function() {
var pluginId = $(this).data('plugin-id');
$('#plugin-config-content').load('plugins/manage/config/' + pluginId);
$('#plugin-config-modal').modal('show');
});
});
</script>
<?= view('partial/footer') ?>

10
package-lock.json generated
View File

@@ -38,7 +38,7 @@
"jquery-form": "^4.3.0",
"jquery-ui-dist": "^1.12.1",
"jquery-validation": "^1.19.5",
"jspdf": "^4.2.0",
"jspdf": "^4.1.0",
"jspdf-autotable": "^5.0.7",
"tableexport.jquery.plugin": "^1.30.0"
},
@@ -3731,12 +3731,12 @@
"license": "MIT"
},
"node_modules/jspdf": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.0.tgz",
"integrity": "sha512-hR/hnRevAXXlrjeqU5oahOE+Ln9ORJUB5brLHHqH67A+RBQZuFr5GkbI9XQI8OUFSEezKegsi45QRpc4bGj75Q==",
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.1.0.tgz",
"integrity": "sha512-xd1d/XRkwqnsq6FP3zH1Q+Ejqn2ULIJeDZ+FTKpaabVpZREjsJKRJwuokTNgdqOU+fl55KgbvgZ1pRTSWCP2kQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.28.6",
"@babel/runtime": "^7.28.4",
"fast-png": "^6.2.0",
"fflate": "^0.8.1"
},

View File

@@ -59,7 +59,7 @@
"jquery-form": "^4.3.0",
"jquery-ui-dist": "^1.12.1",
"jquery-validation": "^1.19.5",
"jspdf": "^4.2.0",
"jspdf": "^4.1.0",
"jspdf-autotable": "^5.0.7",
"tableexport.jquery.plugin": "^1.30.0"
},

View File

@@ -1,440 +0,0 @@
<?php
namespace Tests\Libraries;
use CodeIgniter\Test\CIUnitTestCase;
use App\Enums\RewardOperation;
use App\Libraries\Reward_lib;
use App\Models\Customer;
class Reward_libTest extends CIUnitTestCase
{
use \CodeIgniter\Test\DatabaseTestTrait;
protected $migrate = true;
protected $migrateOnce = true;
protected $refresh = true;
protected $namespace = null;
private Reward_lib $rewardLib;
protected function setUp(): void
{
parent::setUp();
$this->rewardLib = new Reward_lib();
}
/**
* Test calculatePointsEarned returns correct calculation
*/
public function testCalculatePointsEarnedReturnsCorrectValue(): void
{
$pointsEarned = $this->rewardLib->calculatePointsEarned(100.00, 10);
$this->assertEquals(10.0, $pointsEarned);
}
/**
* Test calculatePointsEarned with zero amount
*/
public function testCalculatePointsEarnedWithZeroAmount(): void
{
$pointsEarned = $this->rewardLib->calculatePointsEarned(0, 10);
$this->assertEquals(0.0, $pointsEarned);
}
/**
* Test calculatePointsEarned with zero percentage
*/
public function testCalculatePointsEarnedWithZeroPercentage(): void
{
$pointsEarned = $this->rewardLib->calculatePointsEarned(100.00, 0);
$this->assertEquals(0.0, $pointsEarned);
}
/**
* Test calculatePointsEarned with percentage over 100
*/
public function testCalculatePointsEarnedWithHighPercentage(): void
{
$pointsEarned = $this->rewardLib->calculatePointsEarned(50.00, 200);
$this->assertEquals(100.0, $pointsEarned);
}
/**
* Test hasSufficientPoints returns true when customer has enough points
*/
public function testHasSufficientPointsReturnsTrueWhenSufficient(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 100]);
// Use reflection to inject mock
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->assertTrue($this->rewardLib->hasSufficientPoints(1, 50));
}
/**
* Test hasSufficientPoints returns false when customer has insufficient points
*/
public function testHasSufficientPointsReturnsFalseWhenInsufficient(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 30]);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->assertFalse($this->rewardLib->hasSufficientPoints(1, 50));
}
/**
* Test getPointsBalance returns correct balance
*/
public function testGetPointsBalanceReturnsCorrectValue(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 250]);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->assertEquals(250, $this->rewardLib->getPointsBalance(1));
}
/**
* Test calculateRewardPaymentAmount with mixed payments
*/
public function testCalculateRewardPaymentAmountWithMixedPayments(): void
{
$payments = [
['payment_type' => 'Cash', 'payment_amount' => 50],
['payment_type' => 'Rewards', 'payment_amount' => 25],
['payment_type' => 'Credit Card', 'payment_amount' => 100],
['payment_type' => 'Rewards', 'payment_amount' => 15],
];
$rewardLabels = ['Rewards', 'Points'];
$total = $this->rewardLib->calculateRewardPaymentAmount($payments, $rewardLabels);
$this->assertEquals(40.0, $total);
}
/**
* Test calculateRewardPaymentAmount with empty payments
*/
public function testCalculateRewardPaymentAmountWithEmptyPayments(): void
{
$total = $this->rewardLib->calculateRewardPaymentAmount([], ['Rewards']);
$this->assertEquals(0.0, $total);
}
/**
* Test calculateRewardPaymentAmount with no matching labels
*/
public function testCalculateRewardPaymentAmountWithNoMatchingLabels(): void
{
$payments = [
['payment_type' => 'Cash', 'payment_amount' => 50],
['payment_type' => 'Credit Card', 'payment_amount' => 100],
];
$total = $this->rewardLib->calculateRewardPaymentAmount($payments, ['Rewards']);
$this->assertEquals(0.0, $total);
}
/**
* Test adjustRewardPoints returns false for null customer
*/
public function testAdjustRewardPointsReturnsFalseForNullCustomer(): void
{
$result = $this->rewardLib->adjustRewardPoints(null, 50, RewardOperation::Deduct);
$this->assertFalse($result);
}
/**
* Test adjustRewardPoints returns false for zero amount
*/
public function testAdjustRewardPointsReturnsFalseForZeroAmount(): void
{
$result = $this->rewardLib->adjustRewardPoints(1, 0, RewardOperation::Deduct);
$this->assertFalse($result);
}
/**
* Test adjustRewardDelta returns false for null customer
*/
public function testAdjustRewardDeltaReturnsFalseForNullCustomer(): void
{
$result = $this->rewardLib->adjustRewardDelta(null, 50);
$this->assertFalse($result);
}
/**
* Test adjustRewardDelta returns false for zero adjustment
*/
public function testAdjustRewardDeltaReturnsFalseForZeroAdjustment(): void
{
$result = $this->rewardLib->adjustRewardDelta(1, 0);
$this->assertFalse($result);
}
/**
* Test handleCustomerChange with same customer returns empty result
*/
public function testHandleCustomerChangeWithSameCustomerReturnsEmpty(): void
{
$result = $this->rewardLib->handleCustomerChange(1, 1, 50.0, 75.0);
$this->assertEquals(['restored' => 0.0, 'charged' => 0.0, 'insufficient' => false], $result);
}
/**
* Test handleCustomerChange with null customers
*/
public function testHandleCustomerChangeWithNullCustomers(): void
{
$result = $this->rewardLib->handleCustomerChange(null, null, 50.0, 75.0);
$this->assertEquals(['restored' => 0.0, 'charged' => 0.0, 'insufficient' => false], $result);
}
/**
* Test handleCustomerChange when customer changes from null to valid customer
*/
public function testHandleCustomerChangeFromNullToValidCustomer(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 100]);
$customerModel->method('update_reward_points_value')
->willReturn(true);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->handleCustomerChange(null, 2, 0, 50.0);
$this->assertEquals(50.0, $result['charged']);
$this->assertEquals(0.0, $result['restored']);
}
/**
* Test update reward points correctly deducts from balance
*/
public function testPointsUpdateDuringSaleCreation(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 200]);
$customerModel->expects($this->once())
->method('update_reward_points_value')
->with(1, 150);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->rewardLib->adjustRewardPoints(1, 50, RewardOperation::Deduct);
}
/**
* Test update reward points correctly restores on sale deletion
*/
public function testPointsRestoreOnSaleDeletion(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 150]);
$customerModel->expects($this->once())
->method('update_reward_points_value')
->with(1, 200);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->rewardLib->adjustRewardPoints(1, 50, RewardOperation::Restore);
}
/**
* Test hasSufficientPoints returns true when points exactly match required
*/
public function testHasSufficientPointsReturnsTrueWhenExactMatch(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 50]);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$this->assertTrue($this->rewardLib->hasSufficientPoints(1, 50));
}
/**
* Test adjustRewardPoints returns false when insufficient points for deduct
*/
public function testAdjustRewardPointsReturnsFalseWhenInsufficientPointsForDeduct(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 30]);
$customerModel->expects($this->never())
->method('update_reward_points_value');
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->adjustRewardPoints(1, 50, RewardOperation::Deduct);
$this->assertFalse($result);
}
/**
* Test adjustRewardDelta returns false when insufficient points for positive adjustment
*/
public function testAdjustRewardDeltaReturnsFalseWhenInsufficientPoints(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 20]);
$customerModel->expects($this->never())
->method('update_reward_points_value');
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->adjustRewardDelta(1, 50);
$this->assertFalse($result);
}
/**
* Test adjustRewardDelta succeeds for negative adjustment (refund)
*/
public function testAdjustRewardDeltaSucceedsForNegativeAdjustment(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 100]);
$customerModel->expects($this->once())
->method('update_reward_points_value')
->with(1, 150);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->adjustRewardDelta(1, -50);
$this->assertTrue($result);
}
/**
* Test handleCustomerChange caps charge at available points when insufficient
*/
public function testHandleCustomerChangeCapsChargeWhenInsufficient(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 30]);
$customerModel->expects($this->once())
->method('update_reward_points_value')
->with(2, 0);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->handleCustomerChange(null, 2, 0, 50.0);
$this->assertEquals(30.0, $result['charged']);
$this->assertTrue($result['insufficient']);
}
/**
* Test handleCustomerChange does not charge when new customer has zero points
*/
public function testHandleCustomerChangeCapsChargeAtZero(): void
{
$customerModel = $this->getMockBuilder(Customer::class)
->onlyMethods(['get_info', 'update_reward_points_value'])
->getMock();
$customerModel->method('get_info')
->willReturn((object)['points' => 0]);
$customerModel->expects($this->once())
->method('update_reward_points_value')
->with(2, 0);
$reflection = new \ReflectionClass($this->rewardLib);
$property = $reflection->getProperty('customer');
$property->setAccessible(true);
$property->setValue($this->rewardLib, $customerModel);
$result = $this->rewardLib->handleCustomerChange(null, 2, 0, 50.0);
$this->assertEquals(0.0, $result['charged']);
$this->assertTrue($result['insufficient']);
}
}

View File

@@ -10,15 +10,6 @@
<testsuite name="Helpers">
<directory>helpers</directory>
</testsuite>
<testsuite name="Libraries">
<directory>Libraries</directory>
</testsuite>
<testsuite name="Models">
<directory>Models</directory>
</testsuite>
<testsuite name="Controllers">
<directory>Controllers</directory>
</testsuite>
</testsuites>
</phpunit>