This commit is contained in:
Mohammad Rezai 2025-08-05 17:24:52 +03:30
parent aaa757247a
commit 876003d0b6
106 changed files with 45778 additions and 36759 deletions

102
README.md Normal file
View file

@ -0,0 +1,102 @@
=== Hesabix for WooCommerce ===
Contributors: Mohammad Rezai
Tags: accounting, hesabix, woocommerce, jalali, invoice, integration, persian
Requires at least: 5.2
Tested up to: 6.6.1
Requires PHP: 7.4
Stable tag: 1.0.0
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
Modern, localized, and secure WooCommerce integration with Hesabix Cloud Accounting. Featuring full Jalali calendar support, real-time data sync, and advanced customization for Persian e-commerce.
== 🧩 Overview ==
**Hesabix for WooCommerce** connects your online store with [Hesabix](https://hesabix.com), the powerful cloud-based accounting system built for Persian businesses.
From real-time product, order, and customer sync to full Persian date support, this plugin is everything a modern Iranian online store needs to automate its bookkeeping.
== ✨ Features ==
### 🔗 Seamless Integration
- Automatically syncs products, orders, and customers with your Hesabix account
- One-click synchronization for bulk data
- AJAX-powered UI for responsive operations
### 📅 Persian Calendar Support
- Native Jalali calendar UI
- Gregorian ↔ Jalali date conversion
- Custom date filters and ranges
### 💼 Smart Customer Handling
- Auto-create customers in Hesabix from WooCommerce orders
- National ID, economic code, and business info fields
- Custom checkout fields with flexible validation
### 🧾 Invoice & Finance Management
- Instant invoice generation on new orders
- Freight and shipping cost handling
- Payment method mapping
### ⚙️ Developer Tools
- Clean, modular code with hooks and filters
- Extendable data mappers for products and customers
- Debug logs and status monitoring
### 🌐 Localization & UI
- Fully RTL and Persian language ready
- Modern, tabbed admin interface
- Responsive and mobile-friendly
== 🛠️ Installation & Setup ==
1. Upload the plugin to `/wp-content/plugins/hesabix-woocommerce/`
2. Activate via **Plugins > Hesabix for WooCommerce**
3. Go to **WooCommerce > Hesabix Settings**
4. Enter your API Key (get it from your [Hesabix account](https://app.hesabix.com))
5. Test connection and start syncing!
== ❓ Frequently Asked Questions ==
**How do I get an API key?**
Log in to your Hesabix account and navigate to *Settings > API*. Copy the key and paste it into the plugin settings.
**Is it compatible with Persian WooCommerce stores?**
Yes — fully RTL compatible, Persian translations included, and Jalali calendar support is native.
**Can I control what data gets synced?**
Absolutely — toggle options for each data type and use filters to customize.
**Does it work with subscription products?**
Currently designed for standard WooCommerce orders.
**Is my data safe?**
Yes — we follow WordPress best practices including nonce verification, secure API connections, and local data handling.
== 🖼️ Screenshots ==
1. Plugin Dashboard with sync status
2. Customer field customization
3. Jalali date picker for filtering
4. Invoice configuration
5. Product linking interface
== 🌐 Resources ==
- [Official Website](https://hesabix.com)
- [User Guide](https://hesabix.com/school)
- [Support](https://hesabix.com/support)
== 👨‍💻 Credits ==
**Developer**: Mohammad Rezai
**Website**: [pirouz.xyz](https://pirouz.xyz)
== 🔐 License ==
This plugin is licensed under the GPLv3. You are free to modify, distribute, and use it under the terms of the license.
== 🛡️ Privacy ==
No personal data is collected by this plugin. All communications are strictly between your WordPress site and Hesabix servers.

View file

@ -1,35 +0,0 @@
=== Hesabix Accounting ===
Contributors: saeedsb, hamidprime, sepehr-najafi, Babak alizadeh
Tags: accounting cloud Hesabix
Requires at least: 5.2
Tested up to: 6.6.1
Requires PHP: 5.6
Stable tag: 2.1.1
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Connect Hesabix Online Accounting to WooCommerce.
== Description ==
This plugin helps connect your (online) store to Hesabix online accounting software. By using this plugin, saving products, contacts, and orders in your store will also save them automatically in your Hesabix account. Besides that, just after a client pays a bill, the receipt document will be stored in Hesabix as well. Of course, you have to register your account in Hesabix first. To do so, visit Hesabix at the link here hesabix.com and sign up for free. After you signed up and entered your account, choose your business, then in the settings menu/API, you can find the API keys for the business and import them to the plugin settings. Now your module is ready to use.
For more information and a full guide to how to use Hesabix and WooCommerce Plugin, visit Hesabixs website and go to the “Accounting School” menu.
== Installation ==
1. Upload the plugin files to the `/wp-content/plugins/hesabixWCplugin` directory, or install the Hesabix plugin through the WordPress plugins screen directly.
2. Activate the plugin through the \'Plugins\' screen in WordPress
3. Use the Settings->Hesabix screen to configure the plugin
== Screenshots ==
1. API setting page
2. Catalog setting page
3. Customers setting page
4. Invoice setting page
5. Payment Methods setting page
6. Import and export setting page
7. Sync setting page
8. Log file
== Changelog ==
= 1.0.0 - 07.03.2024 =
* Initial stable release.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,105 +0,0 @@
/**
*
* Name: IRANYekan Font
* Version: 3.3
* Author: Moslem Ebrahimi (moslemebrahimi.com)
* Created on: Sep 17, 2020
* Updated on: Sep 17, 2020
* Website: http://fontiran.com
* Copyright: Commercial/Proprietary Software
--------------------------------------------------------------------------------------
فونت ایران یکان یک نرم افزار مالکیتی محسوب می شود. جهت آگاهی از قوانین استفاده از این فونت ها لطفا به وب سایت (فونت ایران دات کام) مراجعه نمایید
--------------------------------------------------------------------------------------
IRANYekan fonts are considered a proprietary software. To gain information about the laws regarding the use of these fonts, please visit www.fontiran.com
--------------------------------------------------------------------------------------
This set of fonts are used in this project under the license: (.....)
--------------------------------------------------------------------------------------
*
**/
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: bold;
src: url('../fonts/eot/iranyekanwebbold.eot');
src: url('../fonts/eot/iranyekanwebbold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebbold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebbold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebbold.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 100;
src: url('../fonts/eot/iranyekanwebthin.eot');
src: url('../fonts/eot/iranyekanwebthin.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebthin.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebthin.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebthin.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 300;
src: url('../fonts/eot/iranyekanweblight.eot');
src: url('../fonts/eot/iranyekanweblight.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanweblight.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanweblight.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanweblight.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: normal;
src: url('../fonts/eot/iranyekanwebregular.eot');
src: url('../fonts/eot/iranyekanwebregular.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebregular.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebregular.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebregular.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 500;
src: url('../fonts/eot/iranyekanwebmedium.eot');
src: url('../fonts/eot/iranyekanwebmedium.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebmedium.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebmedium.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebmedium.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 800;
src: url('../fonts/eot/iranyekanwebextrabold.eot');
src: url('../fonts/eot/iranyekanwebextrabold.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebextrabold.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebextrabold.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebextrabold.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 850;
src: url('../fonts/eot/iranyekanwebblack.eot');
src: url('../fonts/eot/iranyekanwebblack.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebblack.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebblack.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebblack.ttf') format('truetype');
}
@font-face {
font-family: iranyekan;
font-style: normal;
font-weight: 900;
src: url('../fonts/eot/iranyekanwebextrablack.eot');
src: url('../fonts/eot/iranyekanwebextrablack.eot?#iefix') format('embedded-opentype'), /* IE6-8 */
url('../fonts/woff/iranyekanwebextrablack.woff') format('woff'), /* FF3.6+, IE9, Chrome6+, Saf5.1+*/
url('../fonts/woff2/iranyekanwebextrablack.woff2') format('woff2'), /* FF39+,Chrome36+, Opera24+*/
url('../fonts/ttf/iranyekanwebextrablack.ttf') format('truetype');
}

View file

@ -1,67 +0,0 @@
* {
font-family: "Tahoma", "Calibri", sans-serif;
}
.hand {
cursor: pointer;
}
.hesabix-tab-icon {
width: 16px;
height: 16px;
margin-left: 10px;
}
a.nav-tab {
padding: 5px 10px;
font-weight: normal;
border-radius: 7px 7px 0px 0px;
}
.hesabix-tab-page-title {
color: dimgray;
}
.hesabix-f-12 {
font-size: 12pt;
}
.hesabix-f li {
font-size: 11pt;
}
.hesabix-header {
background-color: #304967;
box-shadow: 5px 5px 5px #f3f3f3;
padding: 5px;
margin-right: -20px;
}
.hesabix-header img {
height: 35px;
}
.hesabix-card {
max-width: none !important;
margin-left: 20px;
background-color: whitesmoke !important;
}
.hesabix-bold {
font-weight: bold;
}
.hesabix-plugin-tutorial-chapter {
color: dimgray;
font-weight: bold;
border-bottom: 1px solid silver;
margin-bottom: 5px;
padding-bottom: 10px;
margin-top: 10px;
}
.hesabix-plugin-tutorial-chapter:hover {
color: dodgerblue;
cursor: pointer;
}

View file

@ -1 +0,0 @@
<?php // Silence is golden

View file

@ -1,867 +0,0 @@
jQuery(function ($) {
$('.progress').hide();
'use strict';
//=====================================================================================================================
$(function () {
// AJAX - Export Products
$('#ssbhesabix_export_products').submit(function () {
// show processing status
$('#ssbhesabix-export-product-submit').attr('disabled', 'disabled');
$('#ssbhesabix-export-product-submit').removeClass('button-primary');
$('#ssbhesabix-export-product-submit').html('<i class="ofwc-spinner"></i> خروج محصولات...');
$('#ssbhesabix-export-product-submit i.spinner').show();
$('#exportProductsProgress').show();
$('#exp ortProductsProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
exportProducts(1, 1, 1, 0);
return false;
});
});
//=====================================================================================================================
function exportProducts(batch, totalBatch, total, updateCount) {
const data = {
'action': 'adminExportProducts',
'batch': batch,
'totalBatch': totalBatch,
'total': total,
'updateCount': updateCount
};
$.post(ajaxurl, data, function (response) {
if (response !== 'failed') {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#exportProductsProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
exportProducts(res.batch + 1, res.totalBatch, res.total, res.updateCount);
return false;
} else {
$('#exportProductsProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در استخراج محصولات');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Import Products
$('#ssbhesabix_import_products').submit(function () {
// show processing status
$('#ssbhesabix-import-product-submit').attr('disabled', 'disabled');
$('#ssbhesabix-import-product-submit').removeClass('button-primary');
$('#ssbhesabix-import-product-submit').html('<i class="ofwc-spinner"></i> در حال ورود کالاها از حسابیکس, لطفاً صبر کنید...');
$('#ssbhesabix-import-product-submit i.spinner').show();
$('#importProductsProgress').show();
$('#importProductsProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
importProducts(1, 1, 1, 0);
return false;
});
});
//=====================================================================================================================
function importProducts(batch, totalBatch, total, updateCount) {
var data = {
'action': 'adminImportProducts',
'batch': batch,
'totalBatch': totalBatch,
'total': total,
'updateCount': updateCount
};
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#importProductsProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
//alert('batch: ' + res.batch + ', totalBatch: ' + res.totalBatch + ', total: ' + res.total);
importProducts(res.batch + 1, res.totalBatch, res.total, res.updateCount);
return false;
} else {
$('#importProductsProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در وارد کردن محصولات');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Export Products opening quantity
$('#ssbhesabix_export_products_opening_quantity').submit(function () {
// show processing status
$('#ssbhesabix-export-product-opening-quantity-submit').attr('disabled', 'disabled');
$('#ssbhesabix-export-product-opening-quantity-submit').removeClass('button-primary');
$('#ssbhesabix-export-product-opening-quantity-submit').html('<i class="ofwc-spinner"></i> استخراج موجودی اول دوره...');
$('#ssbhesabix-export-product-opening-quantity-submit i.spinner').show();
$('#exportProductsOpeningQuantityProgress').show();
$('#exportProductsOpeningQuantityProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
exportProductsOpeningQuantity(1, 1, 1);
return false;
});
});
function exportProductsOpeningQuantity(batch, totalBatch, total) {
var data = {
'action': 'adminExportProductsOpeningQuantity',
'batch': batch,
'totalBatch': totalBatch,
'total': total
};
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#exportProductsOpeningQuantityProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
exportProductsOpeningQuantity(res.batch + 1, res.totalBatch, res.total);
return false;
} else {
$('#exportProductsOpeningQuantityProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در استخراج موجودی اول دوره');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Export Customers
$('#ssbhesabix_export_customers').submit(function () {
// show processing status
$('#ssbhesabix-export-customer-submit').attr('disabled', 'disabled');
$('#ssbhesabix-export-customer-submit').removeClass('button-primary');
$('#ssbhesabix-export-customer-submit').html('<i class="ofwc-spinner"></i> خروجی مشتریان، لطفاً صبر کنید...');
$('#ssbhesabix-export-customer-submit i.spinner').show();
$('#exportCustomersProgress').show();
$('#exportCustomersProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
exportCustomers(1, 1, 1, 0);
return false;
});
});
function exportCustomers(batch, totalBatch, total, updateCount) {
const data = {
'action': 'adminExportCustomers',
'batch': batch,
'totalBatch': totalBatch,
'total': total,
'updateCount': updateCount
};
$.post(ajaxurl, data, function (response) {
if (response !== 'failed') {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#exportCustomersProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
exportCustomers(res.batch + 1, res.totalBatch, res.total, res.updateCount);
return false;
} else {
$('#exportCustomersProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در استخراج مشتریان');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Sync Changes
$('#ssbhesabix_sync_changes').submit(function () {
// show processing status
$('#ssbhesabix-sync-changes-submit').attr('disabled', 'disabled');
$('#ssbhesabix-sync-changes-submit').removeClass('button-primary');
$('#ssbhesabix-sync-changes-submit').html('<i class="ofwc-spinner"></i> همسان سازی تغییرات...');
$('#ssbhesabix-sync-changes-submit i.spinner').show();
var data = {
'action': 'adminSyncChanges'
};
// post it
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
var redirectUrl = response;
/** Debug **/
// console.log(redirectUrl);
// return false;
top.location.replace(redirectUrl);
return false;
} else {
alert('خطا در همگام سازی تغییرات');
return false;
}
});
/*End Post*/
return false;
});
});
//=====================================================================================================================
$(function () {
// AJAX - Sync Products
$('#ssbhesabix_sync_products').submit(function () {
// show processing status
$('#ssbhesabix-sync-products-submit').attr('disabled', 'disabled');
$('#ssbhesabix-sync-products-submit').removeClass('button-primary');
$('#ssbhesabix-sync-products-submit').html('<i class="ofwc-spinner"></i> همسان سازی محصولات...');
$('#ssbhesabix-sync-products-submit i.spinner').show();
$('#syncProductsProgress').show();
$('#syncProductsProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
syncProducts(1, 1, 1);
return false;
});
});
//=====================================================================================================================
function syncProducts(batch, totalBatch, total) {
const data = {
'action': 'adminSyncProducts',
'batch': batch,
'totalBatch': totalBatch,
'total': total
};
//$.post(URL, DATA, CALLBACK)
$.post(ajaxurl, data, function (response) {
if (response !== 'failed') {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#syncProductsProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
//alert('batch: ' + res.batch + ', totalBatch: ' + res.totalBatch + ', total: ' + res.total);
syncProducts(res.batch + 1, res.totalBatch, res.total);
return false;
} else {
$('#syncProductsProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در همگام سازی محصولات');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Sync Orders
$('#ssbhesabix_sync_orders').submit(function () {
// show processing status
$('#ssbhesabix-sync-orders-submit').attr('disabled', 'disabled');
$('#ssbhesabix-sync-orders-submit').removeClass('button-primary');
$('#ssbhesabix-sync-orders-submit').html('<i class="ofwc-spinner"></i> همسان سازی سفارشات...');
$('#ssbhesabix-sync-orders-submit i.spinner').show();
$('#syncOrdersProgress').show();
$('#syncOrdersProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
syncOrders(1, 1, 1, 0);
return false;
});
});
function syncOrders(batch, totalBatch, total, updateCount) {
var date = $('#ssbhesabix_sync_order_date').val();
var endDate = $('#ssbhesabix_sync_order_end_date').val();
const data = {
'action': 'adminSyncOrders',
'date': date,
'endDate': endDate,
'batch': batch,
'totalBatch': totalBatch,
'total': total,
'updateCount': updateCount,
};
$.post(ajaxurl, data, function (response) {
if (response !== 'failed') {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if(res.batch) $('#syncOrdersStatistics').html(`<div>پارت: ${res.batch} از ${res.totalBatch} - تعداد کل: ${res.total}</div>`);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#syncOrdersProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
syncOrders(res.batch + 1, res.totalBatch, res.total, res.updateCount);
return false;
} else {
$('#syncOrdersProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در همگام سازی سفارشات');
return false;
}
});
}
//=====================================================================================================================
$(function () {
// AJAX - Sync Products
$('#ssbhesabix_update_products').submit(function () {
// show processing status
$('#ssbhesabix-update-products-submit').attr('disabled', 'disabled');
$('#ssbhesabix-update-products-submit').removeClass('button-primary');
$('#ssbhesabix-update-products-submit').html('<i class="ofwc-spinner"></i> بروزرسانی محصولات...');
$('#ssbhesabix-update-products-submit i.spinner').show();
$('#updateProductsProgress').show();
$('#updateProductsProgressBar').css('width', 0 + '%').attr('aria-valuenow', 0);
updateProducts(1, 1, 1);
return false;
});
});
//=====================================================================================================================
function updateProducts(batch, totalBatch, total) {
var data = {
'action': 'adminUpdateProducts',
'batch': batch,
'totalBatch': totalBatch,
'total': total
};
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
const res = JSON.parse(response);
res.batch = parseInt(res.batch);
if (res.batch < res.totalBatch) {
let progress = (res.batch * 100) / res.totalBatch;
progress = Math.round(progress);
$('#updateProductsProgressBar').css('width', progress + '%').attr('aria-valuenow', progress);
updateProducts(res.batch + 1, res.totalBatch, res.total);
return false;
} else {
$('#updateProductsProgressBar').css('width', 100 + '%').attr('aria-valuenow', 100);
setTimeout(() => {
top.location.replace(res.redirectUrl);
}, 1000);
return false;
}
} else {
alert('خطا در بروزرسانی محصولات');
return false;
}
});
}
//=====================================================================================================================
// $(function () {
// // AJAX - Sync Products with ID filter
// $('#ssbhesabix_update_products_with_filter').submit(function (e) {
//
// // Show processing status
// var submitButton = $('#ssbhesabix-update-products-with-filter-submit');
// submitButton.removeClass('button-primary');
// submitButton.html('<i class="ofwc-spinner"></i> بروزرسانی محصولات...');
// });
// });
$(function () {
// AJAX - Sync Products
$('#ssbhesabix_update_products_with_filter').submit(function () {
let submitButton = $('#ssbhesabix-update-products-with-filter-submit');
let offset = document.getElementById("ssbhesabix-update-products-offset").value;
let rpp = document.getElementById("ssbhesabix-update-products-rpp").value;
submitButton.removeClass('button-primary');
submitButton.html('<i class="ofwc-spinner"></i> بروزرسانی محصولات لطفا صبر کنید...');
$('#ssbhesabix-update-products-with-filter-submit').attr('disabled', 'disabled');
updateProductsWithFilter(offset, rpp);
return false;
});
});
//=====================================================================================================================
function updateProductsWithFilter(offset, rpp) {
var data = {
'action': 'adminUpdateProductsWithFilter',
'offset': offset,
'rpp': rpp,
};
if(offset && rpp) {
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
const res = JSON.parse(response);
if(!res.error) {
top.location.replace(res.redirectUrl);
}
} else {
alert('خطا در بروزرسانی محصولات');
return false;
}
});
} else {
alert('فیلد ها را به درستی وارد نمایید');
submitButton.addClass('button-primary');
submitButton.html('بروزرسانی محصولات در حسابیکس بر اساس فروشگاه در بازه ID مشخص شده');
$('#ssbhesabix-update-products-with-filter-submit').removeAttr('disabled');
return false;
}
}
//=====================================================================================================================
$(function () {
// AJAX - Clean log
$('#ssbhesabix_clean_log').submit(function (e) {
// show processing status
$('#ssbhesabix-log-clean-submit').attr('disabled', 'disabled');
$('#ssbhesabix-log-clean-submit').removeClass('button-primary');
$('#ssbhesabix-log-clean-submit').html('<i class="ofwc-spinner"></i> پاک کردن فایل لاگ، لطفاً صبر کنید...');
$('#ssbhesabix-log-clean-submit i.spinner').show();
var data = {
'action': 'adminCleanLogFile'
};
// post it
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
var redirectUrl = response;
/** Debug **/
// console.log(redirectUrl);
// return false;
top.location.replace(redirectUrl);
return false;
} else {
alert('خطا در پاکسازی فایل لاگ');
return false;
}
});
/*End Post*/
return false;
});
});
//=====================================================================================================================
$(function () {
// AJAX - Sync Products Manually
$('#ssbhesabix_sync_products_manually').submit(function () {
// show processing status
$('#ssbhesabix_sync_products_manually-submit').attr('disabled', 'disabled');
$('#ssbhesabix_sync_products_manually-submit').removeClass('button-primary');
$('#ssbhesabix_sync_products_manually-submit').html('<i class="ofwc-spinner"></i> ذخیره کردن اطلاعات...');
$('#ssbhesabix_sync_products_manually i.spinner').show();
const inputArray = [];
const inputs = $('.code-input');
console.log(inputs);
for (var n = 0; n < inputs.length; n++) {
var i = inputs[n];
console.log(i);
const obj = {
id: $(i).attr('id'),
hesabix_id: $(i).val(),
parent_id: $(i).attr('data-parent-id')
}
inputArray.push(obj);
}
const page = $('#pageNumber').val();
const rpp = $('#goToPage').attr('data-rpp');
var data = {
'action': 'adminSyncProductsManually',
'data': JSON.stringify(inputArray),
'page': page,
'rpp': rpp
};
// post it
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
var redirectUrl = response;
/** Debug **/
// console.log(redirectUrl);
// return false;
top.location.replace(redirectUrl);
return false;
} else {
alert('خطا در ذخیره اطلاعات');
return false;
}
});
/*End Post*/
return false;
});
$("#goToPage").click(function () {
const page = $('#pageNumber').val();
const rpp = $('#goToPage').attr('data-rpp');
window.location.href = "?page=hesabix-sync-products-manually&p=" + page + "&rpp=" + rpp;
});
$("#show-tips-btn").click(function () {
$('#tips-alert').removeClass('d-none');
$('#tips-alert').addClass('d-block');
});
$("#hide-tips-btn").click(function () {
$('#tips-alert').removeClass('d-block');
$('#tips-alert').addClass('d-none');
});
});
$(".btn-submit-invoice").on( "click", function() {
var orderId = $(this).attr("data-order-id");
var btnEl = $('.btn-submit-invoice[data-order-id=' + orderId + ']');
btnEl.attr('aria-disabled', true);
btnEl.addClass('disabled');
btnEl.html('ثبت فاکتور...');
//btnEl.show();
submitInvoice(orderId);
});
//=====================================================================================================================
function submitInvoice(orderId) {
var data = {
'action': 'adminSubmitInvoice',
'orderId': orderId
};
$.post(ajaxurl, data, function (response) {
if ('failed' !== response) {
const res = JSON.parse(response);
// refresh page
location.reload();
} else {
alert('خطا در ثبت فاکتور');
return false;
}
});
}
// change business warning
var oldApiKey = '';
$("#changeBusinessWarning").hide();
$("#ssbhesabix_account_api").focusin( function () {
oldApiKey = $("#ssbhesabix_account_api" ).val();
});
$("#ssbhesabix_account_api").focusout( function () {
var newApiKey = $("#ssbhesabix_account_api" ).val();
if(oldApiKey != '' && oldApiKey != newApiKey) {
$("#changeBusinessWarning").show();
}
});
//=====================================================================================================================
$(function () {
// AJAX - clear all plugin data
$('#hesabix-clear-plugin-data').click(function () {
if (confirm('هشدار: با انجام این عملیات کلیه اطلاعات افزونه شامل روابط بین کالاها، مشتریان و فاکتور ها و همینطور تنظیمات افزونه حذف می گردد.' +
'آیا از انجام این عملیات مطمئن هستید؟')) {
$('#hesabix-clear-plugin-data').addClass('disabled');
$('#hesabix-clear-plugin-data').html('حذف دیتای افزونه...');
var data = {
'action': 'adminClearPluginData'
};
$.post(ajaxurl, data, function (response) {
$('#hesabix-clear-plugin-data').removeClass('disabled');
$('#hesabix-clear-plugin-data').html('حذف دیتای افزونه');
if ('failed' !== response) {
alert('دیتای افزونه با موفقیت حذف شد.');
return false;
} else {
alert('خطا در هنگام حذف دیتای افزونه.');
return false;
}
});
} else {
// Do nothing!
}
return false;
});
$('#hesabix-install-plugin-data').click(function () {
if (confirm('با انجام این عملیات جدول افزونه در دیتابیس وردپرس ایجاد' +
' و تنظیمات پیش فرض افزونه تنظیم می گردد.' +
' آیا از انجام این عملیات مطمئن هستید؟')) {
$('#hesabix-install-plugin-data').addClass('disabled');
$('#hesabix-install-plugin-data').html('نصب دیتای افزونه...');
var data = {
'action': 'adminInstallPluginData'
};
$.post(ajaxurl, data, function (response) {
$('#hesabix-install-plugin-data').removeClass('disabled');
$('#hesabix-install-plugin-data').html('نصب دیتای افزونه');
if ('failed' !== response) {
alert('دیتای افزونه با موفقیت نصب شد.');
return false;
} else {
alert('خطا در هنگام نصب دیتای افزونه.');
return false;
}
});
} else {
// Do nothing!
}
return false;
});
});
//=====================================================================================================================
$(function () {
//SAVE
$(".hesabix-item-save").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
const attributeId = $(this).data('id');
const code = $("#hesabix-item-" + attributeId).val();
var data = {
'action': 'adminChangeProductCode',
'productId': productId,
'attributeId': attributeId,
'code': code,
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
alert(res.error ? res.message : 'کد کالای متصل با موفقیت تغییر کرد.');
if(productId === attributeId)
$("#ssbhesabix_hesabix_item_code_0").val(code);
else
$("#ssbhesabix_hesabix_item_code_" + attributeId).val(code);
return false;
} else {
alert('خطا در هنگام تغییر کد کالای متصل.');
return false;
}
});
});
//DELETE LINK
$(".hesabix-item-delete-link").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
const attributeId = $(this).data('id');
var data = {
'action': 'adminDeleteProductLink',
'productId': productId,
'attributeId': attributeId
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
$("#hesabix-item-" + attributeId).val('');
if(productId === attributeId)
$("#ssbhesabix_hesabix_item_code_0").val('');
else
$("#ssbhesabix_hesabix_item_code_" + attributeId).val('');
setTimeout(function (){
alert(res.error ? res.message : 'ارتباط محصول با موفقیت حذف شد');
}, 100);
return false;
} else {
alert('خطا در هنگام حذف ارتباط');
return false;
}
});
});
//UPDATE
$(".hesabix-item-update").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
const attributeId = $(this).data('id');
var data = {
'action': 'adminUpdateProduct',
'productId': productId,
'attributeId': attributeId
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
if(res.newPrice != null)
$("#hesabix-item-price-" + attributeId).text(res.newPrice);
if(res.newQuantity != null)
$("#hesabix-item-quantity-" + attributeId).text(res.newQuantity);
if(res.error)
alert(res.message);
return false;
} else {
alert('خطا در هنگام بروزرسانی محصول');
return false;
}
});
});
//SAVE ALL
$("#hesabix-item-save-all").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
const itemsCode = $(".hesabix-item-code");
const itemsData = [];
for (let i = 0; i < itemsCode.length; i++) {
const item = itemsCode[i];
const attributeId = $(item).data('id');
const code = $(item).val();
itemsData.push({attributeId: attributeId, code: code});
}
var data = {
'action': 'adminChangeProductsCode',
'productId': productId,
'itemsData': itemsData
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
alert(res.error ? res.message : 'کد کالاهای متصل با موفقیت تغییر کرد.');
location.reload();
return false;
} else {
alert('خطا در هنگام تغییر کد کالاهای متصل');
return false;
}
});
});
//DELETE
$("#hesabix-item-delete-link-all").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
var data = {
'action': 'adminDeleteProductsLink',
'productId': productId
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
const itemsCode = $(".hesabix-item-code");
for (let i = 0; i < itemsCode.length; i++) {
const item = itemsCode[i];
$(item).val('');
}
$('[id^="ssbhesabix_hesabix_item_code_"]').val('');
setTimeout(function (){
alert(res.error ? res.message : 'ارتباط محصولات با موفقیت حذف شد.');
}, 100);
return false;
} else {
alert('خطا در هنگام حذف ارتباط');
return false;
}
});
});
//UPDATE ALL
$("#hesabix-item-update-all").on('click', function (){
const productId = $("#panel_product_data_hesabix").data('product-id');
var data = {
'action': 'adminUpdateProductAndVariations',
'productId': productId
};
$(this).prop('disabled', true);
const _this = this;
$.post(ajaxurl, data, function (response) {
$(_this).prop('disabled', false);
if ('failed' !== response) {
const res = JSON.parse(response);
if(res.error)
{
alert(res.message);
return false;
}
for (let i = 0; i < res.newData.length; i++) {
if(res.newData[i].newPrice != null)
$("#hesabix-item-price-" + res.newData[i].attributeId).text(res.newData[i].newPrice);
if(res.newData[i].newQuantity != null)
$("#hesabix-item-quantity-" + res.newData[i].attributeId).text(res.newData[i].newQuantity);
}
return false;
} else {
alert('خطا در هنگام بروزرسانی محصول');
return false;
}
});
});
});
//=====================================================================================================================
$(function (){
let radio = $('input:radio[name="addFieldsRadio"]');
let radioChecked = $('input:radio[name="addFieldsRadio"]:checked');
let textInput = $('.contact_text_input');
if(radioChecked.val() === '2'){
textInput.prop( "disabled", false );
}else {
textInput.prop( "disabled", true );
}
$(radio).on('click',function (){
if($(this).val() === '2'){
textInput.prop( "disabled", false );
}else {
textInput.prop( "disabled", true );
}
});
});
});
//=====================================================================================================================
function hesabixTutorialJumpTo(time) {
let vidEl = document.getElementById('hesabix-tutorial-video');
vidEl.play();
vidEl.pause();
vidEl.currentTime = time;
vidEl.play();
}

View file

@ -0,0 +1,297 @@
<?php
/**
* Hesabix Admin Display
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Admin_Display
{
public function __construct()
{
add_action('admin_menu', array(__CLASS__, 'hesabix_add_menu'));
}
static function hesabix_add_menu()
{
$iconUrl = HESABIX_PLUGIN_URL . 'assets/img/menu-icon.png';
add_menu_page(__("Hesabix", 'hesabix'), __("Hesabix", 'hesabix'), "manage_options", "hesabix-option", array(__CLASS__, 'hesabix_plugin_page'), $iconUrl, null);
add_submenu_page("hesabix-option", __("Hesabix Settings", 'hesabix'), __("Hesabix Settings", 'hesabix'), "manage_options", 'hesabix-option', array(__CLASS__, 'hesabix_plugin_page'));
}
function hesabix_plugin_repeated_products()
{
global $wpdb;
$rows = $wpdb->get_results(
"SELECT id_hesabix
FROM {$wpdb->prefix}hesabix
WHERE obj_type = 'product'
GROUP BY id_hesabix
HAVING COUNT(id_hesabix) > 1"
);
$ids = array();
foreach ($rows as $row)
$ids[] = $row->id_hesabix;
$idsStr = implode(',', $ids);
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}hesabix
WHERE obj_type = 'product'
AND id_hesabix IN ($idsStr)
ORDER BY id_hesabix"
)
);
$i = 0;
self::hesabix_plugin_header();
?>
<div class="hesabix-f mt-4">
<h5 class="h5 hesabix-tab-page-title">
<?php echo __('Duplicate Product Codes', 'hesabix'); ?>
</h5>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col"><?php echo __('Hesabix Code', 'hesabix'); ?></th>
<th scope="col"><?php echo __('Product ID', 'hesabix'); ?></th>
<th scope="col"><?php echo __('Attribute ID', 'hesabix'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $p):
$i++; ?>
<tr>
<th scope="row"><?= $i; ?></th>
<td><?= $p->id_hesabix; ?></td>
<td><?= $p->id_ps; ?></td>
<td><?= $p->id_ps_attribute; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
function hesabix_plugin_tools()
{
self::hesabix_plugin_header();
?>
<div class="hesabix-f mt-4">
<h5 class="h5 hesabix-tab-page-title">
<?php echo __('Hesabix Plugin Tools', 'hesabix'); ?>
</h5>
<a href="javascript:void(0);" class="btn btn-danger mt-2"
id="hesabix-clear-plugin-data"><?php echo __('Delete Plugin Data', 'hesabix'); ?></a>
<br>
<a href="javascript:void(0);" class="btn btn-success mt-2"
id="hesabix-install-plugin-data"><?php echo __('Install Plugin Data', 'hesabix'); ?></a>
</div>
<?php
}
public static function getProductsAndRelations($page, $rpp)
{
$offset = ($page - 1) * $rpp;
global $wpdb;
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT post.ID, post.post_title, post.post_parent, post.post_excerpt, wc.sku
FROM {$wpdb->posts} AS post
LEFT OUTER JOIN {$wpdb->prefix}wc_product_meta_lookup AS wc
ON post.ID = wc.product_id
WHERE post.post_type IN ('product', 'product_variation')
AND post.post_status IN ('publish', 'private')
ORDER BY post.post_title ASC
LIMIT %d, %d",
$offset,
$rpp
)
);
$totalCount = $wpdb->get_var(
"SELECT COUNT(*)
FROM {$wpdb->posts} AS post
LEFT OUTER JOIN {$wpdb->prefix}wc_product_meta_lookup AS wc
ON post.ID = wc.product_id
WHERE post.post_type IN ('product', 'product_variation')
AND post.post_status IN ('publish', 'private')"
);
$links = $wpdb->get_results(
"SELECT *
FROM {$wpdb->prefix}hesabix
WHERE obj_type = 'product'"
);
foreach ($rows as $r) {
if ($r->post_excerpt)
$r->post_title = $r->post_title . ' [' . $r->post_excerpt . ']';
}
foreach ($links as $link) {
foreach ($rows as $r) {
if ($r->ID == $link->id_ps && $link->id_ps_attribute == 0) {
$r->id_hesabix = $link->id_hesabix;
} else if ($r->ID == $link->id_ps_attribute) {
$r->id_hesabix = $link->id_hesabix;
}
}
}
return array("data" => $rows, "totalCount" => $totalCount);
}
public static function hesabix_plugin_page()
{
$iconsArray = [
'home',
'cog',
'box-open',
'users',
'file-invoice-dollar',
'sync-alt',
'file-alt',
'cog'
];
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
$setting_tabs = apply_filters('hesabix_setting_tab', array(
'home' => __('Home', 'hesabix'),
'api' => __('API', 'hesabix'),
'catalog' => __('Catalog', 'hesabix'),
'customers' => __('Customers', 'hesabix'),
'invoice' => __('Invoice', 'hesabix'),
'sync' => __('Sync', 'hesabix'),
'log' => __('Log', 'hesabix'),
'extra' => __('Extra Settings', 'hesabix')
));
$current_tab = (isset($_GET['tab'])) ? wc_clean($_GET['tab']) : 'home';
?>
<div class="hesabix-admin">
<div class="hesabix-container">
<?php self::hesabix_plugin_header(); ?>
<div class="hesabix-tabs">
<?php
$i = 0;
foreach ($setting_tabs as $name => $label) {
$iconUrl = HESABIX_PLUGIN_URL . "assets/img/icons/$iconsArray[$i].svg";
$i++;
$active_class = ($current_tab == $name) ? 'active' : '';
echo '<button class="hesabix-tab ' . $active_class . '" data-tab="' . esc_attr($name) . '">';
echo "<svg width='16' height='16' class='hesabix-tab-icon'><image href='$iconUrl' width='16' height='16' /></svg>";
echo $label;
echo '</button>';
}
?>
</div>
<div class="hesabix-tab-content active">
<?php
foreach ($setting_tabs as $setting_tabkey => $setting_tabvalue) {
switch ($setting_tabkey) {
case $current_tab:
do_action('hesabix_' . $setting_tabkey . '_setting_save_field');
do_action('hesabix_' . $setting_tabkey . '_setting');
break;
}
}
?>
</div>
</div>
</div>
<?php
} else {
?>
<div class="hesabix-admin">
<div class="hesabix-container">
<div class="hesabix-alert hesabix-alert-danger">
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
</svg>
<div>
<strong><?php echo __('Hesabix Plugin requires the WooCommerce to work!', 'hesabix') ?></strong>
<div><?php echo __('Please install/activate woocommerce and try again', 'hesabix') ?></div>
</div>
</div>
</div>
</div>
<?php
}
}
public static function hesabix_plugin_header()
{
$logoUrl = HESABIX_PLUGIN_URL . '/assets/img/hesabix-logo.png';
$plugin_version = HESABIX_VERSION;
$is_connected = get_option('hesabix_account_api') ? true : false;
?>
<div class="hesabix-header">
<div class="hesabix-logo">
<img src="<?php echo $logoUrl ?>" alt="<?php echo __('Hesabix', 'hesabix'); ?>">
</div>
<div class="hesabix-info">
<h1 class="hesabix-title text-white mb-4"><?php echo __('Hesabix: WooCommerce', 'hesabix'); ?></h1>
<p class="hesabix-subtitle"><?php echo __('Connect Hesabix Online Accounting to WooCommerce', 'hesabix'); ?></p>
<div class="hesabix-badges d-none d-sm-flex">
<span
class="hesabix-badge version"><?php echo sprintf(__('Version %s', 'hesabix'), $plugin_version); ?></span>
<button id="hesabix-check-update" class="hesabix-badge hesabix-update-badge d-flex flex-row" disabled>
<span class="update-text"></span>
<span class="update-loading d-flex flex-row gap-2"
style="justify-content: center; align-items: center; gap: 5px;">
<div class="hesabix-spinner-small"></div>
<?php echo __('Checking...', 'hesabix'); ?>
</span>
</button>
<a href="https://hesabix.ir/help/topics/" class="hesabix-badge hesabix-guide-badge version"
style="color: white; text-decoration: none;" target="_blank">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z" />
</svg>
<?php echo __('Plugin Guide', 'hesabix'); ?>
</a>
</div>
<div class="hesabix-badges d-flex d-sm-none flex-column" style="align-items: center;">
<div class="d-flex flex-row gap-2">
<span
class="hesabix-badge version"><?php echo sprintf(__('Version %s', 'hesabix'), $plugin_version); ?></span>
</div>
<button id="hesabix-check-update" class="hesabix-badge hesabix-update-badge d-flex flex-row"
style="width: 70%;" disabled>
<span class="update-text"></span>
<span class="update-loading d-flex flex-row gap-2"
style="justify-content: center; align-items: center; gap: 5px;">
<div class="hesabix-spinner-small"></div>
<?php echo __('Checking...', 'hesabix'); ?>
</span>
</button>
<a href="https://hesabix.ir/help/topics/" class="hesabix-badge hesabix-guide-badge version"
style="color: white; text-decoration: none;" target="_blank">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
<path
d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z" />
</svg>
<?php echo __('Plugin Guide', 'hesabix'); ?>
</a>
</div>
</div>
</div>
<?php
}
}
new Hesabix_Admin_Display();

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,371 +1,542 @@
<?php
/*
* @class Ssbhesabix_Html_output
* @version 2.1.1
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/admin/output
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
*/
class Ssbhesabix_Html_output {
public static function init($options = array()) {
if (!empty($options)) {
foreach ($options as $value) {
if (!isset($value['type'])) continue;
if (!isset($value['id'])) $value['id'] = '';
if (!isset($value['title'])) $value['title'] = isset($value['name']) ? $value['name'] : '';
if (!isset($value['class'])) $value['class'] = '';
if (!isset($value['css'])) $value['css'] = '';
if (!isset($value['default'])) $value['default'] = '';
if (!isset($value['desc'])) $value['desc'] = '';
if (!isset($value['desc_tip'])) $value['desc_tip'] = false;
$custom_attributes = array();
if (!empty($value['custom_attributes']) && is_array($value['custom_attributes'])) {
foreach ($value['custom_attributes'] as $attribute => $attribute_value) {
$custom_attributes[] = esc_attr($attribute) . '="' . esc_attr($attribute_value) . '"';
}
}
if (true === $value['desc_tip']) {
$description = '';
$tip = $value['desc'];
} elseif (!empty($value['desc_tip'])) {
$description = $value['desc'];
$tip = $value['desc_tip'];
} elseif (!empty($value['desc'])) {
$description = $value['desc'];
$tip = '';
} else {
$description = $tip = '';
}
if ($description && in_array($value['type'], array('textarea', 'radio'))) {
$description = '<p style="margin-top:0" class="hesabix-p">' . wp_kses_post($description) . '</p>';
} elseif ($description && in_array($value['type'], array('checkbox'))) {
$description = wp_kses_post($description);
} elseif ($description) {
$description = '<span class="description">' . wp_kses_post($description) . '</span>';
}
if (isset($value['placeholder']) && !empty($value['placeholder'])) {
$placeholder = $value['placeholder'];
} else {
$placeholder = '';
}
if ($tip && in_array($value['type'], array('checkbox'))) {
$tip = '<p class="description hesabix-p">' . $tip . '</p>';
}
switch ($value['type']) {
case 'title':
if (!empty($value['title'])) {
echo '<h3 class="hesabix-tab-page-title">' . esc_html($value['title']) . '</h3>';
}
if (!empty($value['desc'])) {
echo wpautop(wptexturize(wp_kses_post($value['desc'])));
}
echo '<table class="form-table hesabix-p">' . "\n\n";
break;
case 'sectionend':
echo '</table>';
break;
case 'text':
case 'email':
case 'number':
case 'color' :
case 'password' :
$type = $value['type'];
$class = '';
$option_value = self::get_option($value['id'], $value['default']);
if ($value['type'] == 'color') {
$type = 'text';
$value['class'] .= 'colorpick';
$description .= '<div id="colorPickerDiv_' . esc_attr($value['id']) . '" class="colorpickdiv" style="z-index: 100;background:#eee;border:1px solid #ccc;position:absolute;display:none;"></div>';
}
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<input
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
type="<?php echo esc_attr($type); ?>"
style="<?php echo esc_attr($value['css']); ?>"
value="<?php echo esc_attr($option_value); ?>"
class="<?php echo esc_attr($value['class']); ?>"
placeholder="<?php echo esc_attr($placeholder); ?>"
<?php echo implode(' ', $custom_attributes); ?>
/> <?php echo $description; ?>
</td>
</tr><?php
break;
case 'textarea':
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<?php echo $description; ?>
<?php
if (isset($value['editor']) && $value['editor'] == 'true') {
echo wp_editor($option_value, $value['id']);
} else {
?>
<textarea
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
><?php echo esc_textarea($option_value); ?></textarea>
<?php } ?>
</td>
</tr><?php
break;
case 'select' :
case 'multiselect' :
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<select
name="<?php echo esc_attr($value['id']); ?><?php if ($value['type'] == 'multiselect') echo '[]'; ?>"
id="<?php echo esc_attr($value['id']); ?>"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
<?php echo ( 'multiselect' == $value['type'] ) ? 'multiple="multiple"' : ''; ?>
>
<?php
foreach ($value['options'] as $key => $val) {
?>
<option value="<?php echo esc_attr($key); ?>" <?php
if (is_array($option_value)) {
selected(in_array($key, $option_value), true);
} else {
selected($option_value, $key);
}
?>><?php echo $val ?></option>
<?php
}
?>
</select> <?php echo $description; ?>
</td>
</tr><?php
break;
case 'radio' :
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<fieldset>
<?php echo $description; ?>
<ul>
<?php
foreach ($value['options'] as $key => $val) {
?>
<li>
<label><input
name="<?php echo esc_attr($value['id']); ?>"
value="<?php echo $key; ?>"
type="radio"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
<?php checked($key, $option_value); ?>
/> <?php echo $val ?></label>
</li>
<?php
}
?>
</ul>
</fieldset>
</td>
</tr><?php
break;
case 'checkbox' :
$option_value = self::get_option($value['id'], $value['default']);
$visbility_class = array();
if (!isset($value['hide_if_checked'])) {
$value['hide_if_checked'] = false;
}
if (!isset($value['show_if_checked'])) {
$value['show_if_checked'] = false;
}
if ('yes' == $value['hide_if_checked'] || 'yes' == $value['show_if_checked']) {
$visbility_class[] = 'hidden_option';
}
if ('option' == $value['hide_if_checked']) {
$visbility_class[] = 'hide_options_if_checked';
}
if ('option' == $value['show_if_checked']) {
$visbility_class[] = 'show_options_if_checked';
}
if (!isset($value['checkboxgroup']) || 'start' == $value['checkboxgroup']) {
?>
<tr style="vertical-align: top" class="<?php echo esc_attr(implode(' ', $visbility_class)); ?>">
<th scope="row" class="titledesc"><?php echo esc_html($value['title']) ?></th>
<td class="forminp forminp-checkbox">
<fieldset>
<?php
} else {
?>
<fieldset class="<?php echo esc_attr(implode(' ', $visbility_class)); ?>">
<?php
}
if (!empty($value['title'])) {
?>
<legend class="screen-reader-text"><span><?php echo esc_html($value['title']) ?></span></legend>
<?php
}
?>
<label for="<?php echo $value['id'] ?>">
<input
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
type="checkbox"
value="1"
<?php checked($option_value, 'yes'); ?>
<?php echo implode(' ', $custom_attributes); ?>
/> <?php echo $description ?>
</label> <?php echo $tip; ?>
<?php
if (!isset($value['checkboxgroup']) || 'end' == $value['checkboxgroup']) {
?>
</fieldset>
</td>
</tr>
<?php
} else {
?>
</fieldset>
<?php
}
break;
case 'single_select_page' :
$args = array(
'name' => $value['id'],
'id' => $value['id'],
'sort_column' => 'menu_order',
'sort_order' => 'ASC',
'show_option_none' => ' ',
'class' => $value['class'],
'echo' => false,
'selected' => absint(self::get_option($value['id']))
);
if (isset($value['args'])) {
$args = wp_parse_args($value['args'], $args);
}
?><tr style="vertical-align: top" class="single_select_page">
<th scope="row" class="titledesc"><?php echo esc_html($value['title']) ?> <?php echo $tip; ?></th>
<td class="forminp">
<?php echo str_replace(' id=', " data-placeholder='" . __('Select a page&hellip;', 'Option') . "' style='" . $value['css'] . "' class='" . $value['class'] . "' id=", wp_dropdown_pages($args)); ?> <?php echo $description; ?>
</td>
</tr><?php
break;
default:
break;
}
}
}
}
//=====================================================================================================
public static function get_option($option_name, $default = '') {
if (strstr($option_name, '[')) {
parse_str($option_name, $option_array);
$option_name = current(array_keys($option_array));
$option_values = get_option($option_name, '');
$key = key($option_array[$option_name]);
if (isset($option_values[$key])) {
$option_value = $option_values[$key];
} else {
$option_value = null;
}
} else {
$option_value = get_option($option_name, null);
}
if (is_array($option_value)) {
$option_value = array_map('stripslashes', $option_value);
} elseif (!is_null($option_value)) {
$option_value = stripslashes($option_value);
if (empty($option_value) && !empty($default)) {
$option_value = null;
}
}
return $option_value === null ? $default : $option_value;
}
//=====================================================================================================
public static function save_fields($options) {
if (empty($_POST)) return false;
$update_options = array();
foreach ($options as $value) {
if (!isset($value['id']) || !isset($value['type'])) {
continue;
}
if (strstr($value['id'], '[')) {
parse_str($value['id'], $option_name_array);
$option_name = current(array_keys($option_name_array));
$setting_name = key($option_name_array[$option_name]);
$option_value = isset($_POST[$option_name][$setting_name]) ? wc_clean($_POST[$option_name][$setting_name]) : null;
} else {
$option_name = $value['id'];
$setting_name = '';
$option_value = isset($_POST[$value['id']]) ? wc_clean($_POST[$value['id']]) : null;
}
switch (sanitize_title($value['type'])) {
case 'checkbox' :
$option_value = is_null($option_value) ? 'no' : 'yes';
break;
case 'textarea' :
$option_value = wp_kses_post(trim($option_value));
break;
case 'text' :
case 'email':
case 'number':
case 'select' :
case 'color' :
case 'password' :
case 'radio' :
$option_value = $option_value;
break;
default :
break;
}
if (!is_null($option_value)) {
if ($option_name && $setting_name) {
if (!isset($update_options[$option_name])) {
$update_options[$option_name] = get_option($option_name, array());
}
if (!is_array($update_options[$option_name])) {
$update_options[$option_name] = array();
}
$update_options[$option_name][$setting_name] = $option_value;
} else {
$update_options[$option_name] = $option_value;
}
}
}
foreach ($update_options as $name => $value) {
update_option($name, wc_clean($value));
}
echo '<div class="updated"><p class="hesabix-p">' . __( 'Settings were saved successfully.', 'ssbhesabix' ) . '</p></div>';
return true;
}
//=====================================================================================================
}
Ssbhesabix_Html_output::init();
<?php
/**
* Hesabix HTML Output
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Html_output {
public static function init($options = array()) {
if (!empty($options)) {
foreach ($options as $value) {
if (!isset($value['type'])) continue;
if (!isset($value['id'])) $value['id'] = '';
if (!isset($value['title'])) $value['title'] = isset($value['name']) ? $value['name'] : '';
if (!isset($value['class'])) $value['class'] = '';
if (!isset($value['css'])) $value['css'] = '';
if (!isset($value['default'])) $value['default'] = '';
if (!isset($value['desc'])) $value['desc'] = '';
if (!isset($value['desc_tip'])) $value['desc_tip'] = false;
$custom_attributes = array();
if (!empty($value['custom_attributes']) && is_array($value['custom_attributes'])) {
foreach ($value['custom_attributes'] as $attribute => $attribute_value) {
$custom_attributes[] = esc_attr($attribute) . '="' . esc_attr($attribute_value) . '"';
}
}
if (true === $value['desc_tip']) {
$description = '';
$tip = $value['desc'];
} elseif (!empty($value['desc_tip'])) {
$description = $value['desc'];
$tip = $value['desc_tip'];
} elseif (!empty($value['desc'])) {
$description = $value['desc'];
$tip = '';
} else {
$description = $tip = '';
}
if ($description && in_array($value['type'], array('textarea', 'radio'))) {
$description = '<p style="margin-top:0" class="hesabix-p">' . wp_kses_post($description) . '</p>';
} elseif ($description && in_array($value['type'], array('checkbox'))) {
$description = wp_kses_post($description);
} elseif ($description) {
$description = '<span class="description">' . wp_kses_post($description) . '</span>';
}
if (isset($value['placeholder']) && !empty($value['placeholder'])) {
$placeholder = $value['placeholder'];
} else {
$placeholder = '';
}
if ($tip && in_array($value['type'], array('checkbox'))) {
$tip = '<p class="description hesabix-p">' . $tip . '</p>';
}
switch ($value['type']) {
case 'title':
if (!empty($value['title'])) {
}
if (!empty($value['desc'])) {
echo wpautop(wptexturize(wp_kses_post($value['desc'])));
}
echo '<table class="form-table hesabix-p">' . "\n\n";
break;
case 'sectionend':
echo '</table>';
break;
case 'text':
case 'email':
case 'number':
case 'color' :
case 'password' :
$type = $value['type'];
$class = '';
$option_value = self::get_option($value['id'], $value['default']);
if ($value['type'] == 'color') {
$type = 'text';
$value['class'] .= 'colorpick';
$description .= '<div id="colorPickerDiv_' . esc_attr($value['id']) . '" class="colorpickdiv" style="z-index: 100;background:#eee;border:1px solid #ccc;position:absolute;display:none;"></div>';
}
?><tr style="vertical-align: top" <?php echo ($value['id'] === 'hesabix_invoice_freight_code') ? 'class="hesabix-freight-code-field hidden"' : (strpos($value['class'], 'custom-api-address-field') !== false ? 'class="custom-api-address-field"' : ''); ?>>
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<input
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
type="<?php echo esc_attr($type); ?>"
style="<?php echo esc_attr($value['css']); ?>"
value="<?php echo esc_attr($option_value); ?>"
class="<?php echo esc_attr($value['class']); ?>"
placeholder="<?php echo esc_attr($placeholder); ?>"
<?php echo implode(' ', $custom_attributes); ?>
/> <?php echo $description; ?>
</td>
</tr><?php
break;
case 'textarea':
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<?php echo $description; ?>
<?php
if (isset($value['editor']) && $value['editor'] == 'true') {
echo wp_editor($option_value, $value['id']);
} else {
?>
<textarea
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
><?php echo esc_textarea($option_value); ?></textarea>
<?php } ?>
</td>
</tr><?php
break;
case 'select' :
case 'multiselect' :
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<select
name="<?php echo esc_attr($value['id']); ?><?php if ($value['type'] == 'multiselect') echo '[]'; ?>"
id="<?php echo esc_attr($value['id']); ?>"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
<?php echo ( 'multiselect' == $value['type'] ) ? 'multiple="multiple"' : ''; ?>
>
<?php
foreach ($value['options'] as $key => $val) {
?>
<option value="<?php echo esc_attr($key); ?>" <?php
if (is_array($option_value)) {
selected(in_array($key, $option_value), true);
} else {
selected($option_value, $key);
}
?>><?php echo $val ?></option>
<?php
}
?>
</select> <?php echo $description; ?>
</td>
</tr><?php
break;
case 'custom_status_selector' :
$option_value = self::get_option($value['id'], $value['default']);
if (!is_array($option_value)) {
if (is_string($option_value) && !empty($option_value)) {
$option_value = array_map('trim', explode(',', $option_value));
} else {
$option_value = array();
}
}
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-custom-status-selector">
<div class="hesabix-status-selector">
<input type="hidden" name="<?php echo esc_attr($value['id']); ?>" value="<?php echo esc_attr(implode(',', $option_value)); ?>" />
<div class="hesabix-status-grid">
<?php
foreach ($value['options'] as $key => $val) {
$is_selected = in_array($key, $option_value);
$status_class = 'hesabix-status-' . str_replace('-', '-', $key);
?>
<div class="hesabix-status-item <?php echo $status_class; ?> <?php echo $is_selected ? 'selected' : ''; ?>">
<input type="checkbox" name="<?php echo esc_attr($value['id']); ?>_checkboxes[]" value="<?php echo esc_attr($key); ?>" <?php echo $is_selected ? 'checked' : ''; ?> />
<div class="hesabix-status-icon">
<?php
switch ($key) {
case 'pending':
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
break;
case 'processing':
echo '<svg viewBox="0 0 24 24"><path d="M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8z"/></svg>';
break;
case 'on-hold':
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
break;
case 'completed':
echo '<svg viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>';
break;
case 'cancelled':
echo '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>';
break;
case 'refunded':
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
break;
case 'failed':
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
break;
case 'checkout-draft':
echo '<svg viewBox="0 0 24 24"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"/></svg>';
break;
default:
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
}
?>
</div>
<div class="hesabix-status-content">
<div class="hesabix-status-title"><?php echo esc_html($val); ?></div>
<div class="hesabix-status-description">
<?php
switch ($key) {
case 'pending':
echo __('Order Pending Payment', 'hesabix');
break;
case 'processing':
echo __('Order Processing', 'hesabix');
break;
case 'on-hold':
echo __('Order On Hold', 'hesabix');
break;
case 'completed':
echo __('Order Completed', 'hesabix');
break;
case 'cancelled':
echo __('Order Cancelled', 'hesabix');
break;
case 'refunded':
echo __('Order Refunded', 'hesabix');
break;
case 'failed':
echo __('Order Failed', 'hesabix');
break;
case 'checkout-draft':
echo __('Order Draft', 'hesabix');
break;
default:
echo 'Order Status';
}
?>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
<?php echo $description; ?>
</td>
</tr><?php
break;
case 'radio' :
$option_value = self::get_option($value['id'], $value['default']);
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-<?php echo sanitize_title($value['type']) ?>">
<fieldset>
<?php echo $description; ?>
<ul>
<?php
foreach ($value['options'] as $key => $val) {
?>
<li>
<label><input
name="<?php echo esc_attr($value['id']); ?>"
value="<?php echo $key; ?>"
type="radio"
style="<?php echo esc_attr($value['css']); ?>"
class="<?php echo esc_attr($value['class']); ?>"
<?php echo implode(' ', $custom_attributes); ?>
<?php checked($key, $option_value); ?>
/> <?php echo $val ?></label>
</li>
<?php
}
?>
</ul>
</fieldset>
</td>
</tr><?php
break;
case 'freight_switch':
$option_value = self::get_option($value['id'], $value['default']);
if ($option_value === '0' || $option_value === 0) {
$option_value = '0'; // Save as Freight
} elseif ($option_value === '1' || $option_value === 1) {
$option_value = '1'; // Save as Service
} elseif (empty($option_value) || $option_value === 'disabled') {
$option_value = 'disabled'; // Don't Save
}
?><tr style="vertical-align: top">
<th scope="row" class="titledesc">
<label for="<?php echo esc_attr($value['id']); ?>"><?php echo esc_html($value['title']); ?></label>
<?php echo $tip; ?>
</th>
<td class="forminp forminp-freight-switch">
<div class="hesabix-freight-switch-container">
<div class="hesabix-freight-options">
<?php foreach ($value['options'] as $key => $val) : ?>
<div class="hesabix-freight-option <?php echo ($option_value == $key) ? 'active' : ''; ?>" data-value="<?php echo esc_attr($key); ?>">
<div class="hesabix-freight-option-content">
<div class="hesabix-freight-icon">
<?php
switch ($key) {
case 'disabled':
echo '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
break;
case '0':
echo '<svg viewBox="0 0 24 24"><path d="M19 7h-3V6a4 4 0 0 0-8 0v1H5a1 1 0 0 0-1 1v11a3 3 0 0 0 3 3h10a3 3 0 0 0 3-3V8a1 1 0 0 0-1-1zM10 6a2 2 0 0 1 4 0v1h-4V6zm8 13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V9h2v1a1 1 0 0 0 2 0V9h4v1a1 1 0 0 0 2 0V9h2v10z"/></svg>';
break;
case '1':
echo '<svg viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>';
break;
}
?>
</div>
<div class="hesabix-freight-title"><?php echo esc_html($val); ?></div>
<div class="hesabix-freight-desc">
<?php
switch ($key) {
case 'disabled':
echo __('Freight cost is not saved in the invoice.', 'hesabix');
break;
case '0':
echo __('Freight cost is saved as a product.', 'hesabix');
break;
case '1':
echo __('Freight cost is saved as a service.', 'hesabix');
break;
}
?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<input type="hidden" name="<?php echo esc_attr($value['id']); ?>" id="<?php echo esc_attr($value['id']); ?>" value="<?php echo esc_attr($option_value); ?>" />
</div>
<?php echo $description; ?>
</td>
</tr><?php
break;
case 'checkbox' :
$option_value = self::get_option($value['id'], $value['default']);
$visbility_class = array();
if (!isset($value['hide_if_checked'])) {
$value['hide_if_checked'] = false;
}
if (!isset($value['show_if_checked'])) {
$value['show_if_checked'] = false;
}
if ('yes' == $value['hide_if_checked'] || 'yes' == $value['show_if_checked']) {
$visbility_class[] = 'hidden_option';
}
if ('option' == $value['hide_if_checked']) {
$visbility_class[] = 'hide_options_if_checked';
}
if ('option' == $value['show_if_checked']) {
$visbility_class[] = 'show_options_if_checked';
}
if (!isset($value['checkboxgroup']) || 'start' == $value['checkboxgroup']) {
?>
<tr style="vertical-align: top" class="<?php echo esc_attr(implode(' ', $visbility_class)); ?>">
<th scope="row" class="titledesc"><?php echo esc_html($value['title']) ?></th>
<td class="forminp forminp-checkbox">
<fieldset>
<?php
} else {
?>
<fieldset class="<?php echo esc_attr(implode(' ', $visbility_class)); ?>">
<?php
}
if (!empty($value['title'])) {
?>
<legend class="screen-reader-text"><span><?php echo esc_html($value['title']) ?></span></legend>
<?php
}
?>
<label for="<?php echo $value['id'] ?>">
<span class="hesabix-switch">
<input
name="<?php echo esc_attr($value['id']); ?>"
id="<?php echo esc_attr($value['id']); ?>"
type="checkbox"
value="1"
<?php checked($option_value, 'yes'); ?>
<?php echo implode(' ', $custom_attributes); ?>
/>
<span class="hesabix-slider"></span>
</span>
<?php echo $description ?>
</label> <?php echo $tip; ?>
<?php
if (!isset($value['checkboxgroup']) || 'end' == $value['checkboxgroup']) {
?>
</fieldset>
</td>
</tr>
<?php
} else {
?>
</fieldset>
<?php
}
break;
case 'single_select_page' :
$args = array(
'name' => $value['id'],
'id' => $value['id'],
'sort_column' => 'menu_order',
'sort_order' => 'ASC',
'show_option_none' => ' ',
'class' => $value['class'],
'echo' => false,
'selected' => absint(self::get_option($value['id']))
);
if (isset($value['args'])) {
$args = wp_parse_args($value['args'], $args);
}
?><tr style="vertical-align: top" class="single_select_page">
<th scope="row" class="titledesc"><?php echo esc_html($value['title']) ?> <?php echo $tip; ?></th>
<td class="forminp">
<?php echo str_replace(' id=', " data-placeholder='" . __('Select a page&hellip;', 'Option') . "' style='" . $value['css'] . "' class='" . $value['class'] . "' id=", wp_dropdown_pages($args)); ?> <?php echo $description; ?>
</td>
</tr><?php
break;
default:
break;
}
}
}
}
public static function get_option($option_name, $default = '') {
if (strstr($option_name, '[')) {
parse_str($option_name, $option_array);
$option_name = current(array_keys($option_array));
$option_values = get_option($option_name, '');
$key = key($option_array[$option_name]);
if (isset($option_values[$key])) {
$option_value = $option_values[$key];
} else {
$option_value = null;
}
} else {
$option_value = get_option($option_name, null);
}
if (is_array($option_value)) {
$option_value = array_map('stripslashes', $option_value);
} elseif (!is_null($option_value)) {
$option_value = stripslashes($option_value);
if (empty($option_value) && !empty($default)) {
$option_value = null;
}
}
return $option_value === null ? $default : $option_value;
}
public static function save_fields($options) {
if (empty($_POST)) return false;
$update_options = array();
foreach ($options as $value) {
if (!isset($value['id']) || !isset($value['type'])) {
continue;
}
if (strstr($value['id'], '[')) {
parse_str($value['id'], $option_name_array);
$option_name = current(array_keys($option_name_array));
$setting_name = key($option_name_array[$option_name]);
$option_value = isset($_POST[$option_name][$setting_name]) ? wc_clean($_POST[$option_name][$setting_name]) : null;
} else {
$option_name = $value['id'];
$setting_name = '';
$option_value = isset($_POST[$value['id']]) ? wc_clean($_POST[$value['id']]) : null;
}
switch (sanitize_title($value['type'])) {
case 'checkbox' :
$option_value = is_null($option_value) ? 'no' : 'yes';
break;
case 'textarea' :
$option_value = wp_kses_post(trim($option_value));
break;
case 'text' :
case 'email':
case 'number':
case 'select' :
case 'color' :
case 'password' :
case 'radio' :
case 'custom_status_selector' :
case 'freight_switch' :
$option_value = $option_value;
break;
default :
break;
}
if (!is_null($option_value)) {
if ($option_name && $setting_name) {
if (!isset($update_options[$option_name])) {
$update_options[$option_name] = get_option($option_name, array());
}
if (!is_array($update_options[$option_name])) {
$update_options[$option_name] = array();
}
$update_options[$option_name][$setting_name] = $option_value;
} else {
$update_options[$option_name] = $option_value;
}
}
}
foreach ($update_options as $name => $value) {
update_option($name, wc_clean($value));
}
return true;
}
}
Hesabix_Html_output::init();

View file

@ -1,397 +0,0 @@
<?php
/**
* @class Ssbhesabix_Admin_Display
* @version 2.1.1
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/admin/display
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
*/
class Ssbhesabix_Admin_Display
{
/**
* Ssbhesabix_Admin_Display constructor.
*/
public function __construct()
{
add_action('admin_menu', array(__CLASS__, 'hesabix_add_menu'));
}
/**
* Hook in methods
* @since 1.0.0
* @access static
*/
/**
* @since 1.0.0
* @access public
*/
static function hesabix_add_menu()
{
$iconUrl = plugins_url('/hesabix-accounting/admin/img/menu-icon.png');
add_menu_page("حسابیکس", "حسابیکس", "manage_options", "ssbhesabix-option", array(__CLASS__, 'hesabix_plugin_page'), $iconUrl, null);
add_submenu_page("ssbhesabix-option", "تنظیمات حسابیکس", "تنظیمات حسابیکس", "manage_options", 'ssbhesabix-option', array(__CLASS__, 'hesabix_plugin_page'));
}
function hesabix_plugin_sync_products_manually()
{
$page = $_GET["p"];
$rpp = $_GET["rpp"];
if (isset($_GET['data'])) {
$data = $_GET["data"];
$codesNotFoundInHesabix = explode(",", $data);
}
//set default values to page and rpp
if (!$page) $page = 1;
if (!$rpp) $rpp = 10;
$result = self::getProductsAndRelations($page, $rpp);
$pageCount = ceil($result["totalCount"] / $rpp);
$i = ($page - 1) * $rpp;
$rpp_options = [10, 15, 20, 30, 50];
$showTips = true;
if (!isset($_COOKIE['syncProductsManuallyHelp'])) {
setcookie('syncProductsManuallyHelp', 'ture');
} else {
$showTips = false;
}
self::hesabix_plugin_header();
?>
<div class="hesabix-f">
<p class="p mt-4">
<h5 class="h5 hesabix-tab-page-title">
همسان سازی دستی کالاهای فروشگاه با حسابیکس
<span class="badge bg-warning text-dark hand <?= $showTips ? 'd-none' : 'd-inline-block' ?>"
id="show-tips-btn">مشاهده نکات مهم</span>
</h5>
<div class="alert alert-danger alert-dismissible fade show <?= isset($codesNotFoundInHesabix) ? 'd-block' : 'd-none' ?>"
role="alert">
<strong>خطا</strong><br> کدهای زیر در حسابیکس پیدا نشد:
<br>
<?php foreach ($codesNotFoundInHesabix as $code): ?>
<span class="badge bg-secondary"><?= $code ?></span>&nbsp;
<?php endforeach; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div id="tips-alert"
class="alert alert-warning alert-dismissible fade show <?= $showTips ? 'd-block' : 'd-none' ?>"
role="alert">
<strong>توجه!</strong>
<ul style="list-style-type:square">
<li>تغییرات هر صفحه را ذخیره کنید و سپس به صفحه بعد بروید.</li>
<li>کد حسابیکس همان کد 6 رقمی (کد حسابداری کالا) است.</li>
<li>از وجود تعریف کالا در حسابیکس اطمینان حاصل کنید.</li>
<li>این صفحه برای زمانی است که شما از قبل یک کالا را هم در فروشگاه و هم در حسابیکس
تعریف کرده اید اما اتصالی بین آنها وجود ندارد.
به کمک این صفحه می توانید این اتصال را بصورت دستی برقرار کنید.
</li>
<li>
برای راحتی کار، این جدول بر اساس نام محصول مرتب سازی شده است،
بنابراین در حسابیکس نیز لیست کالاها را بر اساس نام مرتب سازی کرده و از روی آن شروع به وارد کردن
کدهای
متناظر در این جدول نمایید.
</li>
</ul>
<button type="button" class="btn-close" id="hide-tips-btn"></button>
</div>
</p>
<form id="ssbhesabix_sync_products_manually" autocomplete="off"
action="<?php echo admin_url('admin.php?page=hesabix-sync-products-manually&p=1'); ?>"
method="post">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">نام کالا</th>
<th scope="col">شناسه محصول</th>
<th scope="col">کد حسابیکس</th>
</tr>
</thead>
<tbody>
<?php foreach ($result["data"] as $p):
$i++; ?>
<tr class="<?= $p->id_hesabix ? 'table-success' : 'table-danger'; ?>">
<th scope="row"><?= $i; ?></th>
<td><?= $p->ID; ?></td>
<td><?= $p->post_title; ?></td>
<td><?= $p->sku; ?></td>
<td>
<input type="text" class="form-control code-input" id="<?= $p->ID; ?>"
data-parent-id="<?= $p->post_parent; ?>" value="<?= $p->id_hesabix; ?>"
style="width: 100px">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<label><?= $result["totalCount"] ?> رکورد </label> |
<label><?= $pageCount ?> صفحه </label> |
<label>صفحه جاری: </label>
<input id="pageNumber" class="form-control form-control-sm d-inline" type="text" value="<?= $page ?>"
style="width: 80px">
<a id="goToPage" class="btn btn-outline-secondary btn-sm" data-rpp="<?= $rpp ?>"
href="javascript:void(0)">برو</a>
<div class="dropdown d-inline">
<button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button"
id="dropdownMenuButton1"
data-bs-toggle="dropdown" aria-expanded="false">
<?= $rpp . ' ' ?>ردیف در هر صفحه
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<?php foreach ($rpp_options as $option): ?>
<li><a class="dropdown-item"
href="?page=hesabix-sync-products-manually&p=<?= $page ?>&rpp=<?= $option ?>"><?= $option ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<a class="btn btn-outline-secondary btn-sm <?= $page == 1 ? 'disabled' : '' ?>"
href="?page=hesabix-sync-products-manually&p=<?= $page - 1 ?>&rpp=<?= $rpp ?>">< صفحه قبل</a>
<a class="btn btn-outline-secondary btn-sm <?= $page == $pageCount ? 'disabled' : '' ?>"
href="?page=hesabix-sync-products-manually&p=<?= $page + 1 ?>&rpp=<?= $rpp ?>">صفحه بعد ></a>
<div class="mt-3">
<button class="btn btn-success" id="ssbhesabix_sync_products_manually-submit"
name="ssbhesabix_sync_products_manually-submit"><?php echo __('Save changes', 'ssbhesabix'); ?></button>
</div>
</form>
</div>
<?php
}
//========================================================================================================================================
function hesabix_plugin_repeated_products()
{
global $wpdb;
//$rows = $wpdb->get_results("SELECT id_hesabix FROM " . $wpdb->prefix . "ssbhesabix WHERE obj_type = 'product' GROUP BY id_hesabix HAVING COUNT(id_hesabix) > 1;");
$rows = $wpdb->get_results(
"SELECT id_hesabix
FROM {$wpdb->prefix}ssbhesabix
WHERE obj_type = 'product'
GROUP BY id_hesabix
HAVING COUNT(id_hesabix) > 1"
);
$ids = array();
foreach ($rows as $row)
$ids[] = $row->id_hesabix;
$idsStr = implode(',', $ids);
//$rows = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ssbhesabix WHERE obj_type = 'product' AND id_hesabix IN ($idsStr) ORDER BY id_hesabix");
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}ssbhesabix
WHERE obj_type = 'product'
AND id_hesabix IN ($idsStr)
ORDER BY id_hesabix"
)
);
$i = 0;
self::hesabix_plugin_header();
?>
<div class="hesabix-f mt-4">
<h5 class="h5 hesabix-tab-page-title">
کد محصولات تکراری
</h5>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">کد حسابیکس</th>
<th scope="col">شناسه محصول</th>
<th scope="col">شناسه متغیر</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $p):
$i++; ?>
<tr>
<th scope="row"><?= $i; ?></th>
<td><?= $p->id_hesabix; ?></td>
<td><?= $p->id_ps; ?></td>
<td><?= $p->id_ps_attribute; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
//========================================================================================================================================
function hesabix_plugin_tools() {
self::hesabix_plugin_header();
?>
<div class="hesabix-f mt-4">
<h5 class="h5 hesabix-tab-page-title">
ابزارهای افزونه حسابیکس
</h5>
<a href="javascript:void(0);" class="btn btn-danger mt-2" id="hesabix-clear-plugin-data" >حذف دیتای افزونه</a>
<br>
<a href="javascript:void(0);" class="btn btn-success mt-2" id="hesabix-install-plugin-data">نصب دیتای افزونه</a>
</div>
<?php
}
//========================================================================================================================================
public static function getProductsAndRelations($page, $rpp)
{
$offset = ($page - 1) * $rpp;
global $wpdb;
// $rows = $wpdb->get_results("SELECT post.ID,post.post_title,post.post_parent,post_excerpt,wc.sku FROM `" . $wpdb->prefix . "posts` as post
// LEFT OUTER JOIN `" . $wpdb->prefix . "wc_product_meta_lookup` as wc
// ON post.id = wc.product_id
// WHERE post.post_type IN('product','product_variation') AND post.post_status IN('publish','private')
// ORDER BY post.post_title ASC LIMIT $offset,$rpp");
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT post.ID, post.post_title, post.post_parent, post.post_excerpt, wc.sku
FROM {$wpdb->posts} AS post
LEFT OUTER JOIN {$wpdb->prefix}wc_product_meta_lookup AS wc
ON post.ID = wc.product_id
WHERE post.post_type IN ('product', 'product_variation')
AND post.post_status IN ('publish', 'private')
ORDER BY post.post_title ASC
LIMIT %d, %d",
$offset,
$rpp
)
);
// $totalCount = $wpdb->get_var("SELECT COUNT(*) FROM `" . $wpdb->prefix . "posts` as post
// LEFT OUTER JOIN `" . $wpdb->prefix . "wc_product_meta_lookup` as wc
// ON post.id = wc.product_id
// WHERE post.post_type IN('product','product_variation') AND post.post_status IN('publish','private')");
$totalCount = $wpdb->get_var(
"SELECT COUNT(*)
FROM {$wpdb->posts} AS post
LEFT OUTER JOIN {$wpdb->prefix}wc_product_meta_lookup AS wc
ON post.ID = wc.product_id
WHERE post.post_type IN ('product', 'product_variation')
AND post.post_status IN ('publish', 'private')"
);
// $links = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "ssbhesabix`
// WHERE obj_type ='product'");
$links = $wpdb->get_results(
"SELECT *
FROM {$wpdb->prefix}ssbhesabix
WHERE obj_type = 'product'"
);
foreach ($rows as $r) {
if ($r->post_excerpt)
$r->post_title = $r->post_title . ' [' . $r->post_excerpt . ']';
}
foreach ($links as $link) {
foreach ($rows as $r) {
if ($r->ID == $link->id_ps && $link->id_ps_attribute == 0) {
$r->id_hesabix = $link->id_hesabix;
} else if ($r->ID == $link->id_ps_attribute) {
$r->id_hesabix = $link->id_hesabix;
}
}
}
return array("data" => $rows, "totalCount" => $totalCount);
}
//========================================================================================================================================
/**
* @since 1.0.0
* @access public
*/
public static function hesabix_plugin_page()
{
$iconsArray = ['home', 'cog', 'box-open', 'users', 'file-invoice-dollar', 'money-check-alt', 'file-export', 'sync-alt', 'file-alt', 'cog'];
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
$setting_tabs = apply_filters('ssbhesabix_setting_tab', array(
'home' => __('Home', 'ssbhesabix'),
'api' => __('API', 'ssbhesabix'),
'catalog' => __('Catalog', 'ssbhesabix'),
'customers' => __('Customers', 'ssbhesabix'),
'invoice' => __('Invoice', 'ssbhesabix'),
'payment' => __('Payment Methods', 'ssbhesabix'),
'export' => __('Import and export data', 'ssbhesabix'),
'sync' => __('Sync', 'ssbhesabix'),
'log' => __('Log', 'ssbhesabix'),
'extra' => __('Extra Settings', 'ssbhesabix')
));
$current_tab = (isset($_GET['tab'])) ? wc_clean($_GET['tab']) : 'home';
self::hesabix_plugin_header();
?>
<h2 class="nav-tab-wrapper mt-2">
<?php
$i = 0;
foreach ($setting_tabs as $name => $label) {
$iconUrl = plugins_url("/hesabix-accounting/admin/img/icons/$iconsArray[$i].svg");
$i++;
echo '<a href="' . admin_url('admin.php?page=ssbhesabix-option&tab=' . $name) . '" class="nav-tab ' . ($current_tab == $name ? 'nav-tab-active' : '') . '">' . "<svg width='16' height='16' class='hesabix-tab-icon'><image href='$iconUrl' width='16' height='16' /></svg>" . $label . '</a>';
}
?>
</h2>
<?php
foreach ($setting_tabs as $setting_tabkey => $setting_tabvalue) {
switch ($setting_tabkey) {
case $current_tab:
do_action('ssbhesabix_' . $setting_tabkey . '_setting_save_field');
do_action('ssbhesabix_' . $setting_tabkey . '_setting');
break;
}
}
} else {
echo '<div class="wrap">' . __('Hesabix Plugin requires the WooCommerce to work!, Please install/activate woocommerce and try again', 'ssbhesabix') . '</div>';
}
}
//========================================================================================================================================
public static function hesabix_plugin_header()
{
$logoUrl = plugins_url('/hesabix-accounting/admin/img/hesabix-logo.fa.png');
?>
<div class="hesabix-header">
<div class="row">
<div class="col-auto">
<img src="<?php echo $logoUrl ?>" alt="حسابیکس">
</div>
<div class="col"></div>
<div class="col-auto">
<a class="btn btn-sm btn-success" href="https://hesabix.ir" target="_blank">ورود به
حسابیکس</a>
<a class="btn btn-sm btn-warning"
href="https://hesabix.ir/help/topics/%D8%A7%D9%81%D8%B2%D9%88%D9%86%D9%87/%D9%88%D9%88%DA%A9%D8%A7%D9%85%D8%B1%D8%B3"
target="_blank">راهنمای افزونه</a>
</div>
</div>
</div>
<?php
}
//========================================================================================================================================
}
new Ssbhesabix_Admin_Display();

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,20 @@
<?php
/**
* Hesabix Log Service
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class HesabixLogService
{
public static function writeLogStr($str)
{
$fileName = WP_CONTENT_DIR . '/ssbhesabix-' . date("20y-m-d") . '.txt';
$fileName = WP_CONTENT_DIR . '/hesabix-' . date("20y-m-d") . '.txt';
$dateTime = new DateTimeImmutable( 'now', wp_timezone() );
$dateTime = new DateTimeImmutable('now', wp_timezone());
$date = $dateTime->format('[Y-m-d H:i:s] ');
$str = $date . $str;
@ -16,7 +24,7 @@ class HesabixLogService
public static function writeLogObj($obj)
{
$fileName = WP_CONTENT_DIR . '/ssbhesabix-' . date("20y-m-d") . '.txt';
$fileName = WP_CONTENT_DIR . '/hesabix-' . date("20y-m-d") . '.txt';
ob_start();
var_dump($obj);
file_put_contents($fileName, PHP_EOL . ob_get_flush(), FILE_APPEND);
@ -24,10 +32,10 @@ class HesabixLogService
public static function log($params)
{
$fileName = WP_CONTENT_DIR . '/ssbhesabix-' . date("20y-m-d") . '.txt';
$fileName = WP_CONTENT_DIR . '/hesabix-' . date("20y-m-d") . '.txt';
$log = '';
$dateTime = new DateTimeImmutable( 'now', wp_timezone() );
$dateTime = new DateTimeImmutable('now', wp_timezone());
$date = $dateTime->format('[Y-m-d H:i:s] ');
foreach ($params as $message) {
@ -51,7 +59,7 @@ class HesabixLogService
public static function clearLog()
{
$fileName = WP_CONTENT_DIR . '/ssbhesabix-' . date("20y-m-d") . '.txt';
$fileName = WP_CONTENT_DIR . '/hesabix-' . date("20y-m-d") . '.txt';
if (file_exists($fileName)) {
file_put_contents($fileName, "");
}
@ -59,6 +67,6 @@ class HesabixLogService
public static function getLogFilePath()
{
return WP_CONTENT_DIR . '/ssbhesabix-' . date("20y-m-d") . '.txt';
return WP_CONTENT_DIR . '/hesabix-' . date("20y-m-d") . '.txt';
}
}

View file

@ -1,6 +1,14 @@
<?php
/**
* Hesabix WpFa Service
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
include_once('HesabixLogService.php');
include_once('hesabixLogService.php');
class WpFa
{
@ -10,9 +18,13 @@ class WpFa
public $idWp;
public $idWpAttribute;
public function __construct() {}
public $uidHesabix;
public static function newWpFa($id, $type, $idHesabix, $idWp, $idWpAttribute): WpFa
public function __construct()
{
}
public static function newWpFa($id, $type, $idHesabix, $idWp, $idWpAttribute, $uidHesabix): WpFa
{
$instance = new self();
$instance->id = $id;
@ -20,25 +32,28 @@ class WpFa
$instance->idHesabix = $idHesabix;
$instance->idWp = $idWp;
$instance->idWpAttribute = $idWpAttribute;
$instance->uidHesabix = $uidHesabix;
return $instance;
}
}
class HesabixWpFaService
{
public function __construct() {}
public function getWpFa($objType, $idWp, $idWpAttribute = 0)
public function __construct()
{
if (!isset($objType) || !isset($idWp)) return false;
}
public function getWpFaByWpId($objType, $idWp, $idWpAttribute = 0)
{
if (!isset($objType) || !isset($idWp))
return false;
global $wpdb;
//$row = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "ssbhesabix WHERE `id_ps` = $idWp AND `id_ps_attribute` = $idWpAttribute AND `obj_type` = '$objType'");
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}ssbhesabix
FROM {$wpdb->prefix}hesabix
WHERE `id_ps` = %d
AND `id_ps_attribute` = %d
AND `obj_type` = %s",
@ -49,11 +64,39 @@ class HesabixWpFaService
);
if (isset($row)) return $this->mapWpFa($row);
if (isset($row))
return $this->mapWpFa($row);
return null;
}
//=========================================================================================================
public function getWpFaByHesabixCode($objType, $codehx, $idWpAttribute = 0)
{
if (!isset($objType) || !isset($codehx))
return false;
global $wpdb;
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}hesabix
WHERE `id_hesabix` = %d
AND `id_ps_attribute` = %d
AND `obj_type` = %s",
$codehx,
$idWpAttribute,
$objType
)
);
if (isset($row))
return $this->mapWpFa($row);
return null;
}
public function getWpFaSearch($woocommerce_search_code = '', $woocommerce_attribute_search_code = '', $hesabix_search_code = '', $obj_type_search = '')
{
global $wpdb;
@ -81,7 +124,7 @@ class HesabixWpFaService
$params[] = $obj_type_search;
}
$sql = "SELECT * FROM {$wpdb->prefix}ssbhesabix";
$sql = "SELECT * FROM {$wpdb->prefix}hesabix";
if (!empty($conditions)) {
$sql .= " WHERE " . implode(" AND ", $conditions);
}
@ -99,18 +142,18 @@ class HesabixWpFaService
return $wpFaObjects;
}
//=========================================================================================================
public function getWpFaByHesabixId($objType, $hesabixId)
{
if (!isset($objType) || !isset($hesabixId)) return false;
if (!isset($objType) || !isset($hesabixId))
return false;
global $wpdb;
//$row = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "ssbhesabix WHERE `id_hesabix` = $hesabixId AND `obj_type` = '$objType'");
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}ssbhesabix
FROM {$wpdb->prefix}hesabix
WHERE `id_hesabix` = %d
AND `obj_type` = %s",
$hesabixId,
@ -122,19 +165,18 @@ class HesabixWpFaService
return $this->mapWpFa($row);
return null;
}
//=========================================================================================================
public function getWpFaId($objType, $idWp, $idWpAttribute = 0)
{
if (!isset($objType) || !isset($idWp))
return false;
global $wpdb;
//$row = $wpdb->get_row("SELECT `id` FROM " . $wpdb->prefix . "ssbhesabix WHERE `id_ps` = $idWp AND `id_ps_attribute` = $idWpAttribute AND `obj_type` = '$objType'");
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT `id`
FROM {$wpdb->prefix}ssbhesabix
FROM {$wpdb->prefix}hesabix
WHERE `id_ps` = %d
AND `id_ps_attribute` = %d
AND `obj_type` = %s",
@ -145,23 +187,22 @@ class HesabixWpFaService
);
if (is_object($row))
return (int)$row->id;
return (int) $row->id;
else
return false;
}
//=========================================================================================================
public function getWpFaIdByHesabixId($objType, $hesabixId)
{
if (!isset($objType) || !isset($hesabixId))
return false;
global $wpdb;
//$row = $wpdb->get_row("SELECT `id` FROM " . $wpdb->prefix . "ssbhesabix WHERE `id_hesabix` = $hesabixId AND `obj_type` = '$objType'");
$row = $wpdb->get_row(
$wpdb->prepare(
"SELECT `id`
FROM {$wpdb->prefix}ssbhesabix
FROM {$wpdb->prefix}hesabix
WHERE `id_hesabix` = %d
AND `obj_type` = %s",
$hesabixId,
@ -171,47 +212,103 @@ class HesabixWpFaService
if (isset($row))
return (int)$row->id;
return (int) $row->id;
return null;
}
//=========================================================================================================
public function getProductCodeByWpId($id_product, $id_attribute = 0)
{
$obj = $this->getWpFa('product', $id_product, $id_attribute);
$obj = $this->getWpFaByWpId('product', $id_product, $id_attribute);
if ($obj != null) return $obj->idHesabix;
if ($obj != null)
return $obj->idHesabix;
return null;
}
//=========================================================================================================
public function getProductUidByWpId($id_product, $id_attribute = 0)
{
$obj = $this->getWpFaByWpId('product', $id_product, $id_attribute);
if ($obj != null)
return $obj->uidHesabix;
return null;
}
public function getProductUidByCode($code)
{
$obj = $this->getWpFaByHesabixCode('product', $code);
if ($obj != null)
return $obj->uidHesabix;
$api = new Hesabix_Api();
$response = $api->apiRequest('api/commodity/info/' . $code);
if ($response->code == $code) {
return $response->id;
}
return null;
}
public function getCustomerCodeByWpId($id_customer)
{
$obj = $this->getWpFa('customer', $id_customer);
$obj = $this->getWpFaByWpId('customer', $id_customer);
if ($obj != null) return $obj->idHesabix;
if ($obj != null)
return $obj->idHesabix;
return null;
}
//=========================================================================================================
public function getCustomerUidByWpId($id_customer)
{
$obj = $this->getWpFaByWpId('customer', $id_customer);
if ($obj != null)
return $obj->uidHesabix;
return null;
}
public function getCustomerUidByCode($code_customer)
{
$obj = $this->getWpFaByHesabixCode('customer', $code_customer);
if ($obj != null)
return $obj->uidHesabix;
return null;
}
public function getInvoiceCodeByWpId($id_order)
{
$obj = $this->getWpFa('order', $id_order);
$obj = $this->getWpFaByWpId('order', $id_order);
if ($obj != null) return $obj->idHesabix;
if ($obj != null)
return $obj->idHesabix;
return null;
}
//=========================================================================================================
public function getInvoiceUidByWpId($id_order)
{
$obj = $this->getWpFaByWpId('order', $id_order);
if ($obj != null)
return $obj->uidHesabix;
return null;
}
public function getProductAndCombinations($idWp)
{
global $wpdb;
//$sql = "SELECT * FROM `" . $wpdb->prefix . "ssbhesabix` WHERE `obj_type` = 'product' AND `id_ps` = '$idWp'";
//$result = $wpdb->get_results($sql);
$sql = $wpdb->prepare(
"SELECT *
FROM {$wpdb->prefix}ssbhesabix
FROM {$wpdb->prefix}hesabix
WHERE `obj_type` = 'product'
AND `id_ps` = %d",
$idWp
@ -228,85 +325,93 @@ class HesabixWpFaService
}
return null;
}
//=========================================================================================================
public function mapWpFa($sqlObj): WpFa
{
$wpFa = new WpFa();
$wpFa->id = $sqlObj->id;
$wpFa->idHesabix = $sqlObj->id_hesabix;
$wpFa->uidHesabix = $sqlObj->uid_hesabix;
$wpFa->idWp = $sqlObj->id_ps;
$wpFa->idWpAttribute = $sqlObj->id_ps_attribute;
$wpFa->objType = $sqlObj->obj_type;
return $wpFa;
}
//=========================================================================================================
public function saveProduct($item): bool
{
$json = json_decode($item->Tag);
$hesabix_code = 0;
$id_product = 0;
$id_attribute = 0;
if (isset($item->code))
$hesabix_code = (int) $item->code;
if (isset($item->id))
$hesabix_uid = (int) $item->id;
if (isset($item->tags)) {
$json = $item->tags;
if (isset($json->id_product))
$id_product = (int) $json->id_product;
if (isset($json->id_attribute))
$id_attribute = (int) $json->id_attribute;
}
$wpFaService = new HesabixWpFaService();
$wpFa = $wpFaService->getWpFaByHesabixId('product', $item->Code);
$wpFa = $wpFaService->getWpFaByHesabixId('product', $hesabix_code);
if (!$wpFa) {
$wpFa = WpFa::newWpFa(0, 'product', (int)$item->Code, (int)$json->id_product, (int)$json->id_attribute);
$wpFa = WpFa::newWpFa(0, 'product', $hesabix_code, $id_product, $id_attribute, $hesabix_uid);
$wpFaService->save($wpFa);
HesabixLogService::log(array("Item successfully added. Item code: " . (string)$item->Code . ". Product ID: $json->id_product-$json->id_attribute"));
HesabixLogService::log(array("Item successfully added. Item code: $hesabix_code. Product ID: $id_product-$id_attribute"));
} else {
$wpFa->idHesabix = (int)$item->Code;
$wpFa->idHesabix = $hesabix_code;
$wpFa->uidHesabix = $hesabix_uid;
$wpFaService->update($wpFa);
HesabixLogService::log(array("Item successfully updated. Item code: " . (string)$item->Code . ". Product ID: $json->id_product-$json->id_attribute"));
HesabixLogService::log(array("Item successfully updated. Item code: $hesabix_code. Product ID: $id_product-$id_attribute"));
}
return true;
}
//=========================================================================================================
public function saveCustomer($customer): bool
{
$json = json_decode($customer->Tag);
if ((int)$json->id_customer == 0) return true;
$json = json_decode($customer->tags);
if ((int) $json->id_customer == 0)
return true;
$id = $this->getWpFaId('customer', (int)$json->id_customer);
$id = $this->getWpFaId('customer', (int) $json->id_customer);
global $wpdb;
if (!$id) {
// $wpdb->insert($wpdb->prefix . 'ssbhesabix', array(
// 'id_hesabix' => (int)$customer->Code,
// 'obj_type' => 'customer',
// 'id_ps' => (int)$json->id_customer
// ));
$wpdb->insert(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array(
'id_hesabix' => (int)$customer->Code,
'id_hesabix' => (int) $customer->code,
'uid_hesabix' => (int) $customer->id,
'obj_type' => 'customer',
'id_ps' => (int)$json->id_customer
'id_ps' => (int) $json->id_customer
),
array(
'%d',
'%d',
'%s',
'%d'
)
);
HesabixLogService::writeLogStr("Customer successfully added. Customer code: " . (string)$customer->Code . ". Customer ID: $json->id_customer");
HesabixLogService::writeLogStr("Customer successfully added. Customer code: " . (string) $customer->code . ". Customer ID: $json->id_customer");
} else {
// $wpdb->update($wpdb->prefix . 'ssbhesabix', array(
// 'id_hesabix' => (int)$customer->Code,
// 'obj_type' => 'customer',
// 'id_ps' => (int)$json->id_customer,
// ), array('id' => $id));
$wpdb->update(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array(
'id_hesabix' => (int)$customer->Code,
'id_hesabix' => (int) $customer->code,
'uid_hesabix' => (int) $customer->id,
'obj_type' => 'customer',
'id_ps' => (int)$json->id_customer,
'id_ps' => (int) $json->id_customer,
),
array('id' => $id),
array(
'%d',
'%d',
'%s',
'%d'
@ -314,165 +419,128 @@ class HesabixWpFaService
array('%d')
);
HesabixLogService::writeLogStr("Customer successfully updated. Customer code: " . (string)$customer->Code . ". Customer ID: $json->id_customer");
HesabixLogService::writeLogStr("Customer successfully updated. Customer code: " . (string) $customer->code . ". Customer ID: $json->id_customer");
}
return true;
}
//=========================================================================================================
public function saveInvoice($invoice, $orderType)
{
$json = json_decode($invoice->Tag);
$id = $this->getPsFaId('order', (int)$json->id_order);
$id = $this->getPsFaId('order', (int) $json->id_order);
$invoiceNumber = (int)$invoice->Number;
$invoiceNumber = (int) $invoice->Number;
$objType = $orderType == 0 ? 'order' : 'returnOrder';
if (!$id) {
// Db::getInstance()->insert('ps_hesabix', array(
// 'id_hesabix' => $invoiceNumber,
// 'obj_type' => $objType,
// 'id_ps' => (int)$json->id_order,
// ));
Db::getInstance()->insert('ps_hesabix', array(
'id_hesabix' => $invoiceNumber,
'obj_type' => $objType,
'id_ps' => (int)$json->id_order,
'id_ps' => (int) $json->id_order,
));
if ($objType == 'order')
LogService::writeLogStr("Invoice successfully added. invoice number: " . (string)$invoice->Number . ", order id: " . $json->id_order);
LogService::writeLogStr("Invoice successfully added. invoice number: " . (string) $invoice->Number . ", order id: " . $json->id_order);
else
LogService::writeLogStr("Return Invoice successfully added. Customer code: " . (string)$invoice->Number . ", order id: " . $json->id_order);
LogService::writeLogStr("Return Invoice successfully added. Customer code: " . (string) $invoice->Number . ", order id: " . $json->id_order);
} else {
// Db::getInstance()->update('ps_hesabix', array(
// 'id_hesabix' => $invoiceNumber,
// 'obj_type' => $objType,
// 'id_ps' => (int)$json->id_order,
// ), array('id' => $id), 0, true, true);
Db::getInstance()->update('ps_hesabix', array(
'id_hesabix' => $invoiceNumber,
'obj_type' => $objType,
'id_ps' => (int)$json->id_order,
'id_ps' => (int) $json->id_order,
), array('id' => $id), 0, true, true);
//check if it is order or return order
if ($objType == 'order')
LogService::writeLogStr("Invoice successfully updated. invoice number: " . (string)$invoice->Number . ", order id: " . $json->id_order);
LogService::writeLogStr("Invoice successfully updated. invoice number: " . (string) $invoice->Number . ", order id: " . $json->id_order);
else
LogService::writeLogStr("Return Invoice successfully updated. Customer code: " . (string)$invoice->Number . ", order id: " . $json->id_order);
LogService::writeLogStr("Return Invoice successfully updated. Customer code: " . (string) $invoice->Number . ", order id: " . $json->id_order);
}
return true;
}
//=========================================================================================================
public function save(WpFa $wpFa)
{
global $wpdb;
// $wpdb->insert($wpdb->prefix . 'ssbhesabix', array(
// 'id_hesabix' => $wpFa->idHesabix,
// 'obj_type' => $wpFa->objType,
// 'id_ps' => (int)$wpFa->idWp,
// 'id_ps_attribute' => (int)$wpFa->idWpAttribute,
// ));
$wpdb->insert(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array(
'id_hesabix' => $wpFa->idHesabix,
'obj_type' => $wpFa->objType,
'id_ps' => (int)$wpFa->idWp,
'id_ps_attribute' => (int)$wpFa->idWpAttribute,
'id_ps' => (int) $wpFa->idWp,
'id_ps_attribute' => (int) $wpFa->idWpAttribute,
'uid_hesabix' => (int) $wpFa->uidHesabix,
),
array(
'%s',
'%s',
'%d',
'%d'
'%d',
'%s'
)
);
}
//=========================================================================================================
// public function update(WpFa $wpFa)
// {
// global $wpdb;
// $wpdb->update($wpdb->prefix . 'ssbhesabix', array(
// 'id_hesabix' => $wpFa->idHesabix,
// 'obj_type' => $wpFa->objType,
// 'id_ps' => (int)$wpFa->idWp,
// 'id_ps_attribute' => (int)$wpFa->idWpAttribute,
// ), array('id' => $wpFa->id));
// }
public function update(WpFa $wpFa)
{
global $wpdb;
$idHesabix = isset($wpFa->idHesabix) ? sanitize_text_field($wpFa->idHesabix) : '';
$uidHesabix = isset($wpFa->uidHesabix) ? sanitize_text_field($wpFa->uidHesabix) : '';
$objType = isset($wpFa->objType) ? sanitize_text_field($wpFa->objType) : '';
$idWp = isset($wpFa->idWp) ? (int)$wpFa->idWp : 0;
$idWpAttribute = isset($wpFa->idWpAttribute) ? (int)$wpFa->idWpAttribute : 0;
$idWp = isset($wpFa->idWp) ? (int) $wpFa->idWp : 0;
$idWpAttribute = isset($wpFa->idWpAttribute) ? (int) $wpFa->idWpAttribute : 0;
$wpdb->update(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array(
'id_hesabix' => $idHesabix,
'obj_type' => $objType,
'id_ps' => $idWp,
'id_ps_attribute' => $idWpAttribute,
'uid_hesabix' => $uidHesabix,
),
array('id' => $wpFa->id),
array(
'%s',
'%s',
'%d',
'%d'
'%d',
'%s'
),
array('%d')
);
}
//=========================================================================================================
// public function delete(WpFa $wpFa)
// {
// global $wpdb;
// $wpdb->delete($wpdb->prefix . 'ssbhesabix', array('id' => $wpFa->id));
// }
public function delete(WpFa $wpFa)
{
global $wpdb;
$id = isset($wpFa->id) ? (int)$wpFa->id : 0;
$id = isset($wpFa->id) ? (int) $wpFa->id : 0;
$wpdb->delete(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array('id' => $id),
array('%d')
);
}
//=========================================================================================================
// public function deleteAll($productId)
// {
// global $wpdb;
// $wpdb->delete($wpdb->prefix . 'ssbhesabix', array('id_ps' => $productId));
// }
public function deleteAll($productId)
{
global $wpdb;
$productId = isset($productId) ? (int)$productId : 0;
$productId = isset($productId) ? (int) $productId : 0;
$wpdb->delete(
$wpdb->prefix . 'ssbhesabix',
$wpdb->prefix . 'hesabix',
array('id_ps' => $productId),
array('%d')
);
}
//=========================================================================================================
}

View file

@ -0,0 +1,235 @@
<?php
/**
* Hesabix Customer Service
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class HesabixCustomerService
{
public static $countries;
public static $states;
public static function mapCustomer($code, $id_customer, $type = 'first', $id_order = ''): array
{
self::getCountriesAndStates();
$customer = new WC_Customer($id_customer);
$order = new WC_Order($id_order);
$firstName = $customer->get_first_name() ?: $customer->get_billing_first_name();
$lastName = $customer->get_last_name() ?: $customer->get_billing_last_name();
$name = trim($firstName . ' ' . $lastName);
if (empty($name)) $name = __('Not Defined', 'hesabix');
$checkout_fields = HesabixCustomerService::getAdditionalCheckoutFileds($id_order);
$NationalCode = $checkout_fields['NationalCode'] ?? '';
$EconomicCode = $checkout_fields['EconomicCode'] ?? '';
$RegistrationNumber = $checkout_fields['RegistrationNumber'] ?? '';
$Website = $checkout_fields['Website'] ?? '';
$nodeFamily = get_option('hesabix_contact_automatic_save_node_family') === 'yes'
? __('Persons:', 'hesabix') . get_option('hesabix_contact_node_family') : null;
if ($type === 'shipping') {
$country_code = $order->get_shipping_country();
$state_code = $order->get_shipping_state();
$fullAddress = $order->get_shipping_address_1() . '-' . $order->get_shipping_address_2();
$city = $order->get_shipping_city();
$postalCode = $order->get_shipping_postcode();
} else {
$country_code = $order->get_billing_country();
$state_code = $order->get_billing_state();
$fullAddress = $order->get_billing_address_1() . '-' . $order->get_billing_address_2();
$city = $order->get_billing_city();
$postalCode = $order->get_billing_postcode();
}
if (strlen($fullAddress) < 5) {
$fullAddress = $customer->get_billing_address_1() . '-' . $customer->get_billing_address_2();
}
if (empty($postalCode)) {
$postalCode = $customer->get_billing_postcode();
}
if (preg_match('/^\d+$/', $city)) {
$func = new Hesabix_Admin_Functions();
$city = $func->convertCityCodeToName($city);
}
$country_name = self::$countries[$country_code] ?? '';
$state_name = self::$states[$country_code][$state_code] ?? '';
$hesabixCustomer = [
'nikename' => $name,
'name' => Hesabix_Validation::contactFirstNameValidation($firstName) . Hesabix_Validation::contactLastNameValidation($lastName),
'des' => __('Customer ID in OnlineStore: ', 'hesabix') . $id_customer,
'tel' => (strlen(preg_replace('/\D/', '', $customer->get_billing_phone())) === 11)
? Hesabix_Validation::contactPhoneValidation($customer->get_billing_phone())
: '',
'mobile' => '',
'mobile2' => '',
'address' => Hesabix_Validation::contactAddressValidation($fullAddress),
'company' => '',
'shenasemeli' => $NationalCode,
'codeeghtesadi'=> $EconomicCode,
'sabt' => $RegistrationNumber,
'keshvar' => Hesabix_Validation::contactCountryValidation($country_name),
'ostan' => Hesabix_Validation::contactStateValidation($state_name),
'shahr' => Hesabix_Validation::contactCityValidation($city),
'postalcode' => Hesabix_Validation::contactPostalCodeValidation($postalCode),
'email' => Hesabix_Validation::contactEmailValidation($customer->get_email()),
'website' => $Website,
'fax' => '',
'code' => (int) $code ?: 0,
'types' => [
[ 'label' => __('Customer', 'hesabix'), 'code' => 'customer', 'checked' => true ],
[ 'label' => __('Marketer', 'hesabix'), 'code' => 'marketer', 'checked' => false ],
[ 'label' => __('Employee', 'hesabix'), 'code' => 'emplyee', 'checked' => false ],
[ 'label' => __('Supplier', 'hesabix'),'code' => 'supplier', 'checked' => false ],
[ 'label' => __('Colleague', 'hesabix'), 'code' => 'colleague', 'checked' => false ],
[ 'label' => __('Salesman', 'hesabix'), 'code' => 'salesman', 'checked' => false ],
],
'accounts' => [],
'prelabel' => null,
'speedAccess' => false,
'tags' => json_encode([
'id_customer' => $id_customer
])
];
return self::correctCustomerData($hesabixCustomer);
}
public static function mapGuestCustomer($code, $id_order): array
{
$order = new WC_Order($id_order);
$name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
if (empty($order->get_billing_first_name()) && empty($order->get_billing_last_name())) {
$name = __('Guest Customer', 'hesabix');
}
$nodeFamily = get_option('hesabix_contact_automatic_save_node_family') == 'yes'? __('Persons:', 'hesabix') . get_option('hesabix_contact_node_family') :null;
$checkout_fields = hesabixCustomerService::getAdditionalCheckoutFileds($id_order);
$NationalCode = $checkout_fields['NationalCode'];
$EconomicCode = $checkout_fields['EconomicCode'];
$RegistrationNumber = $checkout_fields['RegistrationNumber'];
$Website = $checkout_fields['Website'];
WC()->countries->countries[ $order->shipping_country ];
$country_name = WC()->countries->countries[ $order->get_billing_country() ];
$states = WC()->countries->get_states( $order->get_billing_country() );
$state_name = $states[ $order->get_billing_state() ];
if(!$state_name) $state_name = WC()->countries->states[$order->billing_country][$order->billing_state];
if(!$state_name) $state_name = $order->get_billing_state();
$city = $order->get_billing_city();
if(preg_match('/^[0-9]+$/', $city)) {
$func = new Hesabix_Admin_Functions();
$city = $func->convertCityCodeToName($order->get_billing_city());
}
$fullAddress = $order->get_billing_address_1() . '-' . $order->get_billing_address_2();
$hesabixCustomer = array(
'Code' => $code,
'Name' => $name,
'FirstName' => Hesabix_Validation::contactFirstNameValidation($order->get_billing_first_name()),
'LastName' => Hesabix_Validation::contactLastNameValidation($order->get_billing_last_name()),
'ContactType' => 1,
'NationalCode' => $NationalCode,
'EconomicCode' => $EconomicCode,
'RegistrationNumber' => $RegistrationNumber,
'Website' => $Website,
'NodeFamily' => $nodeFamily,
'Address' => Hesabix_Validation::contactAddressValidation($fullAddress),
'City' => Hesabix_Validation::contactCityValidation($city),
'State' => Hesabix_Validation::contactStateValidation($state_name),
'Country' => Hesabix_Validation::contactCountryValidation($country_name),
'PostalCode' => Hesabix_Validation::contactPostalCodeValidation($order->get_billing_postcode()),
'Phone' => Hesabix_Validation::contactPhoneValidation($order->get_billing_phone()),
'Email' => Hesabix_Validation::contactEmailValidation($order->get_billing_email()),
'Tag' => json_encode(array('id_customer' => 0)),
'Note' => __('Customer registered as a GuestCustomer.', 'hesabix'),
);
return self::correctCustomerData($hesabixCustomer);
}
private static function getMobileFromPhone($phone) {
if(preg_match("/^09\d{9}$/", $phone))
return $phone;
else if(preg_match("/^9\d{9}$/", $phone))
return '0' . $phone;
else if(preg_match("/^989\d{9}$/", $phone))
return str_replace('98', '0' ,$phone);
else return '';
}
private static function correctCustomerData($hesabixCustomer) {
if($hesabixCustomer["Phone"] == '')
unset($hesabixCustomer["Phone"]);
else {
$mobile = self::getMobileFromPhone($hesabixCustomer["Phone"]);
if($mobile) $hesabixCustomer["Mobile"] = $mobile;
}
if($hesabixCustomer["Email"] == '') unset($hesabixCustomer["Email"]);
if($hesabixCustomer["Address"] == '') unset($hesabixCustomer["Address"]);
if($hesabixCustomer["PostalCode"] == '') unset($hesabixCustomer["PostalCode"]);
if($hesabixCustomer["City"] == '') unset($hesabixCustomer["City"]);
if($hesabixCustomer["State"] == '') unset($hesabixCustomer["State"]);
if($hesabixCustomer["Country"] == '') unset($hesabixCustomer["Country"]);
return $hesabixCustomer;
}
private static function getCountriesAndStates()
{
if (!isset(self::$countries)) {
$countries_obj = new WC_Countries();
self::$countries = $countries_obj->get_countries();
self::$states = $countries_obj->get_states();
}
}
private static function getAdditionalCheckoutFileds($id_order) {
$NationalCode = '_billing_hesabix_nationalcode';
$EconomicCode = '_billing_hesabix_economiccode';
$RegistrationNumber = '_billing_hesabix_registerationnumber';
$Website = '_billing_hesabix_website';
$NationalCode_isActive = get_option('hesabix_contact_NationalCode_checkbox_hesabix');
$EconomicCode_isActive = get_option('hesabix_contact_EconomicCode_checkbox_hesabix');
$RegistrationNumber_isActive = get_option('hesabix_contact_RegistrationNumber_checkbox_hesabix');
$Website_isActive = get_option('hesabix_contact_Website_checkbox_hesabix');
$add_additional_fileds = get_option('hesabix_contact_add_additional_checkout_fields_hesabix');
$fields = array();
if($add_additional_fileds == '1') {
$fields['NationalCode'] = get_post_meta( $id_order, $NationalCode, true) ?? null;
$fields['EconomicCode'] = get_post_meta( $id_order, $EconomicCode, true) ?? null;
$fields['RegistrationNumber'] = get_post_meta( $id_order, $RegistrationNumber, true) ?? null;
$fields['Website'] = get_post_meta( $id_order, $Website, true) ?? null;
} elseif($add_additional_fileds == '2') {
$NationalCode = get_option('hesabix_contact_NationalCode_text_hesabix');
$EconomicCode = get_option('hesabix_contact_EconomicCode_text_hesabix');
$RegistrationNumber = get_option('hesabix_contact_RegistrationNumber_text_hesabix');
$Website = get_option('hesabix_contact_Website_text_hesabix');
if($NationalCode_isActive == 'yes' && $NationalCode)
$fields['NationalCode'] = get_post_meta( $id_order, $NationalCode, true) ?? null;
if($EconomicCode_isActive == 'yes' && $EconomicCode)
$fields['EconomicCode'] = get_post_meta( $id_order, $EconomicCode, true) ?? null;
if($RegistrationNumber_isActive == 'yes' && $RegistrationNumber)
$fields['RegistrationNumber'] = get_post_meta( $id_order, $RegistrationNumber, true) ?? null;
if($Website_isActive == 'yes' && $Website)
$fields['Website'] = get_post_meta( $id_order, $Website, true) ?? null;
}
return $fields;
}
}

View file

@ -0,0 +1,140 @@
<?php
/**
* Hesabix Item Service
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class HesabixItemService
{
public static function mapProduct($product, $id, $new = true)
{
$wpFaService = new HesabixWpFaService();
$categories = $product->get_category_ids();
$code = $new ? null : $wpFaService->getProductCodeByWpId($id);
$price = $product->get_regular_price() ? $product->get_regular_price() : $product->get_price();
$hesabixItem = array(
'code' => $code,
'name' => Hesabix_Validation::itemNameValidation($product->get_title()),
'khadamat' => $product->is_virtual() == 1 ? 1 : 0,
'Tag' => json_encode(array('id_product' => $id, 'id_attribute' => 0))
);
if (get_option("hesabix_do_not_update_titles_in_hesabix", "no") === "no") {
$hesabixItem['PurchasesTitle'] = Hesabix_Validation::itemNameValidation($product->get_title());
$hesabixItem['SalesTitle'] = Hesabix_Validation::itemNameValidation($product->get_title());
}
if (!$code || get_option("hesabix_do_not_update_product_price_in_hesabix", "no") === "no")
$hesabixItem["priceSell"] = self::getPriceInHesabixDefaultCurrency($price);
if (get_option("hesabix_do_not_update_product_barcode_in_hesabix", "no") === "no")
$hesabixItem["barcodes"] = Hesabix_Validation::itemBarcodeValidation($product->get_sku());
if (get_option("hesabix_do_not_update_product_category_in_hesabix", "no") === "no")
if ($categories)
$hesabixItem["NodeFamily"] = self::getCategoryPath($categories[0]);
if (get_option("hesabix_do_not_update_product_product_code_in_hesabix", "no") === "no")
$hesabixItem["ProductCode"] = $id;
return $hesabixItem;
}
public static function mapProductVariation($product, $variation, $id_product, $new = true)
{
$wpFaService = new HesabixWpFaService();
$id_attribute = $variation->get_id();
$categories = $product->get_category_ids();
$code = $new ? null : $wpFaService->getProductCodeByWpId($id_product, $id_attribute);
$productName = $product->get_title();
$variationName = $variation->get_attribute_summary();
if (get_option("hesabix_remove_attributes_titles") == "yes" || get_option("hesabix_remove_attributes_titles") == "1") {
$values = self::getAttributesValues($variationName);
$fullName = Hesabix_Validation::itemNameValidation($productName . ' - ' . implode(", ", $values));
} else {
$fullName = Hesabix_Validation::itemNameValidation($productName . ' - ' . $variationName);
}
$price = $variation->get_regular_price() ? $variation->get_regular_price() : $variation->get_price();
$hesabixItem = array(
'code' => $code,
'name' => $fullName,
'khadamat' => $variation->is_virtual() == 1 ? 1 : 0,
'Tag' => json_encode(array(
'id_product' => $id_product,
'id_attribute' => $id_attribute
)),
);
if (get_option("hesabix_do_not_update_titles_in_hesabix", "no") === "no") {
$hesabixItem['PurchasesTitle'] = $fullName;
$hesabixItem['SalesTitle'] = $fullName;
}
if (!$code || get_option("hesabix_do_not_update_product_price_in_hesabix", "no") === "no")
$hesabixItem["SellPrice"] = self::getPriceInHesabixDefaultCurrency($price);
if (get_option("hesabix_do_not_update_product_barcode_in_hesabix", "no") === "no")
$hesabixItem["Barcode"] = Hesabix_Validation::itemBarcodeValidation($variation->get_sku());
if (get_option("hesabix_do_not_update_product_category_in_hesabix", "no") === "no")
$hesabixItem["NodeFamily"] = self::getCategoryPath($categories[0]);
if (get_option("hesabix_do_not_update_product_product_code_in_hesabix", "no") === "no")
$hesabixItem["ProductCode"] = $id_attribute;
return $hesabixItem;
}
public static function getAttributesValues($variationName)
{
$pairs = explode(",", $variationName);
$values = array();
foreach ($pairs as $pair) {
list($title, $value) = explode(":", $pair);
$values[] = trim($value);
}
return $values;
}
public static function getPriceInHesabixDefaultCurrency($price)
{
if (!isset($price))
return false;
$woocommerce_currency = get_woocommerce_currency();
$hesabix_currency = get_option('hesabix_hesabix_default_currency');
if (!is_numeric($price))
$price = intval($price);
if ($hesabix_currency == 'IRR' && $woocommerce_currency == 'IRT')
$price *= 10;
if ($hesabix_currency == 'IRT' && $woocommerce_currency == 'IRR')
$price /= 10;
return $price;
}
public static function getCategoryPath($id_category)
{
if (!isset($id_category))
return '';
$path = get_term_parents_list($id_category, 'product_cat', array(
'format' => 'name',
'separator' => ':',
'link' => false,
'inclusive' => true,
));
return substr('products: ' . $path, 0, -1);
}
}

View file

@ -1,276 +0,0 @@
<?php
class ssbhesabixCustomerService
{
public static $countries;
public static $states;
public static function mapCustomer($code, $id_customer, $type = 'first',$id_order = ''): array
{
self::getCountriesAndStates();
$customer = new WC_Customer($id_customer);
$order = new WC_Order($id_order);
$firstName = $customer->get_first_name() ? $customer->get_first_name() : $customer->get_billing_first_name();
$lastName = $customer->get_last_name() ? $customer->get_last_name() : $customer->get_billing_last_name();
$name = $firstName . ' ' . $lastName;
$nodeFamily = get_option('ssbhesabix_contact_automatic_save_node_family') == 'yes'? 'اشخاص :' . get_option('ssbhesabix_contact_node_family') : null;
//checkout fields
$checkout_fields = ssbhesabixCustomerService::getAdditionalCheckoutFileds($id_order);
$NationalCode = $checkout_fields['NationalCode'];
$EconomicCode = $checkout_fields['EconomicCode'];
$RegistrationNumber = $checkout_fields['RegistrationNumber'];
$Website = $checkout_fields['Website'];
if($NationalCode === false) $NationalCode = '';
if($EconomicCode === false) $EconomicCode = '';
if($RegistrationNumber === false) $RegistrationNumber = '';
if($Website === false) $Website = '';
if (empty($name) || $name === ' ') $name = __('Not Defined', 'ssbhesabix');
$hesabixCustomer = array();
switch ($type) {
case 'first':
//
case 'billing':
$country_name = self::$countries[$order->get_billing_country()];
$state_name = self::$states[$order->get_billing_country()][$order->get_billing_state()];
$fullAddress = $order->get_billing_address_1() . '-' . $order->get_billing_address_2();
$postalCode = $order->get_billing_postcode();
if(strlen($fullAddress) < 5) {
$fullAddress = $customer->get_billing_address_1() . '-' . $customer->get_billing_address_2();
}
if(empty($country_name))
$country_name = self::$countries[$customer->get_billing_country()];
if(empty($state_name))
$state_name = self::$states[$customer->get_billing_country()][$customer->get_billing_state()];
if(empty($postalCode))
$postalCode = $customer->get_billing_postcode();
$city = $order->get_billing_city();
if(preg_match('/^[0-9]+$/', $city)) {
$func = new Ssbhesabix_Admin_Functions();
$city = $func->convertCityCodeToName($order->get_billing_city());
}
$hesabixCustomer = array(
'code' => $code,
'nikename' => $name,
'name' => Ssbhesabix_Validation::contactFirstNameValidation($firstName) . Ssbhesabix_Validation::contactLastNameValidation($lastName),
'ContactType' => 1,
'NodeFamily' => $nodeFamily,
'shenasemeli' => $NationalCode,
'codeeghtesadi' => $EconomicCode,
'RegistrationNumber' => $RegistrationNumber,
'website' => $Website,
'address' => Ssbhesabix_Validation::contactAddressValidation($fullAddress),
'shahr' => Ssbhesabix_Validation::contactCityValidation($city),
'ostan' => Ssbhesabix_Validation::contactStateValidation($state_name),
'keshvar' => Ssbhesabix_Validation::contactCountryValidation($country_name),
'postalcode' => Ssbhesabix_Validation::contactPostalCodeValidation($postalCode),
'tel' => Ssbhesabix_Validation::contactPhoneValidation($customer->get_billing_phone()),
'emal' => Ssbhesabix_Validation::contactEmailValidation($customer->get_email()),
'Tag' => json_encode(array('id_customer' => $id_customer)),
'des' => __('Customer ID in OnlineStore: ', 'ssbhesabix') . $id_customer,
'types' => [
[
'checked'=>true,
'code'=>'customer'
]
]
);
break;
case 'shipping':
$country_name = self::$countries[$order->get_shipping_country()];
$state_name = self::$states[$order->get_shipping_country()][$order->get_shipping_state()];
$fullAddress = $order->get_shipping_address_1() . ' - ' . $order->get_shipping_address_2();
$postalCode = $order->get_shipping_postcode();
if(strlen($fullAddress) < 5)
$fullAddress = $customer->get_billing_address_1() . '-' . $customer->get_billing_address_2();
if(empty($country_name))
$country_name = self::$countries[$customer->get_billing_country()];
if(empty($state_name))
$state_name = self::$states[$customer->get_billing_country()][$customer->get_billing_state()];
if(empty($postalCode))
$postalCode = $customer->get_shipping_postcode();
$city = $order->get_shipping_city();
if(preg_match('/^[0-9]+$/', $city)) {
$func = new Ssbhesabix_Admin_Functions();
$city = $func->convertCityCodeToName($order->get_shipping_city());
}
$hesabixCustomer = array(
'code' => $code,
'nikename' => $name,
'name' => Ssbhesabix_Validation::contactFirstNameValidation($firstName) . Ssbhesabix_Validation::contactLastNameValidation($lastName),
'ContactType' => 1,
'NodeFamily' => $nodeFamily,
'shenasemeli' => $NationalCode,
'codeeghtesadi' => $EconomicCode,
'RegistrationNumber' => $RegistrationNumber,
'website' => $Website,
'address' => Ssbhesabix_Validation::contactAddressValidation($fullAddress),
'shahr' => Ssbhesabix_Validation::contactCityValidation($city),
'ostan' => Ssbhesabix_Validation::contactStateValidation($state_name),
'keshvar' => Ssbhesabix_Validation::contactCountryValidation($country_name),
'postalcode' => Ssbhesabix_Validation::contactPostalCodeValidation($postalCode),
'tel' => Ssbhesabix_Validation::contactPhoneValidation($customer->get_billing_phone()),
'email' => Ssbhesabix_Validation::contactEmailValidation($customer->get_email()),
'Tag' => json_encode(array('id_customer' => $id_customer)),
'des' => __('Customer ID in OnlineStore: ', 'ssbhesabix') . $id_customer,
'types' => [
[
'checked'=>true,
'code'=>'customer'
]
]
);
break;
}
return self::correctCustomerData($hesabixCustomer);
}
//===========================================================================================================
public static function mapGuestCustomer($code, $id_order): array
{
$order = new WC_Order($id_order);
$name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
if (empty($order->get_billing_first_name()) && empty($order->get_billing_last_name())) {
$name = __('Guest Customer', 'ssbhesabix');
}
$nodeFamily = get_option('ssbhesabix_contact_automatic_save_node_family') == 'yes'? 'اشخاص :' . get_option('ssbhesabix_contact_node_family') :null;
//checkout fields
$checkout_fields = ssbhesabixCustomerService::getAdditionalCheckoutFileds($id_order);
$NationalCode = $checkout_fields['NationalCode'];
$EconomicCode = $checkout_fields['EconomicCode'];
$RegistrationNumber = $checkout_fields['RegistrationNumber'];
$Website = $checkout_fields['Website'];
// $country_name = self::$countries[$order->get_billing_country()];
// $state_name = self::$states[$order->get_billing_state()];
WC()->countries->countries[ $order->shipping_country ];
$country_name = WC()->countries->countries[ $order->get_billing_country() ];
$states = WC()->countries->get_states( $order->get_billing_country() );
$state_name = $states[ $order->get_billing_state() ];
if(!$state_name) $state_name = WC()->countries->states[$order->billing_country][$order->billing_state];
if(!$state_name) $state_name = $order->get_billing_state();
$city = $order->get_billing_city();
if(preg_match('/^[0-9]+$/', $city)) {
$func = new Ssbhesabix_Admin_Functions();
$city = $func->convertCityCodeToName($order->get_billing_city());
}
$fullAddress = $order->get_billing_address_1() . '-' . $order->get_billing_address_2();
$hesabixCustomer = array(
'Code' => $code,
'Name' => $name,
'FirstName' => Ssbhesabix_Validation::contactFirstNameValidation($order->get_billing_first_name()),
'LastName' => Ssbhesabix_Validation::contactLastNameValidation($order->get_billing_last_name()),
'ContactType' => 1,
'NationalCode' => $NationalCode,
'EconomicCode' => $EconomicCode,
'RegistrationNumber' => $RegistrationNumber,
'Website' => $Website,
'NodeFamily' => $nodeFamily,
'Address' => Ssbhesabix_Validation::contactAddressValidation($fullAddress),
'City' => Ssbhesabix_Validation::contactCityValidation($city),
'State' => Ssbhesabix_Validation::contactStateValidation($state_name),
'Country' => Ssbhesabix_Validation::contactCountryValidation($country_name),
'PostalCode' => Ssbhesabix_Validation::contactPostalCodeValidation($order->get_billing_postcode()),
'Phone' => Ssbhesabix_Validation::contactPhoneValidation($order->get_billing_phone()),
'Email' => Ssbhesabix_Validation::contactEmailValidation($order->get_billing_email()),
'Tag' => json_encode(array('id_customer' => 0)),
'Note' => __('Customer registered as a GuestCustomer.', 'ssbhesabix'),
);
return self::correctCustomerData($hesabixCustomer);
}
//===========================================================================================================
private static function getMobileFromPhone($phone) {
if(preg_match("/^09\d{9}$/", $phone))
return $phone;
else if(preg_match("/^9\d{9}$/", $phone))
return '0' . $phone;
else if(preg_match("/^989\d{9}$/", $phone))
return str_replace('98', '0' ,$phone);
else return '';
}
//===========================================================================================================
private static function correctCustomerData($hesabixCustomer) {
if($hesabixCustomer["Phone"] == '')
unset($hesabixCustomer["Phone"]);
else {
$mobile = self::getMobileFromPhone($hesabixCustomer["Phone"]);
if($mobile) $hesabixCustomer["Mobile"] = $mobile;
}
if($hesabixCustomer["Email"] == '') unset($hesabixCustomer["Email"]);
if($hesabixCustomer["Address"] == '') unset($hesabixCustomer["Address"]);
if($hesabixCustomer["PostalCode"] == '') unset($hesabixCustomer["PostalCode"]);
if($hesabixCustomer["City"] == '') unset($hesabixCustomer["City"]);
if($hesabixCustomer["State"] == '') unset($hesabixCustomer["State"]);
if($hesabixCustomer["Country"] == '') unset($hesabixCustomer["Country"]);
return $hesabixCustomer;
}
//===========================================================================================================
private static function getCountriesAndStates()
{
if (!isset(self::$countries)) {
$countries_obj = new WC_Countries();
self::$countries = $countries_obj->get_countries();
self::$states = $countries_obj->get_states();
}
}
//===========================================================================================================
private static function getAdditionalCheckoutFileds($id_order) {
$NationalCode = '_billing_hesabix_nationalcode';
$EconomicCode = '_billing_hesabix_economiccode';
$RegistrationNumber = '_billing_hesabix_registerationnumber';
$Website = '_billing_hesabix_website';
$NationalCode_isActive = get_option('ssbhesabix_contact_NationalCode_checkbox_hesabix');
$EconomicCode_isActive = get_option('ssbhesabix_contact_EconomicCode_checkbox_hesabix');
$RegistrationNumber_isActive = get_option('ssbhesabix_contact_RegistrationNumber_checkbox_hesabix');
$Website_isActive = get_option('ssbhesabix_contact_Website_checkbox_hesabix');
$add_additional_fileds = get_option('ssbhesabix_contact_add_additional_checkout_fields_hesabix');
$fields = array();
// add additional fields to checkout
if($add_additional_fileds == '1') {
$fields['NationalCode'] = get_post_meta( $id_order, $NationalCode, true) ?? null;
$fields['EconomicCode'] = get_post_meta( $id_order, $EconomicCode, true) ?? null;
$fields['RegistrationNumber'] = get_post_meta( $id_order, $RegistrationNumber, true) ?? null;
$fields['Website'] = get_post_meta( $id_order, $Website, true) ?? null;
} elseif($add_additional_fileds == '2') {
$NationalCode = get_option('ssbhesabix_contact_NationalCode_text_hesabix');
$EconomicCode = get_option('ssbhesabix_contact_EconomicCode_text_hesabix');
$RegistrationNumber = get_option('ssbhesabix_contact_RegistrationNumber_text_hesabix');
$Website = get_option('ssbhesabix_contact_Website_text_hesabix');
if($NationalCode_isActive == 'yes' && $NationalCode)
$fields['NationalCode'] = get_post_meta( $id_order, $NationalCode, true) ?? null;
if($EconomicCode_isActive == 'yes' && $EconomicCode)
$fields['EconomicCode'] = get_post_meta( $id_order, $EconomicCode, true) ?? null;
if($RegistrationNumber_isActive == 'yes' && $RegistrationNumber)
$fields['RegistrationNumber'] = get_post_meta( $id_order, $RegistrationNumber, true) ?? null;
if($Website_isActive == 'yes' && $Website)
$fields['Website'] = get_post_meta( $id_order, $Website, true) ?? null;
}
return $fields;
}
}

View file

@ -1,119 +0,0 @@
<?php
class ssbhesabixItemService
{
public static function mapProduct($product, $id, $new = true) {
$wpFaService = new HesabixWpFaService();
$categories = $product->get_category_ids();
$code = $new ? null : $wpFaService->getProductCodeByWpId($id) ;
$price = $product->get_regular_price() ? $product->get_regular_price() : $product->get_price();
$hesabixItem = array(
'code' => $code,
'name' => Ssbhesabix_Validation::itemNameValidation($product->get_title()),
'khadamat' => $product->is_virtual() == 1 ? 1 : 0,
'Tag' => json_encode(array('id_product' => $id, 'id_attribute' => 0))
);
if(get_option("ssbhesabix_do_not_update_titles_in_hesabix", "no") === "no") {
$hesabixItem['PurchasesTitle'] = Ssbhesabix_Validation::itemNameValidation($product->get_title());
$hesabixItem['SalesTitle'] = Ssbhesabix_Validation::itemNameValidation($product->get_title());
}
if(!$code || get_option("ssbhesabix_do_not_update_product_price_in_hesabix", "no") === "no")
$hesabixItem["priceSell"] = self::getPriceInHesabixDefaultCurrency($price);
if(get_option("ssbhesabix_do_not_update_product_barcode_in_hesabix", "no") === "no")
$hesabixItem["barcodes"] = Ssbhesabix_Validation::itemBarcodeValidation($product->get_sku());
if(get_option("ssbhesabix_do_not_update_product_category_in_hesabix", "no") === "no")
if($categories) $hesabixItem["NodeFamily"] = self::getCategoryPath($categories[0]);
if(get_option("ssbhesabix_do_not_update_product_product_code_in_hesabix", "no") === "no")
$hesabixItem["ProductCode"] = $id;
return $hesabixItem;
}
//===========================================================================================================
public static function mapProductVariation($product, $variation, $id_product, $new = true) {
$wpFaService = new HesabixWpFaService();
$id_attribute = $variation->get_id();
$categories = $product->get_category_ids();
$code = $new ? null : $wpFaService->getProductCodeByWpId($id_product, $id_attribute);
$productName = $product->get_title();
$variationName = $variation->get_attribute_summary();
if(get_option("ssbhesabix_remove_attributes_titles") == "yes" || get_option("ssbhesabix_remove_attributes_titles") == "1") {
$values = self::getAttributesValues($variationName);
$fullName = Ssbhesabix_Validation::itemNameValidation($productName . ' - ' . implode(", ", $values));
} else {
$fullName = Ssbhesabix_Validation::itemNameValidation($productName . ' - ' . $variationName);
}
$price = $variation->get_regular_price() ? $variation->get_regular_price() : $variation->get_price();
$hesabixItem = array(
'code' => $code,
'name' => $fullName,
'khadamat' => $variation->is_virtual() == 1 ? 1 : 0,
'Tag' => json_encode(array(
'id_product' => $id_product,
'id_attribute' => $id_attribute
)),
);
if(get_option("ssbhesabix_do_not_update_titles_in_hesabix", "no") === "no") {
$hesabixItem['PurchasesTitle'] = $fullName;
$hesabixItem['SalesTitle'] = $fullName;
}
if(!$code || get_option("ssbhesabix_do_not_update_product_price_in_hesabix", "no") === "no") $hesabixItem["SellPrice"] = self::getPriceInHesabixDefaultCurrency($price);
if(get_option("ssbhesabix_do_not_update_product_barcode_in_hesabix", "no") === "no") $hesabixItem["Barcode"] = Ssbhesabix_Validation::itemBarcodeValidation($variation->get_sku());
if(get_option("ssbhesabix_do_not_update_product_category_in_hesabix", "no") === "no") $hesabixItem["NodeFamily"] = self::getCategoryPath($categories[0]);
if(get_option("ssbhesabix_do_not_update_product_product_code_in_hesabix", "no") === "no") $hesabixItem["ProductCode"] = $id_attribute;
return $hesabixItem;
}
//===========================================================================================================
public static function getAttributesValues($variationName) {
$pairs = explode(",", $variationName);
$values = array();
foreach ($pairs as $pair) {
list($title, $value) = explode(":", $pair);
$values[] = trim($value);
}
return $values;
}
//===========================================================================================================
public static function getPriceInHesabixDefaultCurrency($price)
{
if (!isset($price)) return false;
$woocommerce_currency = get_woocommerce_currency();
$hesabix_currency = get_option('ssbhesabix_hesabix_default_currency');
if (!is_numeric($price)) $price = intval($price);
if ($hesabix_currency == 'IRR' && $woocommerce_currency == 'IRT') $price *= 10;
if ($hesabix_currency == 'IRT' && $woocommerce_currency == 'IRR') $price /= 10;
return $price;
}
//===========================================================================================================
public static function getCategoryPath($id_category)
{
if (!isset($id_category)) return '';
$path = get_term_parents_list($id_category, 'product_cat', array(
'format' => 'name',
'separator' => ':',
'link' => false,
'inclusive' => true,
));
return substr('products: ' . $path, 0, -1);
}
//===========================================================================================================
}

File diff suppressed because it is too large Load diff

2816
assets/css/hesabix-admin.css Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 217 KiB

After

Width:  |  Height:  |  Size: 216 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 199 KiB

After

Width:  |  Height:  |  Size: 198 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 220 KiB

After

Width:  |  Height:  |  Size: 219 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 201 KiB

After

Width:  |  Height:  |  Size: 199 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 198 KiB

After

Width:  |  Height:  |  Size: 196 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 232 KiB

After

Width:  |  Height:  |  Size: 230 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 221 KiB

After

Width:  |  Height:  |  Size: 220 KiB

File diff suppressed because it is too large Load diff

Before

Width:  |  Height:  |  Size: 239 KiB

After

Width:  |  Height:  |  Size: 238 KiB

BIN
assets/img/heart.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 465 KiB

View file

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

BIN
assets/img/hesabix-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View file

Before

Width:  |  Height:  |  Size: 776 B

After

Width:  |  Height:  |  Size: 776 B

View file

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

Before

Width:  |  Height:  |  Size: 752 B

After

Width:  |  Height:  |  Size: 752 B

View file

Before

Width:  |  Height:  |  Size: 641 B

After

Width:  |  Height:  |  Size: 641 B

View file

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

Before

Width:  |  Height:  |  Size: 760 B

After

Width:  |  Height:  |  Size: 760 B

View file

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View file

Before

Width:  |  Height:  |  Size: 1 KiB

After

Width:  |  Height:  |  Size: 1 KiB

View file

Before

Width:  |  Height:  |  Size: 919 B

After

Width:  |  Height:  |  Size: 919 B

View file

Before

Width:  |  Height:  |  Size: 214 B

After

Width:  |  Height:  |  Size: 214 B

View file

Before

Width:  |  Height:  |  Size: 471 B

After

Width:  |  Height:  |  Size: 471 B

File diff suppressed because one or more lines are too long

1875
assets/js/hesabix-admin.js Normal file

File diff suppressed because it is too large Load diff

1875
assets/js/hesabix.js Normal file

File diff suppressed because it is too large Load diff

74
hesabix.php Normal file

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,56 @@
<?php
/**
* Hesabix Activator Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Activator {
public static $hesabix_db_version = '1.1';
public static function activate() {
add_option('hesabix_webhook_password', bin2hex(openssl_random_pseudo_bytes(16)));
add_option('hesabix_last_log_check_id', 0);
add_option('hesabix_live_mode', 0);
add_option('hesabix_debug_mode', 0);
add_option('hesabix_contact_address_status', 1);
add_option('hesabix_contact_node_family', __('Online Store Customers', 'hesabix'));
add_option('hesabix_contact_automaatic_save_node_family', 'yes');
add_option('hesabix_contact_automatically_save_in_hesabix', 'yes');
add_option('hesabix_activation_date', date("Y-m-d"));
add_option('hesabix_use_export_product_opening_quantity', false);
add_option('hesabix_business_expired', 0);
add_option('hesabix_do_not_submit_product_automatically', "no");
add_option('hesabix_do_not_update_product_price_in_hesabix', "no");
add_option('hesabix_contact_add_additional_checkout_fields_hesabix', 1);
add_option('hesabix_show_product_code_in_products_page', "yes");
add_option('hesabix_show_hesabix_code_in_excel_export', "yes");
self::hesabix_create_database_table();
}
public static function hesabix_create_database_table()
{
global $wpdb;
$table_name = $wpdb->prefix . "hesabix";
$charset_collate = $wpdb->get_charset_collate();
$sql = "
CREATE TABLE $table_name (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
obj_type varchar(32) NOT NULL,
id_hesabix int(11) UNSIGNED NOT NULL,
id_ps int(11) UNSIGNED NOT NULL,
id_ps_attribute int(11) UNSIGNED NOT NULL DEFAULT 0,
uid_hesabix int(11) UNSIGNED NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
update_option('hesabix_db_version', self::$hesabix_db_version);
}
}

View file

@ -0,0 +1,16 @@
<?php
/**
* Hesabix Deactivator Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Deactivator
{
public static function deactivate()
{
}
}

View file

@ -0,0 +1,23 @@
<?php
/**
* Hesabix i18n Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_i18n
{
public function load_plugin_textdomain()
{
load_plugin_textdomain(
'hesabix',
false,
dirname(dirname(plugin_basename(__FILE__))) . '/languages/'
);
}
}

View file

@ -0,0 +1,64 @@
<?php
/**
* Hesabix Loader Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Loader
{
protected $actions;
protected $filters;
public function __construct()
{
$this->actions = array();
$this->filters = array();
}
public function add_action($hook, $component, $callback, $priority = 10, $accepted_args = 1)
{
$this->actions = $this->add($this->actions, $hook, $component, $callback, $priority, $accepted_args);
}
public function add_filter($hook, $component, $callback, $priority = 10, $accepted_args = 1)
{
$this->filters = $this->add($this->filters, $hook, $component, $callback, $priority, $accepted_args);
}
private function add($hooks, $hook, $component, $callback, $priority, $accepted_args)
{
$hooks[] = array(
'hook' => $hook,
'component' => $component,
'callback' => $callback,
'priority' => $priority,
'accepted_args' => $accepted_args
);
return $hooks;
}
public function run()
{
foreach ($this->filters as $hook) {
add_filter($hook['hook'], array($hook['component'], $hook['callback']), $hook['priority'], $hook['accepted_args']);
}
foreach ($this->actions as $hook) {
add_action($hook['hook'], array($hook['component'], $hook['callback']), $hook['priority'], $hook['accepted_args']);
}
}
}

View file

@ -0,0 +1,406 @@
<?php
/**
* Hesabix Validation Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix_Validation
{
public static function itemCodeValidation($code)
{
$code = preg_replace('/[^0-9]/', '', $code);
$code = self::formatFarsiNumbers($code);
return mb_substr($code, 0, 5);
}
public static function itemNameValidation($name)
{
$name = self::formatFarsiNumbers($name);
return self::remove_emoji($name, 199);
}
public static function formatFarsiNumbers($str)
{
$farsiNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
$englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for ($i = 0; $i < 10; $i++)
$str = str_replace($farsiNumbers[$i], $englishNumbers[$i], $str);
return $str;
}
public static function itemBarcodeValidation($barcode)
{
$barcode = self::formatFarsiNumbers($barcode);
return mb_substr($barcode, 0, 999);
}
public static function itemCategoryValidation($category)
{
return $category;
}
public static function itemDescriptionValidation($description)
{
return mb_substr($description, 0, 199);
}
public static function itemMainUnitValidation($mainUnit)
{
return mb_substr($mainUnit, 0, 29);
}
public static function itemSubUnitValidation($subUnit)
{
return mb_substr($subUnit, 0, 29);
}
public static function itemConversionFactorValidation($conversionFactor)
{
if ($conversionFactor < 0) {
return 0;
} else {
return $conversionFactor;
}
}
public static function itemSalesTaxValidation($salesTax)
{
if ($salesTax >= 0 && $salesTax <= 100) {
return $salesTax;
} else {
return 0;
}
}
public static function itemSalesInfoValidation($salesInfo)
{
return mb_substr($salesInfo, 0, 99);
}
public static function itemPurchaseCostValidation($purchaseCost)
{
if ($purchaseCost >= 0) {
return $purchaseCost;
} else {
return 0;
}
}
public static function itemPurchaseInfoValidation($purchaseInfo)
{
return mb_substr($purchaseInfo, 0, 99);
}
public static function itemTagValidation($tag)
{
return mb_substr($tag, 0, 254);
}
public static function contactCodeValidation($code)
{
$code = preg_replace('/[^0-9]/', '', $code);
return mb_substr($code, 0, 5);
}
public static function contactDisplayNameValidation($displayName)
{
return mb_substr($displayName, 0, 99);
}
public static function contactCompanyValidation($company)
{
return mb_substr($company, 0, 99);
}
public static function contactTitleValidation($title)
{
return mb_substr($title, 0, 49);
}
public static function contactFirstNameValidation($firstName)
{
return mb_substr($firstName, 0, 49);
}
public static function contactLastNameValidation($lastName)
{
return mb_substr($lastName, 0, 49);
}
public static function contactAddressValidation($address)
{
return mb_substr($address, 0, 149);
}
public static function contactCountryValidation($country)
{
return mb_substr($country, 0, 49);
}
public static function contactStateValidation($state)
{
if (is_numeric($state)) {
if (is_plugin_active("persian-woocommerce-shipping/woocommerce-shipping.php")) {
$state = PWS()::get_state($state);
}
}
return mb_substr($state, 0, 49);
}
public static function contactCityValidation($city)
{
if (is_numeric($city)) {
if (is_plugin_active("persian-woocommerce-shipping/woocommerce-shipping.php")) {
$city = PWS()::get_city($city);
}
}
return mb_substr($city, 0, 49);
}
public static function contactPostalCodeValidation($postalCode)
{
$postalCode = preg_replace('/[^0-9]/', '', $postalCode);
$postalCode = self::formatFarsiNumbers($postalCode);
return mb_substr($postalCode, 0, 10);
}
public static function contactPhoneValidation($phone)
{
$phone = preg_replace('/[^0-9]/', '', $phone);
$phone = self::formatFarsiNumbers($phone);
return mb_substr($phone, 0, 14);
}
public static function contactMobileValidation($mobile)
{
$mobile = preg_replace('/[^0-9]/', '', $mobile);
return mb_substr($mobile, 0, 14);
}
public static function contactFaxValidation($fax)
{
$fax = preg_replace('/[^0-9]/', '', $fax);
return mb_substr($fax, 0, 14);
}
public static function contactEmailValidation($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
$isValid = false;
} else if
(
!preg_match(
'/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\", "", $local)
)
) {
if (
!preg_match(
'/^"(\\\\"|[^"])+"$/',
str_replace("\\\\", "", $local)
)
) {
$isValid = false;
}
}
}
if ($isValid) {
return $email;
} else {
return null;
}
}
public static function contactWebsiteValidation($website)
{
return mb_substr($website, 0, 119);
}
public static function contactNoteValidation($note)
{
return mb_substr($note, 0, 499);
}
public static function contactCategoryValidation($category)
{
return $category;
}
public static function contactTagValidation($tag)
{
return mb_substr($tag, 0, 254);
}
public static function invoiceFinancialYearValidation($financialYear)
{
return $financialYear;
}
public static function invoiceCurrencyRateValidation($currencyRate)
{
if ($currencyRate > 0) {
return $currencyRate;
} else {
return 1;
}
}
public static function invoiceNumberValidation($number)
{
return mb_substr($number, 0, 49);
}
public static function invoiceContactTitleValidation($contactTitle)
{
return mb_substr($contactTitle, 0, 199);
}
public static function invoiceDueDateValidation($dueDate)
{
return $dueDate;
}
public static function invoiceNoteValidation($note)
{
return mb_substr($note, 0, 499);
}
public static function invoiceReferenceValidation($reference)
{
return mb_substr($reference, 0, 49);
}
public static function invoiceTagValidation($tag)
{
return mb_substr($tag, 0, 254);
}
public function invoiceItemsValidation($items)
{
return $items;
}
public static function invoiceItemDescriptionValidation($description)
{
return self::remove_emoji($description, 249);
}
public static function invoiceItemQuantityValidation($quantity)
{
if ($quantity > 0) {
return $quantity;
} else {
return 1;
}
}
public static function invoiceItemUnitValidation($unit)
{
return mb_substr($unit, 0, 29);
}
public static function invoiceItemUnitPriceValidation($unitPrice)
{
if ($unitPrice >= 0) {
return $unitPrice;
} else {
return 0;
}
}
public static function invoiceItemAmountValidation($amount)
{
if ($amount >= 0) {
return $amount;
} else {
return 0;
}
}
public static function invoiceItemDiscountValidation($discount)
{
if ($discount >= 0) {
return $discount;
} else {
return 0;
}
}
public static function invoiceItemTaxValidation($tax)
{
if ($tax >= 0) {
return $tax;
} else {
return 0;
}
}
public static function invoiceItemTotalAmountValidation($totalAmount)
{
if ($totalAmount >= 0) {
return $totalAmount;
} else {
return 0;
}
}
public static function remove_emoji($string, $length = 200): string
{
$regex_alphanumeric = '/[\x{1F100}-\x{1F1FF}]/u';
$clear_string = preg_replace($regex_alphanumeric, '', $string);
$regex_symbols = '/[\x{1F300}-\x{1F5FF}]/u';
$clear_string = preg_replace($regex_symbols, '', $clear_string);
$regex_emoticons = '/[\x{1F600}-\x{1F64F}]/u';
$clear_string = preg_replace($regex_emoticons, '', $clear_string);
$regex_transport = '/[\x{1F680}-\x{1F6FF}]/u';
$clear_string = preg_replace($regex_transport, '', $clear_string);
$regex_supplemental = '/[\x{1F900}-\x{1F9FF}]/u';
$clear_string = preg_replace($regex_supplemental, '', $clear_string);
$regex_misc = '/[\x{2600}-\x{26FF}\x{1F7E9}-\x{1F7EF}]/u';
$clear_string = preg_replace($regex_misc, '', $clear_string);
$regex_dingbats = '/[\x{2700}-\x{27BF}]/u';
$clear_string = preg_replace($regex_dingbats, '', $clear_string);
$truncated_string = mb_substr($clear_string, 0, $length);
return $truncated_string;
}
}

View file

@ -1,352 +1,358 @@
<?php
include_once(plugin_dir_path(__DIR__) . 'admin/services/HesabixLogService.php');
include_once(plugin_dir_path(__DIR__) . 'admin/services/HesabixWpFaService.php');
/*
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
class Ssbhesabix_Webhook
{
public $invoicesObjectId = array();
public $invoiceItemsCode = array();
public $itemsObjectId = array();
public $contactsObjectId = array();
public $warehouseReceiptsObjectId = array();
public function __construct()
{
//hesabixLogService::writeLogStr("Calling Webhook");
$wpFaService = new HesabixWpFaService();
$hesabixApi = new Ssbhesabix_Api();
$lastChange = get_option('ssbhesabix_last_log_check_id');
$changes = $hesabixApi->settingGetChanges($lastChange + 1);
if ($changes->Success) {
update_option('ssbhesabix_business_expired', 0);
foreach ($changes->Result as $item) {
if (!$item->API) {
switch ($item->ObjectType) {
case 'Invoice':
if ($item->Action == 123) {
$wpFa1 = $wpFaService->getWpFaByHesabixId('order', $item->Extra2);
if($wpFa1) {
$wpFaService->delete($wpFa1);
HesabixLogService::writeLogStr("The invoice link with the order deleted. Invoice number: " . $item->Extra2 . ", Order id: " . $wpFa1->idWp);
}
}
$this->invoicesObjectId[] = $item->ObjectId;
foreach (explode(',', $item->Extra) as $invoiceItem) {
if ($invoiceItem != '') {
$this->invoiceItemsCode[] = $invoiceItem;
}
}
break;
case 'WarehouseReceipt':
if ($item->Action == 261) {
global $wpdb;
$hesabixApi = new Ssbhesabix_Api();
$receipt = $hesabixApi->getWarehouseReceipt($item->ObjectId);
// HesabixLogService::writeLogObj($receipt->Result->Items);
foreach ($receipt->Result->Items as $receiptItem) {
$wpFa = $wpFaService->getWpFaByHesabixId('product', $receiptItem->ItemCode);
$wpdb->insert($wpdb->prefix . 'ssbhesabix', array(
'id_hesabix' => (int)$item->ObjectId,
'obj_type' => "receiptItems",
'id_ps' => $wpFa->idWp,
'id_ps_attribute' => $wpFa->idWpAttribute
));
}
if (get_option('ssbhesabix_item_update_quantity', 'no') == 'no') {
HesabixLogService::writeLogStr("Sync Products Quantity is Off");
}
}
if ($item->Action == 263) {
global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "ssbhesabix` WHERE `id_hesabix` = $item->ObjectId");
$receiptID = $item->ObjectId;
foreach ($rows as $row) {
$post_id = ($row->id_ps_attribute && $row->id_ps_attribute > 0) ? $row->id_ps_attribute : $row->id_ps;
//$product = wc_get_product( $post_id );
if (get_option('ssbhesabix_item_update_quantity', 'no') == 'no') {
HesabixLogService::writeLogStr("Sync Products Quantity is Off");
}
$productId = $row->id_ps;
$attributeId = $row->id_ps_attribute;
if (get_option('ssbhesabix_item_update_quantity', 'no') == 'yes')
update_post_meta($attributeId, '_manage_stock', 'yes');
if ($productId == $attributeId) $attributeId = 0;
$result = array();
$wpFaService = new HesabixWpFaService();
$wpFa = $wpFaService->getWpFa('product', $productId, $attributeId);
if ($wpFa) {
$api = new Ssbhesabix_Api();
$warehouse = get_option('ssbhesabix_item_update_quantity_based_on', "-1");
if ($warehouse == "-1")
$response = $api->itemGet($wpFa->idHesabix);
else {
$response = $api->itemGetQuantity($warehouse, array($wpFa->idHesabix));
}
if ($response->Success) {
$item = $warehouse == "-1" ? $response->Result : $response->Result[0];
$newProps = Ssbhesabix_Admin_Functions::setItemChanges($item);
} else {
HesabixLogService::writeLogStr("Product is not defined in Hesabix");
}
}
}
$wpdb->delete($wpdb->prefix . 'ssbhesabix', array('id_hesabix' => $receiptID));
break;
}
$this->warehouseReceiptsObjectId[] = $item->ObjectId;
break;
case 'Product':
if ($item->Action == 53) {
$wpFa = $wpFaService->getWpFaByHesabixId('product', $item->Extra);
if ($wpFa) {
global $wpdb;
$wpdb->delete($wpdb->prefix . 'ssbhesabix', array('id' => $wpFa->id));
}
break;
}
$this->itemsObjectId[] = $item->ObjectId;
break;
case 'Contact':
if ($item->Action == 33) {
$id_obj = $wpFaService->getWpFaIdByHesabixId('customer', $item->Extra);
global $wpdb;
$wpdb->delete($wpdb->prefix . 'ssbhesabix', array('id' => $id_obj));
break;
}
$this->contactsObjectId[] = $item->ObjectId;
break;
}
}
}
$this->invoiceItemsCode = array_unique($this->invoiceItemsCode);
$this->contactsObjectId = array_unique($this->contactsObjectId);
$this->itemsObjectId = array_unique($this->itemsObjectId);
$this->invoicesObjectId = array_unique($this->invoicesObjectId);
$this->setChanges();
$lastChange = end($changes->Result);
if (is_object($lastChange))
update_option('ssbhesabix_last_log_check_id', $lastChange->Id);
else if ($changes->LastId)
update_option('ssbhesabix_last_log_check_id', $changes->LastId);
} else {
HesabixLogService::log(array("ssbhesabix - Cannot check last changes. Error Message: " . (string)$changes->ErrorMessage . ". Error Code: " . (string)$changes->ErrorCode));
if ($changes->ErrorCode == 108) {
update_option('ssbhesabix_business_expired', 1);
add_action('admin_notices', array(__CLASS__, 'ssbhesabix_business_expired_notice'));
}
return false;
}
return true;
}
//=================================================================================================================================
public function ssbhesabix_business_expired_notice()
{
echo '<div class="error"><p>' . __('Cannot connect to Hesabix. Business expired.', 'ssbhesabix') . '</p></div>';
}
//=================================================================================================================================
public function setChanges()
{
//Items
$items = array();
if (!empty($this->warehouseReceiptsObjectId)) {
$receipts = $this->getObjectsByIdList($this->warehouseReceiptsObjectId, 'WarehouseReceipt');
if ($receipts != false) {
foreach ($receipts as $receipt) {
foreach ($receipt->Items as $item)
array_push($this->invoiceItemsCode, $item->ItemCode);
}
}
}
if (!empty($this->itemsObjectId)) {
$objects = $this->getObjectsByIdList($this->itemsObjectId, 'item');
if ($objects != false) {
foreach ($objects as $object) {
array_push($items, $object);
}
}
}
if (!empty($this->invoiceItemsCode)) {
$objects = $this->getObjectsByCodeList($this->invoiceItemsCode);
if ($objects != false) {
foreach ($objects as $object) {
array_push($items, $object);
}
}
}
if (!empty($items)) {
update_option("ssbhesabix_inside_product_edit", 1);
try {
foreach ($items as $item) {
Ssbhesabix_Admin_Functions::setItemChanges($item);
}
} catch (Exception $e) {
} finally {
update_option("ssbhesabix_inside_product_edit", 0);
}
}
return true;
}
//=================================================================================================================================
public function setInvoiceChanges($invoice)
{
if (!is_object($invoice)) return false;
$wpFaService = new HesabixWpFaService();
$number = $invoice->Number;
$json = json_decode($invoice->Tag);
if (is_object($json)) {
$id_order = $json->id_order;
} else {
$id_order = 0;
}
if ($invoice->InvoiceType == 0) {
if ($id_order == 0) {
HesabixLogService::log(array("This invoice is not defined in OnlineStore. Invoice Number: " . $number));
} else {
//check if order exist in wooCommerce
$id_obj = $wpFaService->getWpFaId('order', $id_order);
if ($id_obj != false) {
global $wpdb;
$row = $wpdb->get_row("SELECT `id_hesabix` FROM `" . $wpdb->prefix . "ssbhesabix` WHERE `id` = $id_obj");
if (is_object($row) && $row->id_hesabix != $number) {
$id_hesabix_old = $row->id_hesabix;
//ToDo: number must be int in hesabix
$wpdb->update($wpdb->prefix . 'ssbhesabix', array('id_hesabix' => $number), array('id' => $id_obj));
HesabixLogService::log(array("Invoice Number changed. Old Number: $id_hesabix_old. New ID: $number"));
}
}
}
}
}
//=================================================================================================================================
public function setContactChanges($contact)
{
if (!is_object($contact)) return false;
$code = $contact->Code;
$json = json_decode($contact->Tag);
if (is_object($json)) {
$id_customer = $json->id_customer;
} else {
$id_customer = 0;
}
if ($id_customer == 0) {
HesabixLogService::log(array("This Customer is not define in OnlineStore. Customer code: $code"));
return false;
}
$wpFaService = new HesabixWpFaService();
$id_obj = $wpFaService->getWpFaId('customer', $id_customer);
if ($id_obj != false) {
global $wpdb;
$row = $wpdb->get_row("SELECT `id_hesabix` FROM `" . $wpdb->prefix . "ssbhesabix` WHERE `id` = $id_obj");
if (is_object($row) && $row->id_hesabix != $code) {
$id_hesabix_old = $row->id_hesabix;
$wpdb->update($wpdb->prefix . 'ssbhesabix', array('id_hesabix' => (int)$code), array('id' => $id_obj));
HesabixLogService::log(array("Contact Code changed. Old ID: $id_hesabix_old. New ID: $code"));
}
}
return true;
}
//=================================================================================================================================
public function getObjectsByIdList($idList, $type)
{
$hesabixApi = new Ssbhesabix_Api();
$warehouseCode = get_option('ssbhesabix_item_update_quantity_based_on');
switch ($type) {
case 'item':
if($warehouseCode == '-1') {
$result = $hesabixApi->itemGetById($idList);
} else {
$items = $hesabixApi->itemGetById($idList);
$codeList = [];
foreach ($items->Result as $item) {
array_push($codeList, $item->Code);
}
$result = $hesabixApi->itemGetQuantity($warehouseCode, $codeList);
}
break;
case 'contact':
$result = $hesabixApi->contactGetById($idList);
break;
case 'invoice':
$result = $hesabixApi->invoiceGetInvoices(array("Filters" => array("Property" => "Id", "Operator" => "in", "Value" => $idList)));
break;
case 'WarehouseReceipt':
$result = $hesabixApi->warehouseReceiptGetByIdList($idList);
break;
default:
return false;
}
if (is_object($result) && $result->Success) {
return $result->Result;
}
return false;
}
//=================================================================================================================================
public function getObjectsByCodeList($codeList)
{
$hesabixApi = new Ssbhesabix_Api();
$warehouse = get_option('ssbhesabix_item_update_quantity_based_on', "-1");
if ($warehouse == "-1")
$result = $hesabixApi->itemGetItemsByCodes($codeList);
else {
$result = $hesabixApi->itemGetQuantity($warehouse, $codeList);
}
//$result = $hesabixApi->itemGetItems($queryInfo);
if (is_object($result) && $result->Success) {
return $warehouse == "-1" ? $result->Result->List : $result->Result;
}
return false;
}
}
<?php
/**
* Hesabix Webhook Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
include_once(dirname(__FILE__) . '/../admin/services/hesabixLogService.php');
include_once(dirname(__FILE__) . '/../admin/services/hesabixWpFaService.php');
class Hesabix_Webhook
{
public $invoicesObjectId = array();
public $invoiceItemsCode = array();
public $itemsObjectId = array();
public $contactsObjectId = array();
public $warehouseReceiptsObjectId = array();
public function __construct()
{
$wpFaService = new HesabixWpFaService();
$hesabixApi = new Hesabix_Api();
$lastChange = get_option('hesabix_last_log_check_id');
$changes = $hesabixApi->settingGetChanges($lastChange + 1);
if ($changes->Success) {
update_option('hesabix_business_expired', 0);
foreach ($changes->Result as $item) {
if (!$item->API) {
switch ($item->ObjectType) {
case 'Invoice':
if ($item->Action == 123) {
$wpFa1 = $wpFaService->getWpFaByHesabixId('order', $item->Extra2);
if ($wpFa1) {
$wpFaService->delete($wpFa1);
HesabixLogService::writeLogStr("The invoice link with the order deleted. Invoice number: " . $item->Extra2 . ", Order id: " . $wpFa1->idWp);
}
}
$this->invoicesObjectId[] = $item->ObjectId;
foreach (explode(',', $item->Extra) as $invoiceItem) {
if ($invoiceItem != '') {
$this->invoiceItemsCode[] = $invoiceItem;
}
}
break;
case 'WarehouseReceipt':
if ($item->Action == 261) {
global $wpdb;
$hesabixApi = new Hesabix_Api();
$receipt = $hesabixApi->getWarehouseReceipt($item->ObjectId);
foreach ($receipt->Result->Items as $receiptItem) {
$wpFa = $wpFaService->getWpFaByHesabixId('product', $receiptItem->ItemCode);
$wpdb->insert($wpdb->prefix . 'hesabix', array(
'id_hesabix' => (int) $item->ObjectId,
'obj_type' => "receiptItems",
'id_ps' => $wpFa->idWp,
'id_ps_attribute' => $wpFa->idWpAttribute
));
}
if (get_option('hesabix_item_update_quantity', 'no') == 'no') {
HesabixLogService::writeLogStr("Sync Products Quantity is Off");
}
}
if ($item->Action == 263) {
global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "hesabix` WHERE `id_hesabix` = $item->ObjectId");
$receiptID = $item->ObjectId;
foreach ($rows as $row) {
$post_id = ($row->id_ps_attribute && $row->id_ps_attribute > 0) ? $row->id_ps_attribute : $row->id_ps;
if (get_option('hesabix_item_update_quantity', 'no') == 'no') {
HesabixLogService::writeLogStr("Sync Products Quantity is Off");
}
$productId = $row->id_ps;
$attributeId = $row->id_ps_attribute;
if (get_option('hesabix_item_update_quantity', 'no') == 'yes')
update_post_meta($attributeId, '_manage_stock', 'yes');
if ($productId == $attributeId)
$attributeId = 0;
$result = array();
$wpFaService = new HesabixWpFaService();
$wpFa = $wpFaService->getWpFa('product', $productId, $attributeId);
if ($wpFa) {
$api = new Hesabix_Api();
// $warehouse = get_option('hesabix_item_update_quantity_based_on', "-1");
// if ($warehouse == "-1")
// $response = $api->itemGet($wpFa->idHesabix);
// else {
// $response = $api->itemGetQuantity($warehouse, array($wpFa->idHesabix));
// }
$response = $api->itemGet($wpFa->idHesabix);
if ($response->Success) {
// $item = $warehouse == "-1" ? $response->Result : $response->Result[0];
$item = $response->Result;
$newProps = Hesabix_Admin_Functions::setItemChanges($item);
} else {
HesabixLogService::writeLogStr("Product is not defined in Hesabix");
}
}
}
$wpdb->delete($wpdb->prefix . 'hesabix', array('id_hesabix' => $receiptID));
break;
}
$this->warehouseReceiptsObjectId[] = $item->ObjectId;
break;
case 'Product':
if ($item->Action == 53) {
$wpFa = $wpFaService->getWpFaByHesabixId('product', $item->Extra);
if ($wpFa) {
global $wpdb;
$wpdb->delete($wpdb->prefix . 'hesabix', array('id' => $wpFa->id));
}
break;
}
$this->itemsObjectId[] = $item->ObjectId;
break;
case 'Contact':
if ($item->Action == 33) {
$id_obj = $wpFaService->getWpFaIdByHesabixId('customer', $item->Extra);
global $wpdb;
$wpdb->delete($wpdb->prefix . 'hesabix', array('id' => $id_obj));
break;
}
$this->contactsObjectId[] = $item->ObjectId;
break;
}
}
}
$this->invoiceItemsCode = array_unique($this->invoiceItemsCode);
$this->contactsObjectId = array_unique($this->contactsObjectId);
$this->itemsObjectId = array_unique($this->itemsObjectId);
$this->invoicesObjectId = array_unique($this->invoicesObjectId);
$this->setChanges();
$lastChange = end($changes->Result);
if (is_object($lastChange))
update_option('hesabix_last_log_check_id', $lastChange->Id);
else if ($changes->LastId)
update_option('hesabix_last_log_check_id', $changes->LastId);
} else {
HesabixLogService::log(array("hesabix - Cannot check last changes. Error Message: " . (string) $changes->ErrorMessage . ". Error Code: " . (string) $changes->ErrorCode));
if ($changes->ErrorCode == 108) {
update_option('hesabix_business_expired', 1);
add_action('admin_notices', array(__CLASS__, 'hesabix_business_expired_notice'));
}
return false;
}
return true;
}
public function hesabix_business_expired_notice()
{
echo '<div class="error"><p>' . __('Cannot connect to Hesabix. Business expired.', 'hesabix') . '</p></div>';
}
public function setChanges()
{
$items = array();
if (!empty($this->warehouseReceiptsObjectId)) {
$receipts = $this->getObjectsByIdList($this->warehouseReceiptsObjectId, 'WarehouseReceipt');
if ($receipts != false) {
foreach ($receipts as $receipt) {
foreach ($receipt->Items as $item)
array_push($this->invoiceItemsCode, $item->ItemCode);
}
}
}
if (!empty($this->itemsObjectId)) {
$objects = $this->getObjectsByIdList($this->itemsObjectId, 'item');
if ($objects != false) {
foreach ($objects as $object) {
array_push($items, $object);
}
}
}
if (!empty($this->invoiceItemsCode)) {
$objects = $this->getObjectsByCodeList($this->invoiceItemsCode);
if ($objects != false) {
foreach ($objects as $object) {
array_push($items, $object);
}
}
}
if (!empty($items)) {
update_option("hesabix_inside_product_edit", 1);
try {
foreach ($items as $item) {
Hesabix_Admin_Functions::setItemChanges($item);
}
} catch (Exception $e) {
} finally {
update_option("hesabix_inside_product_edit", 0);
}
}
return true;
}
public function setInvoiceChanges($invoice)
{
if (!is_object($invoice))
return false;
$wpFaService = new HesabixWpFaService();
$number = $invoice->Number;
$json = json_decode($invoice->Tag);
if (is_object($json)) {
$id_order = $json->id_order;
} else {
$id_order = 0;
}
if ($invoice->InvoiceType == 0) {
if ($id_order == 0) {
HesabixLogService::log(array("This invoice is not defined in OnlineStore. Invoice Number: " . $number));
} else {
$id_obj = $wpFaService->getWpFaId('order', $id_order);
if ($id_obj != false) {
global $wpdb;
$row = $wpdb->get_row("SELECT `id_hesabix` FROM `" . $wpdb->prefix . "hesabix` WHERE `id` = $id_obj");
if (is_object($row) && $row->id_hesabix != $number) {
$id_hesabix_old = $row->id_hesabix;
$wpdb->update($wpdb->prefix . 'hesabix', array('id_hesabix' => $number), array('id' => $id_obj));
HesabixLogService::log(array("Invoice Number changed. Old Number: $id_hesabix_old. New ID: $number"));
}
}
}
}
}
public function setContactChanges($contact)
{
if (!is_object($contact))
return false;
$code = $contact->Code;
$json = json_decode($contact->Tag);
if (is_object($json)) {
$id_customer = $json->id_customer;
} else {
$id_customer = 0;
}
if ($id_customer == 0) {
HesabixLogService::log(array("This Customer is not define in OnlineStore. Customer code: $code"));
return false;
}
$wpFaService = new HesabixWpFaService();
$id_obj = $wpFaService->getWpFaId('customer', $id_customer);
if ($id_obj != false) {
global $wpdb;
$row = $wpdb->get_row("SELECT `id_hesabix` FROM `" . $wpdb->prefix . "hesabix` WHERE `id` = $id_obj");
if (is_object($row) && $row->id_hesabix != $code) {
$id_hesabix_old = $row->id_hesabix;
$wpdb->update($wpdb->prefix . 'hesabix', array('id_hesabix' => (int) $code), array('id' => $id_obj));
HesabixLogService::log(array("Contact Code changed. Old ID: $id_hesabix_old. New ID: $code"));
}
}
return true;
}
public function getObjectsByIdList($idList, $type)
{
$hesabixApi = new Hesabix_Api();
// $warehouseCode = get_option('hesabix_item_update_quantity_based_on');
switch ($type) {
case 'item':
// if ($warehouseCode == '-1') {
$result = $hesabixApi->itemGetById($idList);
// } else {
// $items = $hesabixApi->itemGetById($idList);
// $codeList = [];
// foreach ($items->Result as $item) {
// array_push($codeList, $item->Code);
// }
// $result = $hesabixApi->itemGetQuantity($warehouseCode, $codeList);
// }
break;
case 'contact':
$result = $hesabixApi->contactGetById($idList);
break;
case 'invoice':
$result = $hesabixApi->invoiceGetInvoices(array("Filters" => array("Property" => "Id", "Operator" => "in", "Value" => $idList)));
break;
case 'WarehouseReceipt':
$result = $hesabixApi->warehouseReceiptGetByIdList($idList);
break;
default:
return false;
}
if (is_object($result) && $result->Success) {
return $result->Result;
}
return false;
}
public function getObjectsByCodeList($codeList)
{
$hesabixApi = new Hesabix_Api();
// $warehouse = get_option('hesabix_item_update_quantity_based_on', "-1");
// if ($warehouse == "-1")
// $result = $hesabixApi->itemGetItemsByCodes($codeList);
// else {
// $result = $hesabixApi->itemGetQuantity($warehouse, $codeList);
// }
$result = $hesabixApi->itemGetItemsByCodes($codeList);
if (is_object($result) && $result->Success) {
// return $warehouse == "-1" ? $result->Result->List : $result->Result;
return $result->Result->List;
}
return false;
}
}

159
includes/class-hesabix.php Normal file
View file

@ -0,0 +1,159 @@
<?php
/**
* Main Hesabix Plugin Class
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
class Hesabix
{
protected $loader;
protected $plugin_name;
protected $version;
public function __construct()
{
if (defined('HESABIX_VERSION')) {
$this->version = HESABIX_VERSION;
} else {
$this->version = '0.0.1';
}
$this->plugin_name = 'hesabix';
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
}
private function load_dependencies()
{
require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-hesabix-loader.php';
require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-hesabix-i18n.php';
require_once plugin_dir_path(dirname(__FILE__)) . '/admin/class-hesabix-admin.php';
require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-hesabix-api.php';
$this->loader = new Hesabix_Loader();
require_once plugin_dir_path(dirname(__FILE__)) . '/includes/class-hesabix-validation.php';
$this->loader = new Hesabix_Loader();
}
private function set_locale()
{
$plugin_i18n = new Hesabix_i18n();
$this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');
}
private function define_admin_hooks()
{
$plugin_admin = new Hesabix_Admin($this->get_plugin_name(), $this->get_version());
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
$this->loader->add_filter('query_vars', $plugin_admin, 'hesabix_query_vars');
$this->loader->add_action('parse_request', $plugin_admin, 'hesabix_parse_request');
$this->loader->add_action('wp_ajax_nopriv_handle_webhook_request', $plugin_admin, 'hesabix_parse_request');
$this->loader->add_action('wp_ajax_handle_webhook_request', $plugin_admin, 'hesabix_parse_request');
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
$this->loader->add_action('init', $plugin_admin, 'hesabix_init_internal');
if (get_option('hesabix_live_mode')) {
if (get_option('hesabix_hesabix_default_currency') === 0) {
$this->loader->add_action('admin_notices', $plugin_admin, 'hesabix_currency_notice');
}
if (get_option('hesabix_show_hesabix_code_in_excel_export', 'no') == 'yes' || get_option('hesabix_show_hesabix_code_in_excel_export', 0) == 1) {
$this->loader->add_filter('woocommerce_product_export_column_names', $plugin_admin, 'admin_product_add_column');
$this->loader->add_filter('woocommerce_product_export_product_default_columns', $plugin_admin, 'admin_product_add_column');
$this->loader->add_filter('woocommerce_product_export_rows', $plugin_admin, 'admin_product_export_rows', 10, 2);
}
if (get_option('hesabix_show_product_code_in_products_page') === 'yes' || get_option('hesabix_show_product_code_in_products_page', 0) == 1) {
$this->loader->add_filter('manage_edit-product_columns', $plugin_admin, 'admin_products_hesabixId_column', 12);
$this->loader->add_action('manage_product_posts_custom_column', $plugin_admin, 'admin_products_hesabixId_column_content', 10, 2);
$this->loader->add_filter('manage_edit-product_sortable_columns', $plugin_admin, 'admin_products_hesabixId_column');
}
$this->loader->add_action('custom_product_tabs', $plugin_admin, 'hesabix_general_notices');
$this->loader->add_filter('bulk_actions-edit-shop_order', $plugin_admin, 'custom_orders_list_bulk_action', 20, 1);
$this->loader->add_filter('handle_bulk_actions-edit-shop_order', $plugin_admin, 'custom_orders_list_bulk_action_run', 10, 3);
if (get_option('woocommerce_custom_orders_table_enabled') == 'yes') {
$this->loader->add_filter('woocommerce_shop_order_list_table_columns', $plugin_admin, 'custom_hesabix_column_order_list', 20);
$this->loader->add_action('woocommerce_shop_order_list_table_custom_column', $plugin_admin, 'custom_orders_list_column_content', 10, 2);
} else {
$this->loader->add_filter('manage_edit-shop_order_columns', $plugin_admin, 'custom_hesabix_column_order_list', 20);
$this->loader->add_action('manage_shop_order_posts_custom_column', $plugin_admin, 'custom_orders_list_column_content', 20, 2);
}
$this->loader->add_filter('woocommerce_checkout_fields', $plugin_admin, 'add_additional_fields_to_checkout', 10, 3);
$this->loader->add_action('woocommerce_admin_order_data_after_billing_address', $plugin_admin, 'show_additional_fields_in_order_detail', 10, 3);
$this->loader->add_action('woocommerce_order_status_changed', $plugin_admin, 'hesabix_hook_order_status_change', 10, 3);
$this->loader->add_filter('woocommerce_order_status_changed', $plugin_admin, 'hesabix_hook_payment_confirmation', 11, 3);
$this->loader->add_action('woocommerce_new_order', $plugin_admin, 'hesabix_hook_new_order', 11, 2);
$this->loader->add_action('edit_user_profile', $plugin_admin, 'hesabix_hook_edit_user');
$this->loader->add_action('user_register', $plugin_admin, 'hesabix_hook_user_register');
$this->loader->add_action('personal_options_update', $plugin_admin, 'hesabix_hook_user_register');
$this->loader->add_action('profile_update', $plugin_admin, 'hesabix_hook_user_register');
$this->loader->add_action('delete_user', $plugin_admin, 'hesabix_hook_delete_user');
$this->loader->add_action('woocommerce_update_product', $plugin_admin, 'hesabix_hook_new_product');
$this->loader->add_action('before_delete_post', $plugin_admin, 'hesabix_hook_delete_product');
$this->loader->add_action('woocommerce_product_options_general_product_data', $plugin_admin, 'hesabix_hook_product_options_general_product_data');
$this->loader->add_action('woocommerce_process_product_meta', $plugin_admin, 'hesabix_hook_process_product_meta');
$this->loader->add_action('woocommerce_product_after_variable_attributes', $plugin_admin, 'hesabix_hook_product_after_variable_attributes', 10, 3);
$this->loader->add_action('woocommerce_save_product_variation', $plugin_admin, 'hesabix_hook_save_product_variation', 10, 3);
$this->loader->add_filter('woocommerce_product_data_tabs', $plugin_admin, 'add_hesabix_product_data_tab');
$this->loader->add_action('woocommerce_product_data_panels', $plugin_admin, 'add_hesabix_product_data_fields');
} elseif (!get_option('hesabix_live_mode')) {
if (get_option('hesabix_business_expired')) {
$this->loader->add_action('admin_notices', $plugin_admin, 'hesabix_business_expired_notice');
} else {
$this->loader->add_action('admin_notices', $plugin_admin, 'hesabix_live_mode_notice');
}
}
$this->loader->add_filter('wp_ajax_adminExportProducts', $plugin_admin, 'adminExportProductsCallback');
$this->loader->add_filter('wp_ajax_adminImportProducts', $plugin_admin, 'adminImportProductsCallback');
$this->loader->add_filter('wp_ajax_adminExportProductsOpeningQuantity', $plugin_admin, 'adminExportProductsOpeningQuantityCallback');
$this->loader->add_filter('wp_ajax_adminExportCustomers', $plugin_admin, 'adminExportCustomersCallback');
$this->loader->add_filter('wp_ajax_adminSyncChanges', $plugin_admin, 'adminSyncChangesCallback');
$this->loader->add_filter('wp_ajax_admin_sync_products', $plugin_admin, 'admin_sync_products_callback');
$this->loader->add_filter('wp_ajax_admin_sync_orders', $plugin_admin, 'admin_sync_orders_callback');
$this->loader->add_filter('wp_ajax_admin_update_products', $plugin_admin, 'admin_update_products_callback');
$this->loader->add_filter('wp_ajax_admin_update_wc_products', $plugin_admin, 'admin_update_wc_products_callback');
$this->loader->add_filter('wp_ajax_adminUpdateProductsWithFilter', $plugin_admin, 'adminUpdateProductsWithFilterCallback');
$this->loader->add_filter('wp_ajax_adminSubmitInvoice', $plugin_admin, 'adminSubmitInvoiceCallback');
$this->loader->add_filter('wp_ajax_hesabix_update_customers', $plugin_admin, 'hesabix_update_customers_ajax');
$this->loader->add_filter('wp_ajax_adminCleanLogFile', $plugin_admin, 'adminCleanLogFileCallback');
$this->loader->add_filter('wp_ajax_adminClearPluginData', $plugin_admin, 'adminClearPluginDataCallback', 10, 4);
$this->loader->add_filter('wp_ajax_adminInstallPluginData', $plugin_admin, 'adminInstallPluginDataCallback', 10, 4);
$this->loader->add_filter('wp_ajax_adminChangeProductCode', $plugin_admin, 'adminChangeProductCodeCallback');
$this->loader->add_filter('wp_ajax_adminDeleteProductLink', $plugin_admin, 'adminDeleteProductLinkCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProduct', $plugin_admin, 'adminUpdateProductCallback');
$this->loader->add_filter('wp_ajax_adminChangeProductsCode', $plugin_admin, 'adminChangeProductsCodeCallback');
$this->loader->add_filter('wp_ajax_adminDeleteProductsLink', $plugin_admin, 'adminDeleteProductsLinkCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProductAndVariations', $plugin_admin, 'adminUpdateProductAndVariationsCallback');
$this->loader->add_filter('wp_ajax_admin_get_home_stats', $plugin_admin, 'admin_get_home_stats_callback');
$this->loader->add_filter('wp_ajax_admin_check_for_updates', $plugin_admin, 'admin_check_for_updates_callback');
$this->loader->add_filter('wp_ajax_adminSaveApiSettings', $plugin_admin, 'adminSaveApiSettingsCallback');
$this->loader->add_filter('wp_ajax_adminTestApiConnection', $plugin_admin, 'adminTestApiConnectionCallback');
}
}
public function run()
{
$this->loader->run();
}
public function get_plugin_name()
{
return $this->plugin_name;
}
public function get_loader()
{
return $this->loader;
}
public function get_version()
{
return $this->version;
}
}

View file

@ -1,69 +0,0 @@
<?php
/**
* Fired during plugin activation.
*
* This class defines all code necessary to run during the plugin's activation.
*
* @class Ssbhesabix_Activator
* @version 2.1.1
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
*/
class Ssbhesabix_Activator {
public static $ssbhesabix_db_version = '1.1';
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
//===============================================================================================================
public static function activate() {
add_option('ssbhesabix_webhook_password', bin2hex(openssl_random_pseudo_bytes(16)));
add_option('ssbhesabix_last_log_check_id', 0);
add_option('ssbhesabix_live_mode', 0);
add_option('ssbhesabix_debug_mode', 0);
add_option('ssbhesabix_contact_address_status', 1);
add_option('ssbhesabix_contact_node_family', 'مشتریان فروشگاه آن‌لاین');
add_option('ssbhesabix_contact_automaatic_save_node_family', 'yes');
add_option('ssbhesabix_contact_automatically_save_in_hesabix', 'yes');
add_option('ssbhesabix_activation_date', date("Y-m-d"));
add_option('ssbhesabix_use_export_product_opening_quantity', false);
add_option('ssbhesabix_business_expired', 0);
add_option('ssbhesabix_do_not_submit_product_automatically', "no");
add_option('ssbhesabix_do_not_update_product_price_in_hesabix', "no");
add_option('ssbhesabix_contact_add_additional_checkout_fields_hesabix', 1);
self::ssbhesabix_create_database_table();
}
//===============================================================================================================
public static function ssbhesabix_create_database_table()
{
global $wpdb;
$table_name = $wpdb->prefix . "ssbhesabix";
$charset_collate = $wpdb->get_charset_collate();
$sql = "
CREATE TABLE $table_name (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
obj_type varchar(32) NOT NULL,
id_hesabix int(11) UNSIGNED NOT NULL,
id_ps int(11) UNSIGNED NOT NULL,
id_ps_attribute int(11) UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
update_option('ssbhesabix_db_version', self::$ssbhesabix_db_version);
}
//===============================================================================================================
}

View file

@ -1,28 +0,0 @@
<?php
/**
* Fired during plugin deactivation.
*
* This class defines all code necessary to run during the plugin's deactivation.
*
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
*/
class Ssbhesabix_Deactivator {
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function deactivate() {
}
}

View file

@ -1,34 +0,0 @@
<?php
/**
* Define the internationalization functionality.
*
* Loads and defines the internationalization files for this plugin
* so that it is ready for translation.
*
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
class Ssbhesabix_i18n {
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
public function load_plugin_textdomain() {
load_plugin_textdomain(
'ssbhesabix',
false,
dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/'
);
}
}

View file

@ -1,123 +0,0 @@
<?php
/**
* Register all actions and filters for the plugin.
*
* Maintain a list of all hooks that are registered throughout
* the plugin, and register them with the WordPress API. Call the
* run function to execute the list of actions and filters.
*
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
class Ssbhesabix_Loader {
/**
* The array of actions registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $actions The actions registered with WordPress to fire when the plugin loads.
*/
protected $actions;
/**
* The array of filters registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $filters The filters registered with WordPress to fire when the plugin loads.
*/
protected $filters;
/**
* Initialize the collections used to maintain the actions and filters.
*
* @since 1.0.0
*/
public function __construct() {
$this->actions = array();
$this->filters = array();
}
/**
* Add a new action to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress action that is being registered.
* @param object $component A reference to the instance of the object on which the action is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. The priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1.
*/
public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* Add a new filter to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. The priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1
*/
public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* A utility function that is used to register the actions and hooks into a single
* collection.
*
* @since 1.0.0
* @access private
* @param array $hooks The collection of hooks that is being registered (that is, actions or filters).
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority The priority at which the function should be fired.
* @param int $accepted_args The number of arguments that should be passed to the $callback.
* @return array The collection of actions and filters registered with WordPress.
*/
private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) {
$hooks[] = array(
'hook' => $hook,
'component' => $component,
'callback' => $callback,
'priority' => $priority,
'accepted_args' => $accepted_args
);
return $hooks;
}
/**
* Register the filters and actions with WordPress.
*
* @since 1.0.0
*/
public function run() {
foreach ( $this->filters as $hook ) {
add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
foreach ( $this->actions as $hook ) {
add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
}
}

View file

@ -1,318 +0,0 @@
<?php
/*
* @class Ssbhesabix_Validation
* @version 2.1.1
* @since 1.1.5
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
class Ssbhesabix_Validation
{
public static function itemCodeValidation($code)
{
$code = preg_replace('/[^0-9]/', '', $code);
$code = self::formatFarsiNumbers($code);
return mb_substr($code, 0, 5);
}
//=============================================================================================
public static function itemNameValidation($name)
{
$name = self::formatFarsiNumbers($name);
return self::remove_emoji($name, 199);
}
//=============================================================================================
public static function formatFarsiNumbers($str) {
$farsiNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
$englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
for ($i = 0; $i < 10; $i++)
$str = str_replace($farsiNumbers[$i], $englishNumbers[$i], $str);
return $str;
}
//=============================================================================================
public static function itemBarcodeValidation($barcode)
{
$barcode = self::formatFarsiNumbers($barcode);
return mb_substr($barcode, 0, 999);
}
//=============================================================================================
public static function itemCategoryValidation($category) {return $category;}
//=============================================================================================
public static function itemDescriptionValidation($description) {return mb_substr($description, 0, 199);}
//=============================================================================================
public static function itemMainUnitValidation($mainUnit) {return mb_substr($mainUnit, 0, 29);}
//=============================================================================================
public static function itemSubUnitValidation($subUnit) {return mb_substr($subUnit, 0, 29);}
//=============================================================================================
public static function itemConversionFactorValidation($conversionFactor)
{
if ($conversionFactor < 0) {
return 0;
} else {
return $conversionFactor;
}
}
//=============================================================================================
public static function itemSalesTaxValidation($salesTax)
{
if ($salesTax >= 0 && $salesTax <= 100) {
return $salesTax;
} else {
return 0;
}
}
//=============================================================================================
public static function itemSalesInfoValidation($salesInfo) {return mb_substr($salesInfo, 0, 99);}
//=============================================================================================
public static function itemPurchaseCostValidation($purchaseCost)
{
if ($purchaseCost >= 0) {
return $purchaseCost;
} else {
return 0;
}
}
//=============================================================================================
public static function itemPurchaseInfoValidation($purchaseInfo) {return mb_substr($purchaseInfo, 0, 99);}
//=============================================================================================
public static function itemTagValidation($tag) {return mb_substr($tag, 0, 254);}
//=============================================================================================
public static function contactCodeValidation($code)
{
$code = preg_replace('/[^0-9]/', '', $code);
return mb_substr($code, 0, 5);
}
//=============================================================================================
public static function contactDisplayNameValidation($displayName) {return mb_substr($displayName, 0, 99);}
//=============================================================================================
public static function contactCompanyValidation($company) {return mb_substr($company, 0, 99);}
//=============================================================================================
public static function contactTitleValidation($title) {return mb_substr($title, 0, 49);}
//=============================================================================================
public static function contactFirstNameValidation($firstName) {return mb_substr($firstName, 0, 49);}
//=============================================================================================
public static function contactLastNameValidation($lastName) {return mb_substr($lastName, 0, 49);}
//=============================================================================================
public static function contactAddressValidation($address) {return mb_substr($address, 0, 149);}
//=============================================================================================
public static function contactCountryValidation($country) {return mb_substr($country, 0, 49);}
//=============================================================================================
public static function contactStateValidation($state) {
if ( is_numeric( $state ) ) {
if(is_plugin_active("persian-woocommerce-shipping/woocommerce-shipping.php")) {
$state = PWS()::get_state( $state );
}
}
return mb_substr($state, 0, 49);
}
//=============================================================================================
public static function contactCityValidation($city) {
if ( is_numeric( $city ) ) {
if(is_plugin_active("persian-woocommerce-shipping/woocommerce-shipping.php")) {
$city = PWS()::get_city($city);
}
}
return mb_substr($city, 0, 49);
}
//=============================================================================================
public static function contactPostalCodeValidation($postalCode)
{
$postalCode = preg_replace('/[^0-9]/', '', $postalCode);
$postalCode = self::formatFarsiNumbers($postalCode);
return mb_substr($postalCode, 0, 10);
}
//=============================================================================================
public static function contactPhoneValidation($phone)
{
$phone = preg_replace('/[^0-9]/', '', $phone);
$phone = self::formatFarsiNumbers($phone);
return mb_substr($phone, 0, 14);
}
//=============================================================================================
public static function contactMobileValidation($mobile)
{
$mobile = preg_replace('/[^0-9]/', '', $mobile);
return mb_substr($mobile, 0, 14);
}
//=============================================================================================
public static function contactFaxValidation($fax)
{
$fax = preg_replace('/[^0-9]/', '', $fax);
return mb_substr($fax, 0, 14);
}
//=============================================================================================
public static function contactEmailValidation($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex + 1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
// local part length exceeded
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
// domain part length exceeded
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
// local part starts or ends with '.'
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
// local part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
// character not valid in domain part
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
// domain part has two consecutive dots
$isValid = false;
} else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\", "", $local))) {
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\", "", $local))) {
$isValid = false;
}
}
}
if ($isValid) {
return $email;
} else {
return null;
}
}
//=============================================================================================
public static function contactWebsiteValidation($website) {return mb_substr($website, 0, 119);}
//=============================================================================================
public static function contactNoteValidation($note) {return mb_substr($note, 0, 499);}
//=============================================================================================
public static function contactCategoryValidation($category) {return $category;}
//=============================================================================================
public static function contactTagValidation($tag) {return mb_substr($tag, 0, 254);}
//=============================================================================================
public static function invoiceFinancialYearValidation($financialYear) {return $financialYear;}
//=============================================================================================
public static function invoiceCurrencyRateValidation($currencyRate)
{
if ($currencyRate > 0) {
return $currencyRate;
} else {
return 1;
}
}
//=============================================================================================
public static function invoiceNumberValidation($number) {return mb_substr($number, 0, 49);}
//=============================================================================================
public static function invoiceContactTitleValidation($contactTitle) {return mb_substr($contactTitle, 0, 199);}
//=============================================================================================
public static function invoiceDueDateValidation($dueDate) {return $dueDate;}
//=============================================================================================
public static function invoiceNoteValidation($note) {return mb_substr($note, 0, 499);}
//=============================================================================================
public static function invoiceReferenceValidation($reference) {return mb_substr($reference, 0, 49);}
//=============================================================================================
public static function invoiceTagValidation($tag) {return mb_substr($tag, 0, 254);}
//=============================================================================================
public function invoiceItemsValidation($items) {return $items;}
//=============================================================================================
public static function invoiceItemDescriptionValidation($description) {
return self::remove_emoji($description, 249);
}
//=============================================================================================
public static function invoiceItemQuantityValidation($quantity)
{
if ($quantity > 0) {
return $quantity;
} else {
return 1;
}
}
//=============================================================================================
public static function invoiceItemUnitValidation($unit) {return mb_substr($unit, 0, 29);}
//=============================================================================================
public static function invoiceItemUnitPriceValidation($unitPrice)
{
if ($unitPrice >= 0) {
return $unitPrice;
} else {
return 0;
}
}
//=============================================================================================
public static function invoiceItemAmountValidation($amount)
{
if ($amount >= 0) {
return $amount;
} else {
return 0;
}
}
//=============================================================================================
public static function invoiceItemDiscountValidation($discount)
{
if ($discount >= 0) {
return $discount;
} else {
return 0;
}
}
//=============================================================================================
public static function invoiceItemTaxValidation($tax)
{
if ($tax >= 0) {
return $tax;
} else {
return 0;
}
}
//=============================================================================================
public static function invoiceItemTotalAmountValidation($totalAmount)
{
if ($totalAmount >= 0) {
return $totalAmount;
} else {
return 0;
}
}
//=============================================================================================
public static function remove_emoji($string, $length = 200) : string
{
$regex_alphanumeric = '/[\x{1F100}-\x{1F1FF}]/u';
$clear_string = preg_replace($regex_alphanumeric, '', $string);
$regex_symbols = '/[\x{1F300}-\x{1F5FF}]/u';
$clear_string = preg_replace($regex_symbols, '', $clear_string);
$regex_emoticons = '/[\x{1F600}-\x{1F64F}]/u';
$clear_string = preg_replace($regex_emoticons, '', $clear_string);
$regex_transport = '/[\x{1F680}-\x{1F6FF}]/u';
$clear_string = preg_replace($regex_transport, '', $clear_string);
$regex_supplemental = '/[\x{1F900}-\x{1F9FF}]/u';
$clear_string = preg_replace($regex_supplemental, '', $clear_string);
$regex_misc = '/[\x{2600}-\x{26FF}\x{1F7E9}-\x{1F7EF}]/u';
$clear_string = preg_replace($regex_misc, '', $clear_string);
$regex_dingbats = '/[\x{2700}-\x{27BF}]/u';
$clear_string = preg_replace($regex_dingbats, '', $clear_string);
$truncated_string = mb_substr($clear_string, 0, $length);
return $truncated_string;
}
//=============================================================================================
}

View file

@ -1,343 +0,0 @@
<?php
/**
* The core plugin class.
*
* This is used to define internationalization, admin-specific hooks, and
* public-facing site hooks.
*
* Also maintains the unique identifier of this plugin as well as the current
* version of the plugin.
*
* @class Ssbhesabix
* @version 2.1.1
* @since 1.0.0
* @package ssbhesabix
* @subpackage ssbhesabix/includes
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
class Ssbhesabix
{
/**
* The loader that's responsible for maintaining and registering all hooks that power
* the plugin.
*
* @since 1.0.0
* @access protected
* @var Ssbhesabix_Loader $loader Maintains and registers all hooks for the plugin.
*/
protected $loader;
/**
* The unique identifier of this plugin.
*
* @since 1.0.0
* @access protected
* @var string $plugin_name The string used to uniquely identify this plugin.
*/
protected $plugin_name;
/**
* The current version of the plugin.
*
* @since 1.0.0
* @access protected
* @var string $version The current version of the plugin.
*/
protected $version;
//==========================================================================================================
/**
* Define the core functionality of the plugin.
*
* Set the plugin name and the plugin version that can be used throughout the plugin.
* Load the dependencies, define the locale, and set the hooks for the admin area and
* the public-facing side of the site.
*
* @since 1.0.0
*/
public function __construct()
{
if (defined('SSBHESABIX_VERSION')) {
$this->version = SSBHESABIX_VERSION;
} else {
$this->version = '0.40.1';
}
$this->plugin_name = 'ssbhesabix';
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
}
//==========================================================================================================
/**
* Load the required dependencies for this plugin.
*
* Include the following files that make up the plugin:
*
* - Ssbhesabix_Loader. Orchestrates the hooks of the plugin.
* - Ssbhesabix_i18n. Defines internationalization functionality.
* - Ssbhesabix_Admin. Defines all hooks for the admin area.
* - Ssbhesabix_Public. Defines all hooks for the public side of the site.
*
* Create an instance of the loader which will be used to register the hooks
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function load_dependencies()
{
/**
* The class responsible for orchestrating the actions and filters of the
* core plugin.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ssbhesabix-loader.php';
/**
* The class responsible for defining internationalization functionality
* of the plugin.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ssbhesabix-i18n.php';
/**
* The class responsible for defining all actions that occur in the admin area.
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-ssbhesabix-admin.php';
/**
* The class responsible for defining all hesabix API methods
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ssbhesabix-api.php';
$this->loader = new Ssbhesabix_Loader();
/**
* The class responsible for defining all hesabix data Validations
*/
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ssbhesabix-validation.php';
$this->loader = new Ssbhesabix_Loader();
}
//=====================================================================================
/**
* Define the locale for this plugin for internationalization.
*
* Uses the Plugin_Name_i18n class in order to set the domain and to register the hook
* with WordPress.
*
* @since 1.0.0
* @access private
*/
private function set_locale()
{
$plugin_i18n = new Ssbhesabix_i18n();
$this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');
}
//=====================================================================================
/**
* Register all of the hooks related to the admin area functionality
* of the plugin.
*
* @since 1.0.0
* @access private
*/
private function define_admin_hooks()
{
$plugin_admin = new Ssbhesabix_Admin($this->get_plugin_name(), $this->get_version());
//Related to check DB ver on plugin update
//$this->loader->add_action('plugins_loaded', $plugin_admin, 'ssbhesabix_update_db_check');
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
//Related to webhook set
$this->loader->add_filter('query_vars', $plugin_admin, 'ssbhesabix_query_vars');
$this->loader->add_action('parse_request', $plugin_admin, 'ssbhesabix_parse_request');
$this->loader->add_action('wp_ajax_nopriv_handle_webhook_request', $plugin_admin, 'ssbhesabix_parse_request');
$this->loader->add_action('wp_ajax_handle_webhook_request', $plugin_admin, 'ssbhesabix_parse_request');
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
$this->loader->add_action('init', $plugin_admin, 'ssbhesabix_init_internal');
//Check plugin live mode
if (get_option('ssbhesabix_live_mode')) {
if (get_option('ssbhesabix_hesabix_default_currency') === 0) {
$this->loader->add_action('admin_notices', $plugin_admin, 'ssbhesabix_currency_notice');
}
if(get_option('ssbhesabix_show_hesabix_code_in_excel_export', 'no') == 'yes' || get_option('ssbhesabix_show_hesabix_code_in_excel_export', 0) == 1) {
///////////ADD COLUMN TO WOOCOMMERCE CSV
$this->loader->add_filter( 'woocommerce_product_export_column_names', $plugin_admin, 'admin_product_add_column' );
$this->loader->add_filter( 'woocommerce_product_export_product_default_columns', $plugin_admin, 'admin_product_add_column' );
$this->loader->add_filter('woocommerce_product_export_rows', $plugin_admin, 'admin_product_export_rows', 10, 2);
}
// these lines add hesabix id to the all products list page and make it sortable as well
///////////////////////////////////////////////////////////////////////////////////////////////////////
if(get_option('ssbhesabix_show_product_code_in_products_page') === 'yes') {
$this->loader->add_filter( 'manage_edit-product_columns', $plugin_admin,'admin_products_hesabixId_column', 12 );
$this->loader->add_action( 'manage_product_posts_custom_column', $plugin_admin, 'admin_products_hesabixId_column_content', 10, 2 );
$this->loader->add_filter( 'manage_edit-product_sortable_columns', $plugin_admin,'admin_products_hesabixId_column');
}
$this->loader->add_action('custom_product_tabs', $plugin_admin, 'ssbhesabix_general_notices');
// add filter and action for woocommerce order list
$this->loader->add_filter('bulk_actions-edit-shop_order', $plugin_admin, 'custom_orders_list_bulk_action', 20, 1);
$this->loader->add_filter('handle_bulk_actions-edit-shop_order', $plugin_admin, 'custom_orders_list_bulk_action_run', 10, 3);
if (get_option('woocommerce_custom_orders_table_enabled') == 'yes') {
$this->loader->add_filter( 'woocommerce_shop_order_list_table_columns', $plugin_admin, 'custom_hesabix_column_order_list', 20);
$this->loader->add_action( 'woocommerce_shop_order_list_table_custom_column', $plugin_admin, 'custom_orders_list_column_content', 10, 2 );
} else {
$this->loader->add_filter('manage_edit-shop_order_columns', $plugin_admin, 'custom_hesabix_column_order_list', 20);
$this->loader->add_action('manage_shop_order_posts_custom_column', $plugin_admin, 'custom_orders_list_column_content', 20, 2);
}
// check add fields to checkout page by hesabix plugin
if(get_option('ssbhesabix_contact_add_additional_checkout_fields_hesabix') == 1) {
$this->loader->add_filter('woocommerce_checkout_fields', $plugin_admin, 'add_additional_fields_to_checkout', 10, 3);
}
// show checkout additional fields in order detail
if(get_option('ssbhesabix_contact_add_additional_checkout_fields_hesabix') == 1) {
$this->loader->add_action('woocommerce_admin_order_data_after_billing_address', $plugin_admin, 'show_additional_fields_in_order_detail', 10, 3);
}
//Runs when a new order added.
$this->loader->add_action('woocommerce_order_status_changed', $plugin_admin, 'ssbhesabix_hook_order_status_change', 10, 3);
//Runs when an order paid.
// $this->loader->add_action('woocommerce_payment_complete', $plugin_admin, 'ssbhesabix_hook_payment_confirmation', 10, 1);
// $this->loader->add_filter('woocommerce_payment_complete_order_status', $plugin_admin, 'ssbhesabix_hook_payment_confirmation', 10, 1);
// $this->loader->add_filter('woocommerce_order_status_completed', $plugin_admin, 'ssbhesabix_hook_payment_confirmation', 10, 1);
$this->loader->add_filter('woocommerce_order_status_changed', $plugin_admin, 'ssbhesabix_hook_payment_confirmation', 11, 3);
$this->loader->add_action('woocommerce_new_order', $plugin_admin, 'ssbhesabix_hook_new_order', 11, 2);
//Runs when a user's profile is first created.
$this->loader->add_action('edit_user_profile', $plugin_admin, 'ssbhesabix_hook_edit_user');
$this->loader->add_action('user_register', $plugin_admin, 'ssbhesabix_hook_user_register');
// $this->loader->add_action('woocommerce_new_customer', $plugin_admin, 'ssbhesabix_hook_user_register');
// $this->loader->add_action('woocommerce_created_customer', $plugin_admin, 'ssbhesabix_hook_user_register');
//Runs when a user updates personal options from the admin screen.
$this->loader->add_action('personal_options_update', $plugin_admin, 'ssbhesabix_hook_user_register');
//Runs when a user's profile is updated.
$this->loader->add_action('profile_update', $plugin_admin, 'ssbhesabix_hook_user_register');
//Runs when a user is deleted.
$this->loader->add_action('delete_user', $plugin_admin, 'ssbhesabix_hook_delete_user');
//Runs when a product is added.
// $this->loader->add_action('woocommerce_new_product', $plugin_admin, 'ssbhesabix_hook_new_product');
// $this->loader->add_action('woocommerce_new_product_variation', $plugin_admin, 'ssbhesabix_hook_new_product_variation', 10, 2);
//Runs when a product is updated.
$this->loader->add_action('woocommerce_update_product', $plugin_admin, 'ssbhesabix_hook_new_product');
// $this->loader->add_action('woocommerce_update_product_variation', $plugin_admin, 'ssbhesabix_hook_new_product');
//Runs when a product is deleted.
$this->loader->add_action('before_delete_post', $plugin_admin, 'ssbhesabix_hook_delete_product');
//$this->loader->add_action('woocommerce_delete_product_variation', $plugin_admin, 'ssbhesabix_hook_delete_product_variation');
//Display hesabix item code in Product data section
$this->loader->add_action('woocommerce_product_options_general_product_data', $plugin_admin, 'ssbhesabix_hook_product_options_general_product_data');
$this->loader->add_action('woocommerce_process_product_meta', $plugin_admin, 'ssbhesabix_hook_process_product_meta');
//Display hesabix item code in Product variable attribute section
$this->loader->add_action('woocommerce_product_after_variable_attributes', $plugin_admin, 'ssbhesabix_hook_product_after_variable_attributes', 10, 3);
$this->loader->add_action('woocommerce_save_product_variation', $plugin_admin, 'ssbhesabix_hook_save_product_variation', 10, 3);
$this->loader->add_filter('woocommerce_product_data_tabs', $plugin_admin, 'add_hesabix_product_data_tab');
$this->loader->add_action('woocommerce_product_data_panels', $plugin_admin, 'add_hesabix_product_data_fields');
} elseif (!get_option('ssbhesabix_live_mode')) {
if (get_option('ssbhesabix_business_expired'))
$this->loader->add_action('admin_notices', $plugin_admin, 'ssbhesabix_business_expired_notice');
else
$this->loader->add_action('admin_notices', $plugin_admin, 'ssbhesabix_live_mode_notice');
}
/*
* Action - Ajax 'Export Tabs' from hesabix/Export
* @since 1.0.0
*/
$this->loader->add_filter('wp_ajax_adminExportProducts', $plugin_admin, 'adminExportProductsCallback');
$this->loader->add_filter('wp_ajax_adminImportProducts', $plugin_admin, 'adminImportProductsCallback');
$this->loader->add_filter('wp_ajax_adminExportProductsOpeningQuantity', $plugin_admin, 'adminExportProductsOpeningQuantityCallback');
$this->loader->add_filter('wp_ajax_adminExportCustomers', $plugin_admin, 'adminExportCustomersCallback');
/*
* Action - Ajax 'Sync Tabs' from hesabix/Sync
* @since 1.0.0
*/
$this->loader->add_filter('wp_ajax_adminSyncChanges', $plugin_admin, 'adminSyncChangesCallback');
$this->loader->add_filter('wp_ajax_adminSyncProducts', $plugin_admin, 'adminSyncProductsCallback');
$this->loader->add_filter('wp_ajax_adminSyncOrders', $plugin_admin, 'adminSyncOrdersCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProducts', $plugin_admin, 'adminUpdateProductsCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProductsWithFilter', $plugin_admin, 'adminUpdateProductsWithFilterCallback');
$this->loader->add_filter('wp_ajax_adminSubmitInvoice', $plugin_admin, 'adminSubmitInvoiceCallback');
/*
* Action - Ajax 'Log Tab' from hesabix/Log
* @since 1.0.0
*/
$this->loader->add_filter('wp_ajax_adminCleanLogFile', $plugin_admin, 'adminCleanLogFileCallback');
$this->loader->add_filter('wp_ajax_adminSyncProductsManually', $plugin_admin, 'adminSyncProductsManuallyCallback', 10, 4);
$this->loader->add_filter('wp_ajax_adminClearPluginData', $plugin_admin, 'adminClearPluginDataCallback', 10, 4);
$this->loader->add_filter('wp_ajax_adminInstallPluginData', $plugin_admin, 'adminInstallPluginDataCallback', 10, 4);
$this->loader->add_filter('wp_ajax_adminChangeProductCode', $plugin_admin, 'adminChangeProductCodeCallback');
$this->loader->add_filter('wp_ajax_adminDeleteProductLink', $plugin_admin, 'adminDeleteProductLinkCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProduct', $plugin_admin, 'adminUpdateProductCallback');
$this->loader->add_filter('wp_ajax_adminChangeProductsCode', $plugin_admin, 'adminChangeProductsCodeCallback');
$this->loader->add_filter('wp_ajax_adminDeleteProductsLink', $plugin_admin, 'adminDeleteProductsLinkCallback');
$this->loader->add_filter('wp_ajax_adminUpdateProductAndVariations', $plugin_admin, 'adminUpdateProductAndVariationsCallback');
} else {
$this->loader->add_action('admin_notices', $plugin_admin, 'ssbhesabix_missing_notice');
}
}
//=====================================================================================
/**
* Run the loader to execute all of the hooks with WordPress.
*
* @since 1.0.0
*/
public function run() {$this->loader->run();}
//=====================================================================================
/**
* The name of the plugin used to uniquely identify it within the context of
* WordPress and to define internationalization functionality.
*
* @return string The name of the plugin.
* @since 1.0.0
*/
public function get_plugin_name() {return $this->plugin_name;}
//=====================================================================================
/**
* The reference to the class that orchestrates the hooks with the plugin.
*
* @return Ssbhesabix_Loader Orchestrates the hooks of the plugin.
* @since 1.0.0
*/
public function get_loader() {return $this->loader;}
//=====================================================================================
/**
* Retrieve the version number of the plugin.
*
* @return string The version number of the plugin.
* @since 1.0.0
*/
public function get_version() {return $this->version;}
//=====================================================================================
}

View file

@ -0,0 +1,33 @@
<?php
/**
* Hesabix Webhook Endpoint
*
* @package Hesabix
* @author Mohammad Rezai
* @author URI https://pirouz.xyz
* @since 1.0.0
*/
if (
!(defined('STDIN') || (strtolower(php_sapi_name()) == 'cli' && (!isset($_SERVER['REMOTE_ADDR'])
|| empty($_SERVER['REMOTE_ADDR']))))
) {
if (substr(wp_hash(AUTH_KEY . 'hesabix/webhook'), 0, 10) != $_GET['token']) {
die('Bad token');
}
}
$post = file_get_contents('php://input');
$result = json_decode($post);
if (!is_object($result)) {
die('Invalid request.');
}
if ($result->Password != get_option('hesabix_webhook_password')) {
die('Invalid password.');
}
include(dirname(__FILE__) . '/class-hesabix-webhook.php');
HesabixLogService::writeLogStr("Hesabix Webhook Called");
new Hesabix_Webhook();

View file

@ -1 +0,0 @@
<?php // Silence is golden

View file

@ -1,31 +0,0 @@
<?php
/*
* @author Saeed Sattar Beglou <saeed.sb@gmail.com>
* @author HamidReza Gharahzadeh <hamidprime@gmail.com>
* @author Sepehr Najafi <sepehrn249@gmail.com>
* @author Babak Alizadeh <alizadeh.babak@gmail.com>
*/
/* Check security token */
if (!(defined('STDIN') || (strtolower(php_sapi_name()) == 'cli' && (!isset($_SERVER['REMOTE_ADDR'])
|| empty($_SERVER['REMOTE_ADDR']))))) {
if (substr(wp_hash(AUTH_KEY . 'ssbhesabix/webhook'), 0, 10) != $_GET['token']) {
die('Bad token');
}
}
$post = file_get_contents('php://input');
$result = json_decode($post);
if (!is_object($result)) {
die('Invalid request.');
}
if ($result->Password != get_option('ssbhesabix_webhook_password')) {
die('Invalid password.');
}
include(dirname(__FILE__) . '/class-ssbhesabix-webhook.php');
HesabixLogService::writeLogStr("Hesabix Webhook Called");
new Ssbhesabix_Webhook();

View file

@ -1 +0,0 @@
<?php // Silence is golden

BIN
languages/hesabix-fa_IR.mo Normal file

Binary file not shown.

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