120 Commits

Author SHA1 Message Date
Almira Krdzic
ddf7d4452c Refactor admin cl interface and handle product access with groups 2018-10-16 16:57:48 +02:00
Almira Krdzic
554dc37a2d updated timestamp of role related db updates so they get triggered again 2018-10-16 06:49:57 +02:00
Almira Krdzic
dc1a1c64d2 Add default roles 2018-10-15 18:08:09 +02:00
Almira Krdzic
2d7b6c55e6 add view admin dashboard to cl 2018-10-15 17:22:58 +02:00
Almira Krdzic
d7103df6dc add view admin dashboard to cl 2018-10-15 17:21:30 +02:00
Almira Krdzic
b7ac53d195 use only customer specific prices if set 2018-10-15 14:59:57 +02:00
Almira Krdzic
f14d35b1aa Fix tests 2018-10-15 05:06:46 +02:00
Almira Krdzic
e810dd086a Merge branch 'master' into commercial-lead-prices 2018-10-15 00:31:24 +02:00
Bilal Catic
8789eb1426 Merge branch 'organization-access' into 'master'
Organization access

See merge request saburly/wiaas/new-wiaas!32
2018-10-14 22:27:52 +00:00
Almira Krdzic
bd724d12c2 Merge branch 'master' into organization-access 2018-10-15 00:25:11 +02:00
Almira
803e62ea69 Merge branch 'backoffice-max-cost-margin' into 'master'
Backoffice - max cost margin

See merge request saburly/wiaas/new-wiaas!31
2018-10-14 22:24:33 +00:00
Bilal Catic
a5168d3487 remove unnecessary code 2018-10-14 23:42:18 +02:00
Bilal Catic
d7c34c3b0b remove double code, change hook for validation 2018-10-14 23:38:38 +02:00
Bilal Catic
55dc87e174 check if taxonomy query exists and append if exists 2018-10-14 16:03:05 +02:00
Bilal Catic
9f3fe44bb1 add proper message when adding invalid package to cart 2018-10-14 15:31:27 +02:00
Bilal Catic
ba2629ca22 refactor 2018-10-14 14:46:35 +02:00
Bilal Catic
14eda981b7 add notice instead of throwing error 2018-10-14 14:24:06 +02:00
Bilal Catic
8df4ec3dc7 move package validation to seperate function 2018-10-14 14:19:22 +02:00
Almira Krdzic
17acc9d96a Error proof creating suppliers link to organization 2018-10-13 14:28:45 +02:00
Bilal Catic
4bdad78ed8 add tests 2018-10-12 11:15:41 +02:00
Bilal Catic
f3d911e5b1 remove debug logging 2018-10-12 11:15:41 +02:00
Bilal Catic
e4a7b28301 fix tests 2018-10-12 11:15:41 +02:00
Bilal Catic
84ba574bcb add detailed error message 2018-10-12 11:15:41 +02:00
Bilal Catic
4f31cc94e8 update package status on package update 2018-10-12 11:15:41 +02:00
Bilal Catic
bc74b504db fix const declaration 2018-10-12 11:15:41 +02:00
Bilal Catic
8d2b1e52b4 prevent checkout with invalid package 2018-10-12 11:15:41 +02:00
Bilal Catic
63c1ee945f prevent adding invalid package to cart 2018-10-12 11:15:41 +02:00
Bilal Catic
1e9f959b16 fetch only available packages 2018-10-12 11:15:41 +02:00
Bilal Catic
afe4ac1676 update package status on product update 2018-10-12 11:15:41 +02:00
Bilal Catic
c7e8a526e0 add custom package status 2018-10-12 11:15:16 +02:00
Bilal Catic
ac9c89e8eb update name to reflect logic behind margin 2018-10-12 11:15:16 +02:00
Bilal Catic
ea63870704 use minimum cost margin in pricing panel 2018-10-12 11:15:16 +02:00
Bilal Catic
accc359cbe handle bundle minimum cost margin read and update 2018-10-12 11:15:16 +02:00
Bilal Catic
57d61918b9 add minimum cost margin input box 2018-10-12 11:15:16 +02:00
Almira Krdzic
a830a47d31 retrieve all commercial leads on request 2018-10-11 07:52:10 +02:00
Almira Krdzic
61109e9bf0 Merge branch 'organization-access' into commercial-lead-prices 2018-10-11 07:27:32 +02:00
Almira Krdzic
c6a1f9837d Merge branch 'master' into organization-access 2018-10-11 07:14:33 +02:00
Almira
089bea5ce4 Merge branch 'suppliers-simple-product' into 'master'
Supplier

See merge request saburly/wiaas/new-wiaas!28
2018-10-11 05:13:43 +00:00
Almira Krdzic
b53fbe5402 Handle commercial lead prices 2018-10-11 07:12:53 +02:00
Almira Krdzic
84cd11f9c9 handle user roles by organization 2018-10-11 04:16:43 +02:00
Nedim Uka
a2656173c2 Connected supplier and organisation terms 2018-10-05 16:57:08 +02:00
Bilal Catic
9a8e05e341 Merge branch 'checkout-documents' into 'master'
Wiaas documents handling

See merge request saburly/wiaas/new-wiaas!29
2018-10-05 10:11:32 +00:00
Almira Krdzic
246788207b remove unused import 2018-10-04 18:36:53 +02:00
Nedim Uka
360b24c6ec Added Supplier taxonomy 2018-10-04 13:33:13 +02:00
Almira Krdzic
d11860223f Merge branch 'master' into checkout-documents 2018-10-04 13:22:26 +02:00
Almira
c537557daf Merge branch 'package-template-refactoring' into 'master'
Templates refactoring

See merge request saburly/wiaas/new-wiaas!26
2018-10-04 11:21:17 +00:00
Nedim Uka
c102b6a5ad Fixed template selection bug 2018-10-04 13:14:49 +02:00
Nedim Uka
f41252ea23 Services not listed bug fix 2018-10-04 12:54:34 +02:00
Nedim Uka
c5c07cbfae Fixed bug where template categoryes are not save properly in template 2018-10-04 12:41:17 +02:00
Nedim Uka
7ceac97fed Fixed template validation bug 2018-10-04 10:51:18 +02:00
Almira Krdzic
ab9ee2cb0d Checkout logic 2018-10-04 03:15:51 +02:00
Almira
451f9fb2eb Merge branch 'frontend-show-order-docuemnts' into 'master'
Display order documents in order details page

See merge request saburly/wiaas/new-wiaas!27
2018-10-03 18:46:28 +00:00
Nedim Uka
b028fb3f04 Removed error log 2018-10-03 16:58:52 +02:00
Almira Krdzic
3ad210f883 Handle wiaas documents 2018-10-03 16:46:41 +02:00
Nedim Uka
4c760b12c3 Added unit tests for templates 2018-10-01 17:03:24 +02:00
Bilal Catic
ea9a47fd39 create unit test 2018-09-30 21:37:34 +02:00
Bilal Catic
925896c469 don't show documents on other tabs 2018-09-30 21:37:34 +02:00
Bilal Catic
2cd4a77a34 rename props 2018-09-30 21:37:34 +02:00
Bilal Catic
174517a161 stop fetching data on view change 2018-09-30 21:37:34 +02:00
Bilal Catic
dc1311340f add documents property to order 2018-09-30 21:37:34 +02:00
Nedim Uka
f1c99c28ae Added documentation to methods 2018-09-28 14:24:47 +02:00
Nedim Uka
6f6fb1115a renamed variables to 2018-09-27 16:02:49 +02:00
Nedim Uka
93d03a96ee Refactored template product feature 2018-09-27 15:09:52 +02:00
Nedim Uka
21d96a0e55 Removed uneccesary code from wiaas admin panels.js 2018-09-27 15:09:52 +02:00
Nedim Uka
6afffc7eca Merge branch 'order-projects' into 'master'
CART: Order projects

See merge request saburly/wiaas/new-wiaas!25
2018-09-26 14:13:05 +00:00
Almira Krdzic
5f744f016e remove call to empty function 2018-09-26 16:06:21 +02:00
Almira Krdzic
0e59272689 Merge branch 'master' into order-projects 2018-09-26 16:03:15 +02:00
Almira
aa8aa42164 Merge branch 'login-bug' into 'master'
Replaced login screen with loader, wile validating access token

See merge request saburly/wiaas/new-wiaas!24
2018-09-26 14:02:32 +00:00
Almira Krdzic
415c5d8747 Remove empty function 2018-09-26 16:01:43 +02:00
Almira Krdzic
12805678b1 Change order project name sanitize function 2018-09-26 11:11:44 +02:00
Almira Krdzic
e1a1b4dc49 Fix filtering unavailable order projects 2018-09-25 13:47:25 +02:00
Almira Krdzic
4ecadc8bcc Fix error for html client response handling 2018-09-25 13:18:03 +02:00
Nedim Uka
eab040b13d Reduced loader size 2018-09-25 11:38:38 +02:00
Almira Krdzic
fdc01b974e Fix broken counting of orders inside order project 2018-09-24 22:19:21 +02:00
Almira Krdzic
11c26aeee1 Handle order project and refactor api 2018-09-24 21:51:55 +02:00
Nedim Uka
9c4539acfe Replaced login screen with loader, wile validating access token 2018-09-24 16:10:55 +02:00
Almira Krdzic
8cc2a7c8bc Merge branch 'master' into order-projects 2018-09-21 20:48:45 +02:00
Bilal Catic
c13983d6df Merge branch 'frontend-handle-page-refresh' into 'master'
add rewrite rule to apache for frontend

See merge request saburly/wiaas/new-wiaas!23
2018-09-20 12:33:53 +00:00
Bilal Catic
0065b25fef add rewrite rule to apache for frontend 2018-09-20 14:29:34 +02:00
Almira
d8c38ec089 Merge branch 'frontend-profileSettings' into 'master'
Frontend profile settings

See merge request saburly/wiaas/new-wiaas!20
2018-09-20 12:27:02 +00:00
Bilal Catic
cbf1de3403 modify test to use DELTE instead of POST 2018-09-20 14:08:32 +02:00
Bilal Catic
41e92e2390 use DELETE instead of POST for delete action 2018-09-20 13:57:01 +02:00
Bilal Catic
5da2353d04 add tests for profile endpoints 2018-09-20 13:39:25 +02:00
Bilal Catic
4159f12854 fix company info update 2018-09-20 13:39:25 +02:00
Bilal Catic
3fa75daafd fix typo 2018-09-20 13:39:25 +02:00
Bilal Catic
c637880245 fix personal info validation 2018-09-20 13:39:25 +02:00
Bilal Catic
fa2b691996 apply snake case change 2018-09-20 13:39:25 +02:00
Bilal Catic
393158808a snake case - camel case transformations 2018-09-20 13:39:25 +02:00
Bilal Catic
0787cf834f use snake case 2018-09-20 13:39:25 +02:00
Bilal Catic
522417ca28 use snake case 2018-09-20 13:39:25 +02:00
Bilal Catic
498f5526a9 use customer endpoint for profile actions 2018-09-20 13:39:25 +02:00
Bilal Catic
31115b7c6a add helper to transform snake case to camel case 2018-09-20 13:39:25 +02:00
Bilal Catic
af2da3eed0 add customer class and endpoint 2018-09-20 13:39:25 +02:00
GotPPay
d36398f2ab remove comment 2018-09-20 13:39:25 +02:00
GotPPay
32379f7f47 simple frontend address validation 2018-09-20 13:39:25 +02:00
GotPPay
82e4579e88 simple backend address validation 2018-09-20 13:39:25 +02:00
GotPPay
b93aed107b use new list of countries and adapt backend and frontend to it 2018-09-20 13:39:25 +02:00
GotPPay
5d91576fb7 turn off autocomplete also for billing address input/edit 2018-09-20 13:39:25 +02:00
GotPPay
c322c8ac78 display name, last name and email above address for profile addresses 2018-09-20 13:39:25 +02:00
GotPPay
90402d3e1d change property name to comply with frontend 2018-09-20 13:39:25 +02:00
GotPPay
84916a01ed add first name, last name and email fields to profile address on backend 2018-09-20 13:39:25 +02:00
GotPPay
b98f3c979c add aditional fields to profile address on frontend 2018-09-20 13:39:25 +02:00
GotPPay
a901da55fc Enable address changes in cart module 2018-09-20 13:39:25 +02:00
GotPPay
8a9af7ed8c keep old variable name 2018-09-20 13:39:25 +02:00
GotPPay
39cb851a55 change property name to comply with frontend 2018-09-20 13:39:25 +02:00
GotPPay
e6e487f312 add unit tests 2018-09-20 13:39:25 +02:00
GotPPay
d26569a8be create user class and make use of it 2018-09-20 13:39:25 +02:00
GotPPay
aae23e4ea3 improve frontend code 2018-09-20 13:39:25 +02:00
GotPPay
a79ef1044c user profile edit actions 2018-09-20 13:39:25 +02:00
GotPPay
b974eab225 add tests for rest-user-api 2018-09-20 13:39:25 +02:00
GotPPay
b3cff5d095 add list of available countries 2018-09-20 13:39:25 +02:00
GotPPay
4ce7b86ea9 update and read customer phone number, company name and VAT number 2018-09-20 13:39:25 +02:00
GotPPay
bc61e2e706 use custom user endpoint for validation and JWT auth for login 2018-09-20 13:39:25 +02:00
GotPPay
9da31990fd add user info to JWT token response 2018-09-20 13:39:25 +02:00
GotPPay
f63e118579 add user controller 2018-09-20 13:39:25 +02:00
Almira
cf92f62703 Merge branch 'templates' into 'master'
Package templates

See merge request saburly/wiaas/new-wiaas!16
2018-09-20 11:12:20 +00:00
Almira Krdzic
6e5f2af5a3 Started work on order projects 2018-09-20 10:32:05 +02:00
Bilal Catic
7c2a77b75d Merge branch 'wiaas-test' into 'master'
Wiaas test

See merge request saburly/wiaas/new-wiaas!22
2018-09-19 13:03:50 +00:00
Almira Krdzic
85deb1d9f8 Tests 2018-09-19 10:52:59 +02:00
Almira Krdzic
cae148ebce Packages and products countries test 2018-09-18 13:13:48 +02:00
154 changed files with 10129 additions and 1650 deletions

View File

@@ -2,6 +2,8 @@ FROM php:7.0-apache
ARG API_URL
ARG WIAAS_CUSTOMER_INTERFACE
ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
@@ -35,6 +37,8 @@ ENV WP_LOGGED_IN_SALT ${WP_LOGGED_IN_SALT}
ENV WP_NONCE_SALT ${WP_NONCE_SALT}
ENV WP_JWT_AUTH_SECRET_KEY ${WP_JWT_AUTH_SECRET_KEY}
ENV WIAAS_CUSTOMER_INTERFACE ${WIAAS_CUSTOMER_INTERFACE}
RUN apt-get update && apt-get install -y git unzip gnupg mysql-client sudo
COPY docker/php/composer.phar /usr/local/bin/composer

View File

@@ -0,0 +1,17 @@
#wpadminbar #wp-admin-bar-wiaas-view-as .ab-icon {
float: none;
margin-left: 10px;
color: rgba(240,245,250,0.7) !important;
}
#wpadminbar #wp-admin-bar-wiaas-view-as .ab-label {
font-weight: bold;
}
#wpadminbar #wp-admin-bar-wiaas-view-as a:not(:hover) .ab-icon:before {
color: rgba(240,245,250,0.7) !important;
}
#createuser .acf-taxonomy-field, #your-profile .acf-taxonomy-field {
width: 25em;
}

View File

@@ -120,4 +120,17 @@
#wiaas_package_option_groups_list .wiaas_option_group h3 {
background-color:#F9F9F9;
}
#createuser label[for="role"], #createuser label[for="url"], #createuser #role, #createuser #url{
display: none;
}
#your-profile label[for="role"], #your-profile label[for="url"],#your-profile #role, #your-profile #url{
display: none;
}
#adminmenu #toplevel_page_wiaas-cl-packages div.wp-menu-image::before {
font-family: WooCommerce!important;
content: '\e006';
}

View File

@@ -0,0 +1,7 @@
#posts-filter .tablenav .actions {
display: none;
}
#menu-posts-product .wp-submenu li:last-child {
display: none;
}

View File

@@ -0,0 +1,71 @@
jQuery(document).ready(function ($) {
$('#tabs').each(function() {
var disabled = $( this ).data('disabled') || '';
$( this ).tabs({
disabled: [ disabled ]
});
});
$('#wiaas_add_cl_customer_extras').click(function(e) {
e.preventDefault();
var customer_id = $('#wiaas_cl_customers').val();
if (!customer_id || customer_id === '0') {
return;
}
$.post(window.ajaxurl, {
action: 'wiaas_create_cl_customer_extras',
_ajax_nonce: $('#wiaas_create_cl_customer_extras_nonce').val(),
customer_id: customer_id,
package_id: $('#wiaas_cl_package_id').val()
}).done( function (result) {
$('#tabs-2').append(result);
$('#wiaas_cl_customer_' + customer_id).prop( 'disabled', true );
});
$('#wiaas_cl_customers').val('0');
});
$('#wiaas_package_extras').delegate('.wiaas_remove_cl_extras', 'click', function(e) {
e.preventDefault();
var customer_id = $( this ).data('customer_id');
$('#extras_customer_' + customer_id).remove();
$('#wiaas_cl_customer_' + customer_id).prop( 'disabled', false );
$('#wiaas_cl_customers').val('0');
});
$('#wiaas_package_extras').delegate('.wiaas-cl-extra-input', 'change', function(e) {
e.preventDefault();
var val = parseFloat($( this ).val());
var target = '#' + $( this).data('target');
if (isNaN(val)) {
$(target).val('Invalid!');
return;
}
var type = $( this).data('type');
if (type === 'fixed') {
$(target).text( $(target).data('base') + val);
}
if (type === 'recurrent' || type === 'services') {
$(target).data(type, val);
$(target).text( $(target).data('base') + $(target).data('recurrent') + $(target).data('services'));
}
});
});

View File

@@ -1,76 +1,23 @@
jQuery(function ($) {
var $edit_in_cart = $('.bundle_edit_in_cart'),
$group_mode_select = $('select#_wc_pb_group_mode'),
$bundled_products_panel = $('#bundled_product_data'),
$bundled_products_toolbar = $bundled_products_panel.find('.toolbar'),
$template_products_container_hardware = $('.wiaas-template-items_hardware'),
$template_products_container_software = $('.wiaas-template-items_software'),
$template_products_container_services = $('.wiaas-template-items_services'),
$template_products_container_isntallation = $('.wiaas-template-items_installation'),
var $template_categories_container_hardware = $('.wiaas-template-items_hardware'),
$template_categories_container_software = $('.wiaas-template-items_software'),
$template_categories_container_services = $('.wiaas-template-items_services'),
$template_categories_container_isntallation = $('.wiaas-template-items_installation'),
$template_products = $('.wc-bundled-item',
$template_products_container_services,
$template_products_container_software,
$template_products_container_hardware,
$template_products_container_isntallation),
$template_categories = $('.wc-bundled-item',
$template_categories_container_services,
$template_categories_container_software,
$template_categories_container_hardware,
$template_categories_container_isntallation),
$template_search_hardware = $('#wiaastemplate_products_hardware'),
$template_search_software = $('#wiaastemplate_products_software'),
$template_search_services = $('#wiaastemplate_products_services'),
$template_search_installation = $('#wiaastemplate_products_installation'),
bundled_product_objects = {},
bundled_products_add_count = $template_products.length,
block_params = {
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
};
template_category_objects = {},
template_category_add_count = $template_categories.length;
$.fn.wc_bundles_select2 = function () {
$(document.body).trigger('wc-enhanced-select-init');
};
// Bundle type move stock msg up.
$('.bundle_stock_msg').appendTo('._manage_stock_field .description');
// Simple type options are valid for bundles.
$('.show_if_simple:not(.hide_if_bundle)').addClass('show_if_bundle');
$('body').on('woocommerce-product-type-change', function (event, select_val) {
if ('bundle' === select_val) {
$('.show_if_external').hide();
$('.show_if_bundle').show();
$('input#_manage_stock').change();
$('#_nyp').change();
}
});
$group_mode_select.change(function () {
if ($.inArray($group_mode_select.val(), wc_bundles_admin_params.group_modes_with_parent) === -1) {
$edit_in_cart.hide();
} else {
$edit_in_cart.show();
}
});
// Downloadable support.
$('input#_downloadable').change(function () {
$('select#product-type').change();
});
// Trigger product type change.
$('select#product-type').change();
// Trigger group mode change.
$group_mode_select.change();
init_event_handlers();
@@ -81,52 +28,50 @@ jQuery(function ($) {
$template_search_hardware
.on('change', function () {
addSearchedProduct('hardware', $template_search_hardware, $template_products_container_hardware)
addSearchedTemplateCategory('hardware', $template_search_hardware, $template_categories_container_hardware)
});
$template_search_software
.on('change', function () {
addSearchedProduct('software', $template_search_software, $template_products_container_software)
addSearchedTemplateCategory('software', $template_search_software, $template_categories_container_software)
});
$template_search_installation
.on('change', function () {
addSearchedProduct('services', $template_search_installation, $template_products_container_isntallation)
addSearchedTemplateCategory('installation', $template_search_installation, $template_categories_container_isntallation)
});
$template_search_services
.on('change', function () {
addSearchedProduct('installation', $template_search_services, $template_products_container_services)
addSearchedTemplateCategory('services', $template_search_services, $template_categories_container_services)
});
function addSearchedProduct(options, search, container) {
var bundled_product_ids = search.val(),
bundled_product_id = bundled_product_ids && bundled_product_ids.length > 0 ? bundled_product_ids.shift() : false;
function addSearchedTemplateCategory(options, search, container) {
var template_category_ids = search.val(),
template_category_id = template_category_ids && template_category_ids.length > 0 ? template_category_ids.shift() : false;
var template_category_title =search.text();
if (!bundled_product_id) {
if (!template_category_id) {
return false;
}
search.val([]).change();
$bundled_products_panel.block(block_params);
bundled_products_add_count++;
template_category_add_count++;
var data = {
action: 'wiaas_add_template_product',
post_id: woocommerce_admin_meta_boxes.post_id,
id: bundled_products_add_count,
id: template_category_add_count,
title: template_category_title,
product_id: bundled_product_id,
template_category_id: template_category_id,
security: wc_bundles_admin_params.add_bundled_product_nonce,
options: options,
};
@@ -140,13 +85,11 @@ jQuery(function ($) {
container.append(response.markup);
var $added = $('.wiaas-template-item', container).last(),
added_id = 'bundled_item_' + bundled_products_add_count;
added_id = 'bundled_item_' + template_category_add_count;
$added.data('bundled_item_id', added_id);
$added.wc_bundles_select2();
$bundled_products_panel.trigger('wc-bundles-added-bundled-product');
} else if (response.message !== '') {
window.alert(response.message);
}
@@ -161,8 +104,6 @@ jQuery(function ($) {
}
search.text('');
$bundled_products_panel.unblock();
});
}, 250);
@@ -170,7 +111,7 @@ jQuery(function ($) {
return false;
}
$template_products_container_isntallation
$template_categories_container_isntallation
// Remove Item.
.on('click', 'a.remove_row', function (e) {
@@ -181,15 +122,13 @@ jQuery(function ($) {
$el.find('*').off();
$el.remove();
delete bundled_product_objects[el_id];
$bundled_products_panel.triggerHandler('wc-bundled-products-changed');
delete template_category_objects[el_id];
e.preventDefault();
});
$template_products_container_hardware
$template_categories_container_hardware
// Remove Item.
.on('click', 'a.remove_row', function (e) {
@@ -200,15 +139,13 @@ jQuery(function ($) {
$el.find('*').off();
$el.remove();
delete bundled_product_objects[el_id];
$bundled_products_panel.triggerHandler('wc-bundled-products-changed');
delete template_category_objects[el_id];
e.preventDefault();
});
$template_products_container_software
$template_categories_container_software
// Remove Item.
.on('click', 'a.remove_row', function (e) {
@@ -219,15 +156,13 @@ jQuery(function ($) {
$el.find('*').off();
$el.remove();
delete bundled_product_objects[el_id];
$bundled_products_panel.triggerHandler('wc-bundled-products-changed');
delete template_category_objects[el_id];
e.preventDefault();
});
$template_products_container_services
$template_categories_container_services
// Remove Item.
.on('click', 'a.remove_row', function (e) {
@@ -238,9 +173,7 @@ jQuery(function ($) {
$el.find('*').off();
$el.remove();
delete bundled_product_objects[el_id];
$bundled_products_panel.triggerHandler('wc-bundled-products-changed');
delete template_category_objects[el_id];
e.preventDefault();

View File

@@ -0,0 +1,260 @@
<?php
/**
* Class Wiaas_Admin_CM_Packages
*
*/
class Wiaas_Admin_CL_Packages {
/**
* Handles output of Commercial Lead packages page in admin panel.
*
* Shows list of packages available for sale and packages sold by current commercial lead.
* Enables adding package to commercial lead catalogue and setting package specific prices
* for current commercial lead.
*
*/
public static function init() {
add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 100 );
add_action( 'admin_menu', array(__CLASS__, 'add_cl_packages_menu') );
add_action( 'admin_head', array( __CLASS__, 'menu_highlight' ) );
add_filter( 'manage_product_posts_columns', array( __CLASS__, 'define_list_table_products_columns' ), 999 );
add_filter( 'bulk_actions-edit-product', array( __CLASS__, 'define_list_table_products_bulk_actions' ), 999 );
add_filter( 'views_edit-product', array( __CLASS__, 'define_list_table_products_views' ), 999 );
add_filter( 'post_row_actions', array( __CLASS__, 'define_list_table_products_row_actions' ), 999, 2 );
add_filter( 'list_table_primary_column', array( __CLASS__, 'define_list_table_products_primary_column' ), 999, 2 );
add_action( 'manage_product_posts_custom_column', array( __CLASS__, 'render_list_table_products_columns' ), 10, 2 );
}
public static function enqueue_scripts() {
$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );
wp_enqueue_style( 'wiaas_admin_menu', $plugin_url . '/assets/css/menu.css' );
}
public static function add_cl_packages_menu() {
add_submenu_page(
'edit.php?post_type=product',
__( 'Products', 'wiaas' ),
null,
'manage_wiaas_cl_products',
'wiaas-cl-package',
array(__CLASS__, 'output_package')
);
}
public static function menu_highlight() {
global $parent_file;
$screen = get_current_screen();
if ($screen->id === 'admin_page_wiaas-cl-product') {
error_log('set parent');
$parent_file = 'edit.php?post_type=product';
}
}
public static function output_package() {
wp_enqueue_script( 'jquery-ui-tabs' );
$package_id = absint( $_GET['cl_package_id'] );
$package = wc_get_product($package_id);
if (!$package) {
return;
}
if (! empty($_POST['wiaas_save_cl_extras_nonce']) && ! empty($_POST['cl_extras'])) {
if (wp_verify_nonce($_POST['wiaas_save_cl_extras_nonce'], 'wiaas_save_cl_extras')) {
self::_handle_cl_extras_update($package_id);
}
}
$bundled_items = $package->get_bundled_items();
$bundled_items_per_category = array();
foreach ($bundled_items as $bundled_item) {
$category = Wiaas_Product_Category::get_category($bundled_item->product);
if (isset($category)) {
if ($category ==='hardware' || $category === 'software') {
$category = 'products';
}
$bundled_items_per_category[$category] ?: array();
$bundled_items_per_category[$category][] = $bundled_item;
}
}
$configured_prices = Wiaas_Package_Pricing::get_package_prices($package);
$cl_id = wiaas_get_current_user_organization_id();
$cl_extras = Wiaas_Package_CL_Pricing::get_extras($cl_id, $package_id);
$has_default_cl_extras = ! empty($cl_extras);
// default values for catalogue package
if (! $has_default_cl_extras) {
$cl_extras = array();
foreach ($configured_prices as $type => $configured_price) {
$cl_extras[$type.'_default'] = array(
'visible' => true,
'fixed' => 0,
'services' => 0,
'recurrent' => 0
);
}
}
$package_cl_extra_types = array_keys($cl_extras);
$customer_ids_with_extras = array();
foreach ($package_cl_extra_types as $package_cl_extra_type) {
$customer_id_with_extras = explode('_customer_', $package_cl_extra_type)[1];
if (isset($customer_id_with_extras) && ($customer_id_with_extras = absint($customer_id_with_extras)) > 0) {
$customer_ids_with_extras[] = $customer_id_with_extras;
}
}
$customer_ids_with_extras = array_unique($customer_ids_with_extras);
require 'views/html-cl-package-details.php';
}
/**
* @section Customize display of list table products for commercial lead
*/
/**
* Define columns for commercial lead view
* @param array $columns
*
* @return array
*/
public static function define_list_table_products_columns($columns) {
$cl_columns = array();
$cl_columns['thumb'] = $columns['thumb'];
$cl_columns['wiaas_cl_name'] = $columns['name'];
$cl_columns['taxonomy-package_type'] = __('Type', 'wiaas');
$cl_columns['taxonomy-package_status'] = __('Status', 'wiaas');
$cl_columns['taxonomy-product_country'] = $columns['taxonomy-product_country'];
$cl_columns['date'] = $columns['date'];
return $cl_columns;
}
/**
* Hide list table products bulk actions for commercial lead view
*
* @return array
*/
public static function define_list_table_products_bulk_actions() {
return array();
}
/**
* Hide list table products views for commercial lead view
*
* @return array
*/
public static function define_list_table_products_views() {
return array();
}
/**
* Show only ID in table products views for commercial lead view
*
* @return array
*/
public static function define_list_table_products_row_actions($actions, $post) {
if ($post->post_type === 'product') {
return array( 'id' => sprintf( __( 'ID: %d', 'woocommerce' ), $post->ID ) );
}
return $actions;
}
/**
* Define custom primary column in list table products for commercial lead view
*
* @param $default
* @param $screen_id
*
* @return string
*/
public static function define_list_table_products_primary_column($default, $screen_id) {
if ( 'edit-product' === $screen_id ) {
return 'wiaas_cl_name';
}
return $default;
}
public static function render_list_table_products_columns($column, $post_id) {
if ($column === 'wiaas_cl_name') {
$package = wc_get_product($post_id);
$edit_link = admin_url( 'edit.php?post_type=product&page=wiaas-cl-package&cl_package_id=' . absint( $package->get_id() ) );
echo '<strong><a class="row-title" href="' . esc_url( $edit_link ) . '">' . esc_html( $package->get_title() ) . '</a></strong>';
}
}
// PRIVATE HANDLERS
private static function _handle_cl_extras_update($package_id) {
$cl_extras = wp_unslash($_POST['cl_extras']);
$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());
$posted_cl_extras = array();
foreach ($cl_extras as $cl_extra) {
$customer_id = isset($cl_extra['customer']) ? absint($cl_extra['customer']) : 0;
$type = sanitize_key($cl_extra['type']);
$fixed_extra = isset($cl_extra['fixed']) ? floatval($cl_extra['fixed']) : 0;
$services_extra = isset($cl_extra['services']) ? floatval($cl_extra['services']) : 0;
$recurrent_extra = isset($cl_extra['recurrent']) ? floatval($cl_extra['recurrent']) : 0;
$extra_type = $customer_id > 0 ? $type.'_customer_'.$customer_id : $type.'_default';
if (in_array($type, $pay_types)) {
$posted_cl_extras[$extra_type] = array(
'type' => $type,
'visible' => $cl_extra['visible'] === 'on',
'fixed' => $fixed_extra,
'services' => $services_extra,
'recurrent' => $recurrent_extra,
);
}
}
Wiaas_Package_CL_Pricing::set_extras(
wiaas_get_current_user_organization_id(),
$package_id,
$posted_cl_extras
);
}
}
Wiaas_Admin_CL_Packages::init();

View File

@@ -0,0 +1,237 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<style>
#tabs-navigation {
height: 30px;
}
#tabs-navigation > li {
float: left;
line-height: 30px;
font-weight: bold;
}
#tabs-navigation > li.ui-state-active > a {
color: #000;
}
#tabs-navigation > li.ui-state-disabled > a {
color: #ccc;
cursor: default;
}
#tabs-navigation > li > a {
text-decoration: none;
padding: .5em;
}
.wiaas-configured-prices > thead {
background: #f2f2f2;
}
.wiaas-configured-prices > thead td {
vertical-align: middle;
position: relative;
}
.wiaas-configured-prices > thead i {
position: absolute;
vertical-align: top;
right: -8px;
top: -8px;
cursor: pointer;
}
.wiaas-configured-prices > tbody > tr > td {
vertical-align: middle;
}
.wiaas-configured-prices > tbody > tr > td:first-child {
max-width: 100px;
vertical-align: middle;
}
.wiaas-configured-prices > tbody > tr > td:nth-child(2) label {
float: left;;
width: 70px;
}
.wiaas-configured-prices input[type='text'] {
width: 100px;
}
#managed_36 > td:nth-child(2) > div:last-child {
position: relative;
padding-bottom: 20px;
}
#managed_36 > td:nth-child(2) > div:last-child > span {
position: absolute;
bottom: 0;
left: 70px;
}
</style>
<script>
</script>
<div class="wrap">
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="postbox-container-1" class="postbox-container">
<div class="postbox">
<div class="inside">
<div class="panel-wrap">
<div class="panel">
<div>
<?php
foreach ($bundled_items_per_category as $category => $category_bundled_items) {
echo sprintf(
'<strong style="text-transform: uppercase;" class="text-uppercase">%s (%s)</strong>',
esc_attr( $category ),
esc_attr(count($category_bundled_items)) );
foreach ($category_bundled_items as $bundled_item) {
$title = $bundled_item->product->get_title();
echo sprintf( '<p>%s x %s</p>', esc_attr($bundled_item->get_quantity('max')), esc_attr( $title ) );
}
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="postbox-container-2" class="postbox-container">
<div class="postbox">
<div class="inside">
<div class="panel-wrap">
<div class="panel">
<h1 style="padding: 0;"><?php echo $package->get_name(); ?></h1>
</div>
</div>
</div>
</div>
<?php
if (! empty($package->get_short_description())) {
?>
<div class="postbox">
<?php wp_editor( $package->get_short_description(), 'content', array(
'_content_editor_dfw' => $_content_editor_dfw,
'drag_drop_upload' => false,
'media_buttons' => false,
'quicktags' => false,
'tabfocus_elements' => 'content-html',
'tinymce' => array(
'resize' => false,
'wp_autoresize_on' => true,
'add_unload_trigger' => false,
'wp_keep_scroll_position' => ! $is_IE,
'readonly'=> true,
'toolbar' => false,
),
) ); ?>
</div>
<?php
}
?>
<div class="postbox">
<div class="inside">
<div class="panel-wrap">
<div class="panel">
<div class="wrap">
<div>
<i style="vertical-align: middle;" class="dashicons dashicons-info"></i>
<strong><?php esc_html_e('EPR', 'wiaas') ?></strong>
<span><?php esc_html_e('= Extra package recurrent commission', 'wiaas') ?></span>
</div>
<div>
<i style="vertical-align: middle;" class="dashicons dashicons-info"></i>
<strong><?php esc_html_e('ESR') ?></strong>
<span><?php esc_html_e('= Extra services and support recurrent commission', 'wiaas') ?></span>
</div>
<div>
<i style="vertical-align: middle;" class="dashicons dashicons-info"></i>
<strong><?php esc_html_e('Extra commission', 'wiaas') ?></strong>
<span><?php esc_html_e('= EPR + ESR', 'wiaas') ?></span>
</div>
</div>
<div id="tabs" data-disabled="<?php echo $has_default_cl_extras ? '' : '1' ; ?>">
<ul id="tabs-navigation">
<li><a href="#tabs-1"><?php esc_html_e('Default prices', 'wiaas') ?></a> | </li>
<li><a href="#tabs-2"><?php esc_html_e('Customer specific prices', 'wiaas') ?></a></li>
</ul>
<form id="wiaas_package_extras" action="" method="post">
<input type="hidden" name="page" value="wiaas-cl-package"/>
<input type="hidden" id="wiaas_cl_package_id" name="cl_package_id" value="<?php echo esc_attr($package->get_id()) ?>"/>
<div id="tabs-1">
<?php require 'html-cl-package-prices.php'; ?>
</div>
<div id="tabs-2">
<div class="form-group">
<select id="wiaas_cl_customers" class="form-control">
<option selected value="0" disabled> Select customer ...</option>
<?php
$customers = wiaas_get_customers();
foreach ($customers as $id => $name) {
// shik current organization if it has role of customer
if ($id === $cl_id) {
continue;
}
?>
<option
<?php disabled(in_array($id, $customer_ids_with_extras), true, true) ?>
id="wiaas_cl_customer_<?php esc_attr_e($id, 'wiaas') ?>"
value="<?php esc_attr_e($id, 'wiaas') ?>"
>
<?php esc_html_e($name, 'wiaas') ?>
</option>
<?php
}
?>
</select>
<?php wp_nonce_field( 'wiaas_create_cl_customer_extras', 'wiaas_create_cl_customer_extras_nonce' ); ?>
<button id="wiaas_add_cl_customer_extras" class="button">Add</button>
</div>
<?php
// Render customer specific prices if any
foreach ($customer_ids_with_extras as $customer_id) {
require 'html-cl-package-prices.php';
}
?>
</div>
<?php wp_nonce_field( 'wiaas_save_cl_extras', 'wiaas_save_cl_extras_nonce' ); ?>
<?php submit_button( __( 'Save', 'wiaas' ), 'primary', 'submit' ); ?>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br class="clear" />
</div>
</div>

View File

@@ -0,0 +1,162 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
$id = isset($customer_id) ? 'extras_customer_'.$customer_id : 'extras_default';
?>
<table id="<?php esc_attr_e($id, 'wiaas') ?>" style="margin-top: 20px;" class="widefat wiaas-configured-prices">
<thead>
<tr>
<td>
<?php
if (isset($customer_id)) {
echo '<h4>'. esc_html(wiaas_get_organization_name($customer_id)). '</h4>';
}
?>
</td>
<td><?php esc_html_e('Minimal sell price', 'wiaas') ?></td>
<td><?php esc_html_e('Extra commision', 'wiaas') ?></td>
<td><?php esc_html_e('Default price', 'wiaas') ?></td>
<td><?php esc_html_e('Visible?', 'wiaas') ?>
<?php
if (isset($customer_id)) {
?>
<i
data-customer_id="<?php esc_attr_e($customer_id, 'wiaas') ?>"
class="dashicons dashicons-dismiss wiaas_remove_cl_extras"
></i>
<?php
}
?>
</td>
</tr>
</thead>
<tbody>
<?php
foreach ($configured_prices as $type => $configured_price) {
$extra_type = isset($customer_id) ? $type.'_customer_'.$customer_id : $type.'_default';
?>
<input
type="hidden"
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][type]"
value="<?php esc_attr_e($type, 'wiaas')?>"
>
<?php
if (isset($customer_id)) {
?>
<input
type="hidden"
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][customer]"
value="<?php esc_attr_e($customer_id, 'wiaas')?>"
>
<?php
}
?>
<tr id="<?php esc_attr_e($extra_type, 'wias')?>">
<td>
<strong><?php esc_html_e($configured_price['payment_type']) ?></strong>
</td>
<td class="form-group">
<div class="form-control">
<label>Fixed:</label>
<input type="text" value="<?php esc_attr_e($configured_price['minimal_fixed_price'], 'wiaas') ?>" readonly>
</div>
<div class="form-control">
<label>Monthly:</label>
<input type="text" value="<?php esc_attr_e($configured_price['minimal_recurrent_price'], 'wiaas') ?>" readonly>
<?php
if($configured_price['package_pay_period'] > 0) {
echo sprintf( '<span>(%s for services)</span>', esc_attr( $configured_price['minimal_services_price'] ) );
}
?>
</div>
</td>
<td class="form-group">
<div class="form-control">
<label>+</label>
<input
class="wiaas-cl-extra-input"
data-target="wiaas_cl_fixed_extra_<?php esc_attr_e($extra_type, 'wiaas') ?>"
data-type="fixed"
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][fixed]"
value="<?php esc_attr_e($cl_extras[$extra_type]['fixed'], 'wiaas') ?>"
type="text"
>
</div>
<?php
if($configured_price['package_pay_period'] > 0) {
?>
<div class="form-control">
<label>+</label>
<input
class="wiaas-cl-extra-input"
data-target="wiaas_cl_recurrent_extra_<?php esc_attr_e($extra_type, 'wiaas') ?>"
data-type="recurrent"
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][recurrent]"
value="<?php esc_attr_e($cl_extras[$extra_type]['recurrent'], 'wiaas') ?>"
type="text"
>
<label><?php esc_html_e('(EPR)', 'wiaas') ?></label>
</div>
<?php
}
?>
<div class="form-control">
<label>+</label>
<input
class="wiaas-cl-extra-input"
data-target="wiaas_cl_monthly_extra_<?php esc_attr_e($extra_type, 'wiaas') ?>"
data-type="services"
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][services]"
value="<?php esc_attr_e($cl_extras[$extra_type]['services'], 'wiaas') ?>"
type="text"
>
<label><?php esc_html_e('(ESR)', 'wiaas') ?></label>
</div>
</td>
<td>
<div> =
<strong
id="wiaas_cl_fixed_extra_<?php esc_attr_e($extra_type, 'wiaas') ?>"
data-base="<?php esc_attr_e($configured_price['minimal_fixed_price'], 'wiaas') ?>"
>
<?php esc_html_e($configured_price['minimal_fixed_price'] + $cl_extras[$extra_type]['fixed'], 'wiaas') ?>
</strong>
</div>
<div> =
<strong
id="wiaas_cl_monthly_extra_<?php esc_attr_e($extra_type, 'wiaas') ?>"
data-base="<?php esc_attr_e($configured_price['minimal_recurrent_price'], 'wiaas') ?>"
data-recurrent="<?php esc_attr_e($cl_extras[$extra_type]['recurrent'], 'wiaas') ?>"
data-services="<?php esc_attr_e($cl_extras[$extra_type]['services'], 'wiaas') ?>"
>
<?php
esc_html_e($configured_price['minimal_recurrent_price'] +
$cl_extras[$extra_type]['recurrent'] +
$cl_extras[$extra_type]['services'], 'wiaas')
?>
</div>
</td>
<td class="form-group">
<input
name="cl_extras[<?php esc_attr_e($extra_type, 'wiaas')?>][visible]"
<?php checked($cl_extras[$extra_type]['visible'], true, true) ?>
type="checkbox"
>
</td>
</tr>
<?php
}
?>
</tbody>
</table>

View File

@@ -0,0 +1,31 @@
<?php
add_action('wp_ajax_wiaas_create_cl_customer_extras', 'wiaas_ajax_create_cl_customer_extras');
function wiaas_ajax_create_cl_customer_extras() {
check_ajax_referer('wiaas_create_cl_customer_extras');
$customer_id = absint($_POST['customer_id']);
$package_id = absint($_POST['package_id']);
$package = wc_get_product($package_id);
$configured_prices = Wiaas_Package_Pricing::get_package_prices($package);
$cl_extras = array();
foreach ($configured_prices as $type => $configured_price) {
$cl_extras[$type.'_customer_'.$customer_id] = array(
'type' => $type,
'visible' => true,
'fixed' => 0,
'services' => 0,
'recurrent' => 0
);
}
require_once 'views/html-cl-package-prices.php';
die();
}

View File

@@ -0,0 +1,40 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class Wiaas_Admin_CL {
public static function init() {
add_action('init', array(__CLASS__, 'init_admin_cl'));
}
public static function init_admin_cl() {
$user = wp_get_current_user();
$role = $user->roles[0];
if ($role === 'commercial_lead') {
require_once dirname( __FILE__ ) . '/admin-cl/class-wiaas-admin-cl-packages.php';
require_once dirname( __FILE__ ) . '/admin-cl/wiaas-admin-cl-packages-ajax.php';
add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 100 );
}
}
public static function enqueue_scripts() {
$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );
wp_enqueue_script( 'wiaas_admin_cl_packages', $plugin_url . '/assets/js/wiaas-admin-cl-packages.js' );
wp_enqueue_style( 'wiaas_admin_cl', $plugin_url . '/assets/css/wiaas-admin-cl.css' );
}
}
Wiaas_Admin_CL::init();

View File

@@ -0,0 +1,14 @@
<?php
class Wiaas_Admin_Documents {
public static function init() {
require_once dirname( __FILE__ ) . '/documents/class-wiaas-admin-product-documents.php';
require_once dirname( __FILE__ ) . '/documents/class-wiaas-admin-document-editor.php';
require_once dirname( __FILE__ ) . '/documents/wiaas-admin-document-ajax.php';
}
}
Wiaas_Admin_Documents::init();

View File

@@ -0,0 +1,149 @@
<?php
class Wiaas_Admin_Order_Projects {
public static function init() {
// Add admin page and subpage since woocommerce orders have custom menu page
// so this will not be automatic
add_filter('admin_menu', array(__CLASS__, 'add_admin_page'));
add_action( 'parent_file', array(__CLASS__, 'highlight_order_projects_parent_menu') );
// Add is available fields to create and edit forms
add_action( 'shop_order_project_add_form_fields', array( __CLASS__, 'add_is_available_field' ) );
add_action( 'shop_order_project_edit_form_fields', array( __CLASS__, 'edit_is_available_field' ) );
// Add is available column
add_filter( 'manage_edit-shop_order_project_columns', array( __CLASS__, 'update_table_headers' ) );
add_filter( 'manage_shop_order_project_custom_column', array( __CLASS__, 'update_table_column_content' ), 10, 3 );
// Save is available field when creating and editing
add_action( 'created_term', array( __CLASS__, 'save_is_available_field' ), 10, 3 );
add_action( 'edit_term', array( __CLASS__, 'save_is_available_field' ), 10, 3 );
}
/**
* Add admin submenu page for order projects
*/
public static function add_admin_page() {
add_submenu_page( 'woocommerce',
esc_html__( 'Order projects', 'wiaas' ),
esc_html__( 'Order projects', 'wiaas' ),
'manage_woocommerce',
'edit-tags.php?taxonomy=shop_order_project'
);
}
/**
* Correctly highlight parent menu page when order projects submenu is selected
* @param $parent_file
*
* @return string
*/
public static function highlight_order_projects_parent_menu($parent_file) {
if ( get_current_screen()->taxonomy == 'shop_order_project' ) {
$parent_file = 'woocommerce';
}
return $parent_file;
}
/**
* Add is available field to order project creation form
*/
public static function add_is_available_field() {
?>
<div class="form-field form-required">
<input
type="checkbox"
class="postform"
style="float:left; margin-top: 4px; margin-right: 10px;"
id="is_available"
name="is_available"
/>
<label for="is_available"><?php _e( 'Is Available?', 'wiaas' ); ?></label>
</div>
<?php
}
/**
* Add is available field to order project edit form
* @param $order_project
*/
public static function edit_is_available_field($order_project) {
?>
<tr class="form-field">
<th scope="row" valign="top"><label><?php _e( 'Is Available?', 'wiaas' ); ?></label></th>
<td>
<input
type="checkbox"
class="checkbox"
id="is_available"
name="is_available"
<?php
checked( true, Wiaas_Order_Project::is_order_project_available($order_project), true )
?>
/>
</td>
</tr>
<?php
}
/**
* Update table headers for order projects
* Will add `is available` and `wiaas count` columns and remove default count column
*
* @param array $columns Available order project table headers
*
* @return array Edited order project table headers
*/
public static function update_table_headers($columns) {
$columns['wiaas_is_available'] = __( 'Is Available?', 'wiaas' );
$columns['wiaas_count'] = __('Count', 'wiaas');
unset($columns['posts']);
return $columns;
}
/**
* Render content for order project table column
* Will add content for `is available` and `wiaas count` columns
*
* @param string $columns Row content for order projects table
* @param string $column Current column header
* @param int $id Order project id
*
* @return string Edited row content with appended is available info
*/
public static function update_table_column_content($columns, $column, $id) {
if ($column === 'wiaas_is_available') {
$is_available = Wiaas_Order_Project::is_order_project_available($id);
$columns .= $is_available ? 'Yes' : 'No';
}
if ($column === 'wiaas_count') {
$term = get_term($id, 'shop_order_project');
$args = array(
'shop_order_project' => $term->slug,
'post_type' => 'shop_order'
);
$columns .= "<a href='" . esc_url ( add_query_arg( $args, 'edit.php' ) ) . "'>$term->count</a>";
}
return $columns;
}
/**
* Save posted is available field for created or edited order project
* @param $term_id
* @param string $tt_id
* @param string $taxonomy
*/
public static function save_is_available_field($term_id, $tt_id = '', $taxonomy = '') {
if ( 'shop_order_project' === $taxonomy ) {
Wiaas_Order_Project::set_is_order_project_available($term_id, $_POST['is_available'] === 'on');
}
}
}
Wiaas_Admin_Order_Projects::init();

View File

@@ -0,0 +1,174 @@
<?php
class Wiaas_Admin_Organization {
public static function init() {
// role switcher for organization
add_action( 'admin_bar_menu', array( __CLASS__, 'add_role_switcher_menu' ), 10, 2 );
// change user role if requested
add_action('admin_init', array(__CLASS__, 'maybe_change_user_role'));
add_filter('manage_users_columns', array(__CLASS__, 'manage_users_table_columns'));
add_filter('views_users', array(__CLASS__, 'hide_users_table_list_navigation'));
add_filter('get_role_list', array(__CLASS__, 'get_role_list_for_user'), 10, 2);
add_filter('woocommerce_customer_meta_fields', array(__CLASS__, 'hide_woocommerce_customer_fields'));
}
public static function hide_woocommerce_customer_fields() {
return array();
}
public static function hide_users_table_list_navigation() {
return array();
}
/**
* Render user organization roles as available user roles on user list
* @param $role_list
* @param $user
*
* @return mixed
*/
public static function get_role_list_for_user($role_list, $user) {
$organization_id = wiaas_get_user_organization_id($user->ID);
if (! empty($organization_id)) {
$organization_roles = wiaas_get_organization_roles($organization_id);
foreach ($organization_roles as $organization_role) {
$role_list[$organization_role] = translate_user_role( wp_roles()->role_names[ $organization_role ] );
}
if (! empty($organization_role)) {
unset($role_list['none']);
}
}
return $role_list;
}
/**
* Customize columns for users table list view
*
* @param array $defaults
*
* @return array
*/
public static function manage_users_table_columns( $defaults = array() ) {
$defaults['role'] = __('Roles', 'wiaas');
unset($defaults['posts']);
return $defaults;
}
/**
* Adds organization roles switcher menu to admin bar
*
* @param $admin_bar
*/
public static function add_role_switcher_menu($admin_bar) {
if (is_super_admin()) {
$roles = array( 'administrator' );
} else {
$organization_id = wiaas_get_current_user_organization_id();
$roles = wiaas_get_organization_roles($organization_id);
}
$user = wp_get_current_user();
$current_role = $user->roles[0];
// Add menu item.
$admin_bar->add_menu( array(
'id' => 'wiaas-view-as',
'parent' => 'top-secondary',
'title' => '<span>' .
__( 'View as:', 'wiaas' ) .
'</span>' .
'<span style="margin-left: 6px; font-weight: bold;">'.
__(translate_user_role( wp_roles()->role_names[ $current_role ] ), 'wiaas') .
'</span>' .
'<i style="float: right;" class="ab-icon dashicons dashicons-arrow-down"></i>',
'href' => false,
'meta' => array(
'title' => __( 'View As', 'wiaas' ),
'tabindex' => '0',
),
) );
foreach ($roles as $role) {
$role_name = translate_user_role( wp_roles()->role_names[ $role ] );
if ($role === $current_role) {
// highlight current role
$title = '<span class="ab-label">' . __( $role_name, 'wiaas' ) . '</span>';
$url = false;
} else if ($role === 'customer') {
// set external link for customer role
$title = '<span>' . __( $role_name, 'wiaas' ) . '</span>';
$title .= '<span class="ab-icon dashicons dashicons-external"></span>';
$url = WIAAS_CUSTOMER_INTERFACE;
$target = '_blank';
} else {
$title = '<span>' . __( $role_name, 'wiaas' ) . '</span>';
$url = wp_nonce_url(admin_url(), 'wiaas-set-role', 'wiaas-set-role-nonce');
$url = add_query_arg( 'wiaas-role', $role, $url );
$target = '_parent';
}
$admin_bar->add_menu( array(
'id' => 'wiaas_'.$role,
'parent' => 'wiaas-view-as',
'title' => $title,
'href' => $url,
'meta' => array(
'title' => __( $role_name, 'wiaas' ),
'target' => $target
),
) );
}
}
/**
*
* Process organization role switch request if needed
*
*/
public static function maybe_change_user_role() {
if (! empty($_GET['wiaas-set-role-nonce']) && ! empty($_GET['wiaas-role'])) {
if (wp_verify_nonce($_GET['wiaas-set-role-nonce'], 'wiaas-set-role')) {
$role_name = sanitize_key($_GET['wiaas-role']);
$role = wp_roles()->get_role($role_name);
if (! empty($role) && $role_name !== 'customer') {
// get current user
$current_user = wp_get_current_user();
update_user_meta($current_user->ID, '_wiaas_current_user_admin_role', $role->name);
// switch user role
$current_user->set_role($role->name);
}
}
wp_safe_redirect( admin_url('index.php') );
exit;
}
}
}
Wiaas_Admin_Organization::init();

View File

@@ -7,16 +7,10 @@ if ( ! defined( 'ABSPATH' ) ) {
class Wiaas_Admin_Package {
public static function init() {
add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 100 );
require_once dirname( __FILE__ ) . '/package/class-wiaas-admin-linked-packages.php';
require_once dirname( __FILE__ ) . '/package/class-wiaas-admin-package-types.php';
}
public static function enqueue_scripts() {
$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );
wp_enqueue_style( 'wiaas_admin_styles', $plugin_url . '/assets/css/package.css' );
}
}
Wiaas_Admin_Package::init();

View File

@@ -0,0 +1,92 @@
<?php
/**
* Editor for wiaas document post screen
*
* Class Wiaas_Admin_Document_Editor
*/
class Wiaas_Admin_Document_Editor {
public static function init() {
add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );
add_action( 'save_post', array( __CLASS__, 'save' ), 1, 2 );
}
/**
* Add wiaas document editor metaboxes
*/
public static function add_meta_boxes() {
add_meta_box( 'wiaas_document_details', __( 'Details', 'wiaas' ), array(
__CLASS__,
'document_info'
), 'wiaas_doc', 'normal', 'low');
}
/**
* Save wiaas document informations
* @param $post_id
* @param $post
*/
public static function save ($post_id, $post) {
if ( empty( $post_id ) || empty( $post ) || empty( $_POST ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( is_int( wp_is_post_revision( $post ) ) ) {
return;
}
if ( is_int( wp_is_post_autosave( $post ) ) ) {
return;
}
if ( empty( $_POST['wiaas_doc_nonce'] ) || ! wp_verify_nonce( $_POST['wiaas_doc_nonce'], 'save_wiaas_doc' ) ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( $post->post_type != 'wiaas_doc' ) {
return;
}
// unset nonce because it's only valid of 1 post
unset( $_POST['wiaas_doc_nonce'] );
if (isset($_POST['wiaas_doc_version']) && $_POST['wiaas_doc_version'] !== '') {
$version = sanitize_text_field($_POST['wiaas_doc_version']);
if(wiaas_document_version_exists($version)) {
Wiaas_Document::add_document_version($post_id, $version);
}
}
if (isset($_POST['wiaas_doc_type'])) {
Wiaas_Document::set_doc_type($post_id, sanitize_key($_POST['wiaas_doc_type']));
}
Wiaas_Document::set_is_doc_visible($post_id, $_POST['wiaas_doc_visible'] === 'on');
}
/**
* Render wiaas document info metabox
*/
public static function document_info() {
global $post;
$parent_post_type = $post->post_type;
$document_id = $post->ID;
$ajax_action = 'wiaas_upload_file';
require 'views/html-document-info.php';
}
}
Wiaas_Admin_Document_Editor::init();

View File

@@ -0,0 +1,78 @@
<?php
class Wiaas_Admin_Product_Documents {
public static function init() {
add_action( 'woocommerce_product_data_tabs', array( __CLASS__, 'add_linked_documents_tab' ) );
add_action( 'woocommerce_product_data_panels', array( __CLASS__, 'linked_documents_tab' ) );
add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );
add_action( 'woocommerce_process_product_meta', array( __CLASS__, 'process_meta_box' ));
}
/**
* Add upload and link document metabox to product screen
*/
public static function add_meta_boxes() {
add_meta_box( 'wiaas_upload_and_link_document', __( 'Upload and link document', 'wiaas' ), array(
__CLASS__,
'upload_and_link_document'
), 'product', 'side');
}
/**
* Render upload and link document metabox to product screen
*/
public static function upload_and_link_document() {
$ajax_action = 'wiaas_quick_add_document';
require 'views/html-document-form.php';
}
/**
* Add linked documents tabs for product screen
*
* @param array $tabs
*
* @return array
*/
public static function add_linked_documents_tab($tabs) {
$tabs['wiaas_documents'] = array(
'label' => __( 'Linked Documents', 'wiaas' ),
'target' => 'wiaas_documents',
'class' => array('show_if_bundle', 'show_if_simple'),
'priority' => 20,
);
return $tabs;
}
/**
* Render linked documents tab content for product screen
*/
public static function linked_documents_tab() {
global $post;
$documents_ids = wiaas_get_object_attached_documents($post->ID);
include 'views/html-product-documents.php';
}
/**
* Save linked document for product
*
* @param int $package_id
*/
public static function process_meta_box($package_id) {
$documents = isset($_POST['wiaas_attached_documents']) && is_array($_POST['wiaas_attached_documents']) ?
$_POST['wiaas_attached_documents'] : array();
wiaas_attach_documents_to_object($package_id, $documents);
}
}
Wiaas_Admin_Product_Documents::init();

View File

@@ -0,0 +1,51 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* int $id ID of the attached document
*/
$doc_info = Wiaas_Document::get_doc_info($id);
$type = isset($doc_info['type']) && is_array($doc_info['type']) ? $doc_info['type']['name'] : ' - ';
$visible = Wiaas_Document::is_doc_visible($id);
?>
<tr id="wiaas_attached_document_<?php echo esc_attr($id); ?>">
<td width="1%">
<?php
if ($visible) {
echo '<span class="dashicons dashicons-visibility"></span>';
} else {
echo '<span class="dashicons dashicons-hidden"></span>';
}
?>
</td>
<td>
<div>
<input type="hidden" name="wiaas_attached_documents[]" value="<?php echo esc_attr($id); ?>" />
<b>
<?php esc_html_e($doc_info['name'], 'wiaas'); ?>
</b>
</div>
</td>
<td>
<span>
<?php esc_html_e($type, 'wiaas'); ?>
</span>
</td>
<td width="1%"><a href="<?php echo esc_attr($doc_info['url']) ?>" download>
<span class="dashicons dashicons-download"></span>
</a>
</td>
<td width="1%">
<button
data-id="<?php echo esc_attr($id); ?>"
class="button wiaas-remove-attached-document">
<small><?php esc_html_e('Remove', 'wiaas'); ?></small>
</button>
</td>
</tr>

View File

@@ -0,0 +1,258 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
*
*/
$is_update = isset($document_id);
global $post;
$insert_new_document = $post->post_type !== 'wiaas_doc';
?>
<style>
#wiaas_document_form .form-group {
margin-bottom:15px;
min-height: 30px;
}
#wiaas_document_form .form-control {
width: 100%;
height: 34px;
padding:6px 12px;
border: 1px solid #d5d5d5;
}
#wiaas_document_form #plupload-browse-button {
color: #444 !important;
background-color: #FFFFFF !important;
border-color: #CCCCCC !important;
text-transform: uppercase !important;
letter-spacing: 1px !important;
border-radius: 2px !important;
}
#wiaas_document_form #plupload-upload-ui {
height: 230px;
}
#wiaas_document_form #drag-drop-area {
max-height: 200px;
}
#wiaas_document_form .drag-drop .drag-drop-inside {
margin: 50px auto 0;
}
</style>
<script>
jQuery(document).ready(function ($) {
<?php
if ($insert_new_document) {
$nonce = wp_create_nonce('wiaas_quick_add_document');
$action = 'wiaas_quick_add_document';
} else {
$nonce = wp_create_nonce('wiaas_upload_file');
$action = 'wiaas_upload_file';
}
$plupload_init = array(
'runtimes' => 'html5,silverlight,flash,html4',
'browse_button' => 'plupload-browse-button',
'container' => 'plupload-upload-ui',
'drop_element' => 'drag-drop-area',
'file_data_name' => 'wiaas_file',
'multiple_queues' => false,
'url' => admin_url('admin-ajax.php'),
'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
'filters' => array(array(
'title' => __('Allowed Files'),
'extensions' => join(',', Wiaas_Document_Upload::allowed_extensions()))
),
'multipart' => true,
'urlstream_upload' => true,
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => $nonce,
'action' => $action,
'type' => 'wiaas_doc'
),
);
if(get_option('__wpdm_chunk_upload',0) == 1){
$plupload_init['chunk_size'] = get_option('__wpdm_chunk_size', 1024).'kb';
$plupload_init['max_retries'] = 3;
} else
$plupload_init['max_file_size'] = wp_max_upload_size().'b';
?>
// create the uploader and pass the config from above
var uploader = new plupload.Uploader(<?php echo json_encode($plupload_init); ?>);
// checks if browser supports drag and drop upload, makes some css adjustments if necessary
uploader.bind('Init', function(up){
var uploaddiv = jQuery('#plupload-upload-ui');
if(up.features.dragdrop){
uploaddiv.addClass('drag-drop');
jQuery('#drag-drop-area')
.bind('dragover.wp-uploader', function(){ uploaddiv.addClass('drag-over'); })
.bind('dragleave.wp-uploader, drop.wp-uploader', function(){ uploaddiv.removeClass('drag-over'); });
}else{
uploaddiv.removeClass('drag-drop');
jQuery('#drag-drop-area').unbind('.wp-uploader');
}
});
uploader.init();
// a file was added in the queue
uploader.bind('FilesAdded', function(up, files){
//var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
<?php
if ($insert_new_document) {
?>
var params = uploader.getOption('multipart_params');
params['doc_title'] = $('#wiaas_new_doc_title').val();
params['doc_type'] = $('#wiaas_new_doc_type').val();
params['doc_visible'] = $('#wiaas_new_doc_visible').is(':checked');
uploader.setOption('multipart_params', params);
plupload.each(files, function(file){
jQuery('#wiaas_selected_file').val(file.name);
});
<?php
}
?>
uploader.refresh();
uploader.start();
});
$("#wiaas_document_add_version").click(function(e) {
e.preventDefault();
uploader.start();
});
// a file was uploaded
uploader.bind('FileUploaded', function(up, file, response) {
response = response.response;
if (response.substring(0, 6) === 'ERROR:') {
jQuery('#wiaas_upload_errors').html('<span class="text-danger">' +
'<i class="fa fa-exclamation-triangle"></i>' +
' &nbsp; ' + response.substring(6, response.length) +
'</span>');
return;
}
<?php
if ($insert_new_document) {
?>
$('#wiaas_attached_documents').find('tbody').append(response);
<?php
} else {
?>
$('#wiaas_uploaded_file').val(response);
jQuery('#publish').click();
<?php
}
?>
});
});
</script>
<div id="wiaas_document_form">
<?php
if ($insert_new_document) {
?>
<p class="form-group">
<input
id="wiaas_new_doc_title"
type="text"
placeholder="Title"
class="form-control input-lg" />
</p>
<?php
}
?>
<p class="form-group">
<select
id="wiaas_new_doc_type"
name="wiaas_doc_type"
class="form-control input-lg">
<?php
$all_doc_types = Wiaas_Document::get_available_doc_types();
if (!$insert_new_document) {
$selected_doc_type = Wiaas_Document::get_doc_type($post->ID);
$selected_doc_type = is_array($selected_doc_type) ? $selected_doc_type['id'] : '';
}
foreach ($all_doc_types as $doc_type) {
if (!$doc_type['is_special_type']) {
?>
<option
value="<?php echo $doc_type['id'] ?>"
<?php selected($doc_type['id'], $selected_doc_type, true)?>
>
<?php esc_html_e($doc_type['name'], 'wiaas') ?>
</option>
<?php
}
}
?>
</select>
</p>
<p class="form-group">
<input
id="wiaas_new_doc_visible"
name="wiaas_doc_visible"
<?php if (!$insert_new_document)
checked(Wiaas_Document::is_doc_visible($post->ID), true, true) ?>
type="checkbox"
/>
<label><?php echo __( 'Visible to customer?', 'wiaas' ); ?></label>
</p>
<input id="wiaas_uploaded_file" name="wiaas_doc_version" type="hidden">
<div>
<div id="plupload-upload-ui" class="hide-if-no-js">
<div id="drag-drop-area" style="height:240px">
<div class="drag-drop-inside">
<p class="drag-drop-info"><?php _e( 'Drop file here', 'wiaas' ); ?></p>
<p><?php echo _x( 'or', 'Drop file here *or* select file', 'wiaas' ); ?></p>
<p class="drag-drop-buttons"><input id="plupload-browse-button" type="button"
value="<?php esc_attr_e( 'Select File', 'wiaas' ); ?>"
class="button"/></p>
</div>
</div>
</p>
</div>
</div>
<div id="wiaas_upload_errors" style="color: darkred;">
</div>
</div>

View File

@@ -0,0 +1,87 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* int $document_id ID of the document
*/
?>
<style>
#wiaas_document_info table {
margin-top: 25px;
}
#wiaas_document_info table > thead {
background: #f5f5f5;
}
#wiaas_document_info table b {
color: #72777c;
}
#tagsdiv-wiaas_doc_type {
display: none;
}
#wiaas_document_new_version {
max-width: 320px;
margin: auto;
}
</style>
<div id="wiaas_document_info">
<?php echo wp_nonce_field('save_wiaas_doc', 'wiaas_doc_nonce') ?>
<div id="wiaas_document_new_version">
<?php
require 'html-document-form.php';
?>
</div>
<div class="form-group">
<table class="widefat">
<thead>
<tr>
<td></td>
<td><b>Versions</b></td>
<td></td>
</tr>
</thead>
<tbody id="wiaas_doc_versions">
<?php
$versions = Wiaas_Document::get_document_versions($document_id);
foreach ($versions as $index => $version) {
?>
<tr>
<td><?php esc_html_e('#' . ($index + 1), 'wiaas') ?></td>
<td><?php
esc_html_e(
wiaas_get_doc_version_filename($version).'.'.wiaas_get_doc_version_extension($version),
'wiaas')
?></td>
<td>
<a
href="<?php echo esc_attr(Wiaas_Document::get_doc_download_link($document_id, $index)) ?>"
download>
<span class="dashicons dashicons-download"></span>
</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>

View File

@@ -0,0 +1,84 @@
<?php
/**
* Wiaas Linked Packages Editor
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$( '.wiaas-search-documents' ).each(function() {
var element = $( this );
var searchTarget = $('#' + element.data('target'));
element.autocomplete({
source: function(request, response) {
$.get( window.ajaxurl, {
action: 'wiaas_json_search_documents',
query: request.term,
_ajax_nonce: '<?php echo wp_create_nonce('wiaas_json_search_documents') ?>'
} ).done( function( documents ) {
response( documents || []);
}
);
},
select: function(event, ui) {
if (!searchTarget || $('#wiaas_attached_document_' + ui.item.id).length) {
return;
}
$.get(window.ajaxurl, {
action: 'wiaas_link_document',
_ajax_nonce: '<?php echo wp_create_nonce('wiaas_link_document') ?>',
id: ui.item.id
}).done( function (document) {
searchTarget.find('tbody').append(document);
});
}
})
.autocomplete( 'instance' )._renderItem = function( ul, item ) {
return $( '<li role="option" id="wiaas-document-autocomplete-' + item.id + '">' )
.text( item.name )
.appendTo( ul );
};
});
$('#wiaas_attached_documents').delegate('.wiaas-remove-attached-document', 'click', function (e) {
e.preventDefault();
var id = $(this).data('id');
$('#wiaas_attached_document_' + id).remove();
});
});
</script>
<div id="wiaas_documents" class="panel woocommerce_options_panel">
<div class="options_group">
<p class="form-field">
<label style="font-weight: bold;" for="wiaas_addon_packages"><?php esc_html_e( 'Search documents:', 'wiaas' ); ?></label>
<input type="text" data-target="wiaas_attached_documents" class="wiaas-search-documents"/>
</p>
</div>
<div class="options_group">
<div class="form-field">
<div style="margin:20px">
<table id="wiaas_attached_documents" class="widefat wp-list-table">
<tbody>
<?php
foreach ($documents_ids as $id) {
require 'html-attached-document.php';
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,105 @@
<?php
add_action( 'wp_ajax_wiaas_upload_file', 'wiaas_ajax_upload_document_version' );
add_action( 'wp_ajax_wiaas_quick_add_document', 'wiaas_ajax_quick_add_document' );
add_action( 'wp_ajax_wiaas_link_document', 'wiaas_ajax_link_document' );
add_action( 'wp_ajax_wiaas_json_search_documents','wiaas_ajax_json_search_documents' );
/**
* Upload document version file with ajax
*/
function wiaas_ajax_upload_document_version() {
check_ajax_referer('wiaas_upload_file');
if (!isset($_FILES['wiaas_file']) || empty($_FILES['wiaas_file'])) {
echo "ERROR: No file present!";
die();
}
$version = Wiaas_Document_Upload::upload_document_version('wiaas_file');
if (is_wp_error($version)) {
echo 'ERROR:' . $version->get_error_message();
die();
}
echo $version;
die();
}
/**
* Quick add new document and return attachment view for it
*/
function wiaas_ajax_quick_add_document() {
check_ajax_referer('wiaas_quick_add_document');
//validate file
if (!isset($_FILES['wiaas_file']) || empty($_FILES['wiaas_file'])) {
echo "ERROR: No file present!";
die();
}
// Upload document version file
$version = Wiaas_Document_Upload::upload_document_version('wiaas_file');
// Upload failed so return the error
if (is_wp_error($version)) {
echo 'ERROR:' . $version->get_error_message();
die();
}
// Get document title
$title = isset($_POST['doc_title']) && $_POST['doc_title'] !== '' ?
sanitize_text_field($_POST['doc_title']) :
pathinfo( $version, PATHINFO_FILENAME );
// Try to create new document
$id = Wiaas_Document::add_document(
$title,
$version,
$_POST['doc_visible'] === 'true');
// Document creation failed so return the error
if (!$id) {
echo "ERROR: Document could not be created!";
die();
}
// If document type is sent then assign new document to it
if (isset($_POST['doc_type'])) {
Wiaas_Document::set_doc_type( $id, sanitize_key($_POST['doc_type']) );
}
require 'views/html-attached-document.php';
die();
}
/**
* Render attacment view for linked document
*/
function wiaas_ajax_link_document() {
check_ajax_referer('wiaas_link_document');
$id = absint($_GET['id']);
require 'views/html-attached-document.php';
die();
}
/**
*
*Search wiaas documents by name
*/
function wiaas_ajax_json_search_documents() {
check_ajax_referer('wiaas_json_search_documents');
$q = ( ! empty( $_GET['query'] ) ? sanitize_text_field($_GET['query']) : '' );
$result = Wiaas_Document::search($q);
wp_send_json( $result );
}

View File

@@ -28,20 +28,6 @@ if ( ! defined( 'ABSPATH' ) ) {
}
}
function showDownloadableFiles() {
$('#general_product_data').find('.show_if_downloadable').each(function() {
$(this).show();
$(this).removeClass('hidden');
$(this).removeClass('show_if_downloadable');
$(this).addClass('show_if_simple');
$(this).addClass('show_if_bundle');
$(this).find('._download_limit_field, ._download_expiry_field').hide();
});
}
showDownloadableFiles();
handlePackageTypeToolsVisiblity();
});
</script>

View File

@@ -58,6 +58,7 @@ class Wiaas_Admin_Package_Pricing {
$package = wc_get_product( $post->ID );
$pricing_rules = Wiaas_Package_Pricing::get_package_prices($package);
$commission = Wiaas_Package_Pricing::get_package_pricing_commission($package);
$max_cost_margin = Wiaas_Package_Pricing::get_package_max_cost_margin($package);
include 'views/html-package-pricing.php';
}
@@ -71,7 +72,8 @@ class Wiaas_Admin_Package_Pricing {
Wiaas_Package_Pricing::set_package_prices(
wc_get_product( $post_id ),
$_POST['wiaas_pricing_rules'],
$_POST['wiaas_pricing_rules_commision']);
$_POST['wiaas_pricing_rules_commision'],
$_POST['wiaas_max_cost_margin']);
}
}

View File

@@ -6,13 +6,7 @@ if ( ! defined( 'ABSPATH' ) ) {
<?php
$value = $pricing_rule['minimal_services_price'];
if ($pricing_rule['principal_amount'] > 0 && $pay_type['package_pay_period'] > 0) {
$value += wiaas_PMT(
Wiaas_Pricing::INTEREST_RATE,
$pay_type['package_pay_period'],
$pricing_rule['principal_amount']);
}
$value = $pricing_rule['minimal_recurrent_price'];
?>
<tr>

View File

@@ -144,6 +144,20 @@ if ( ! defined( 'ABSPATH' ) ) {
});
</script>
<div class="options_group">
<?php
woocommerce_wp_text_input(
array(
'id' => '_wiaas_max_cost_margin',
'name' => 'wiaas_max_cost_margin',
'value' => $max_cost_margin,
'label' => __( 'Max cost margin:', 'wiaas' ),
'type' => 'number',
)
);
?>
</div>
<div class="options_group">
<?php
woocommerce_wp_text_input(

View File

@@ -6,12 +6,24 @@ if ( ! defined( 'ABSPATH' ) ) {
<script>
jQuery(document).ready(function($) {
$("#general_product_data").find('.pricing').addClass('hide_if_bundle');
$("#general_product_data").find('.pricing').removeClass('show_if_bundle');
if ($('#product-type').val() === 'bundle') {
$("#general_product_data .pricing").hide();
if ($('#product-type').val() === 'simple') {
$('#general_product_data').find('.pricing').show();
} else {
$('#general_product_data').find('.pricing').hide();
}
$('#general_product_data').find('.pricing').attr('class','wiaas_show_if_simple');
$('body').on('woocommerce-product-type-change', function (event, select_val) {
if ('simple' === select_val) {
$('.wiaas_show_if_simple').show();
} else {
$('.wiaas_show_if_simple').hide();
}
});
});
</script>
@@ -21,7 +33,7 @@ woocommerce_wp_checkbox(
'id' => '_wiaas_recurring_price',
'value' => $product_pricing['is_recurring'] ? 'yes' : 'no',
'data_type' => 'price',
'label' => __( $product->get_category_ids()[0], 'wiaas' ),
'label' => __( 'Is recurring?', 'wiaas' ),
)
);

View File

@@ -3,27 +3,35 @@
class Wiaas_Admin_Template_Selection {
public static function init() {
add_action('add_meta_boxes', array(__CLASS__, 'create_custom_meta_box'), 100);
add_action('woocommerce_process_product_meta_bundle', array(__CLASS__, 'save_custom_content_meta_box'), 10, 1);
add_action('add_meta_boxes', array(__CLASS__, 'create_template_meta_box'), 100);
add_action('woocommerce_process_product_meta_bundle', array(__CLASS__, 'save_template_content_meta_box'), 10, 1);
// Processes and saves type-specific data.
add_action('woocommerce_admin_process_product_object', array(__CLASS__, 'validate_bundle'), 11);
}
public static function create_custom_meta_box() {
/**
* Renders template selection meta box
*/
public static function create_template_meta_box() {
add_meta_box(
'template_product_meta_box',
__('Choose package template <em>(optional)</em>', 'cmb'),
'Wiaas_Admin_Template_Selection::add_custom_content_meta_box',
'Wiaas_Admin_Template_Selection::add_template_content_meta_box',
'product',
'normal',
'high'
);
}
public static function add_custom_content_meta_box($post) {
/**
* Fill in the value of template selection dropdown,
* and render template categories of the selected template
*
* @param $post WP_Post object
*/
public static function add_template_content_meta_box($post) {
$value = get_post_meta($post->ID, '_select_template', true);
@@ -49,49 +57,82 @@ class Wiaas_Admin_Template_Selection {
$template_products_data = self::show_template_products($value);
self::render_template_products($template_products_data['hardware']);
self::render_template_products($template_products_data['service']);
self::render_template_products($template_products_data['services']);
self::render_template_products($template_products_data['installation']);
self::render_template_products($template_products_data['software']);
?></div><?php
}
public static function get_categories_from_templates($products_form_template) {
/**
* Extract template categories for all of the main product categories
* (software , hardware, services, installation) and combine them in one array
*
* @param $categories_form_template
* @return array of Wiaas_Template_Category_Object
*/
public static function get_categories_from_templates($categories_form_template) {
$all_template_categories = array();
$all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['hardware']));
$all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['service']));
$all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['installation']));
$all_template_categories = array_merge($all_template_categories, self::get_product_categories($products_form_template['software']));
$all_template_categories = array_merge($all_template_categories,
WC_Product_Template::extract_template_product_categories($categories_form_template['hardware']));
$all_template_categories = array_merge($all_template_categories,
WC_Product_Template::extract_template_product_categories($categories_form_template['services']));
$all_template_categories = array_merge($all_template_categories,
WC_Product_Template::extract_template_product_categories($categories_form_template['installation']));
$all_template_categories = array_merge($all_template_categories,
WC_Product_Template::extract_template_product_categories($categories_form_template['software']));
return $all_template_categories;
}
/**
* Return all of the template product meta_data from selected template
*
* @param $selected_template integer an id of selected template
* @return array of template categories
*/
public static function show_template_products($selected_template) {
if (empty($selected_template)) {
return;
return array();
} else {
$template_products_hardware = (get_post_meta($selected_template, '_template_items_hardware', true));
$template_products_service = (get_post_meta($selected_template, '_template_items_service', true));
$template_products_installation = (get_post_meta($selected_template, '_template_items_installation', true));
$template_products_software = (get_post_meta($selected_template, '_template_items_software', true));
$template_products_hardware = WC_Product_Template::get_template_categories_from_meta(
$selected_template, '_template_items_hardware');
$template_products_services = WC_Product_Template::get_template_categories_from_meta(
$selected_template, '_template_items_services');
$template_products_installation = WC_Product_Template::get_template_categories_from_meta(
$selected_template, '_template_items_installation');
$template_products_software = WC_Product_Template::get_template_categories_from_meta(
$selected_template, '_template_items_software');
}
return array(
'hardware' => $template_products_hardware,
'service' => $template_products_service,
'services' => $template_products_services,
'installation' => $template_products_installation,
'software' => $template_products_software
);
}
/**
* Render html of template categories
*
* @param $template_products array containing template category information
*/
public static function render_template_products($template_products) {
if (!empty($template_products)) {
@@ -108,90 +149,43 @@ class Wiaas_Admin_Template_Selection {
}
}
public static function get_product_categories($category_meta) {
$category_objects = array();
/**
* Save selected template
*
* @param $post_id WP_Post
*/
if (empty($category_meta)) {
return array();
}
foreach ($category_meta as $meta) {
if (!empty($meta)) {
$category_template_id = $meta['template_category_id'];
$template_category_object = new Wiaas_Template_Category_Object(
$category_template_id,
$meta['template_category_title'],
$meta['quantity']);
$category_objects[$category_template_id] = $template_category_object;
}
}
return empty($category_objects) ? null : $category_objects;
}
public static function get_bundled_product_categories($bundled_items) {
$template_category_objects = array();
foreach ($bundled_items as $item_id => $item) {
$item_data = $item->get_data();
$post_terms = wp_get_object_terms($item->get_product_id(), 'template_category', array('fields' => 'id=>name'));
if (!empty($post_terms) && !is_wp_error($post_terms)) {
$cat = '';
$category_template_id = '';
foreach ($post_terms as $id => $term) {
$cat = $term;
$category_template_id = $id;
}
$template_category_object = new Wiaas_Template_Category_Object(
$category_template_id,
$cat,
$item_data['quantity_max']);
$template_category_objects[$category_template_id] = $template_category_object;
}
}
return $template_category_objects;
}
function save_custom_content_meta_box($post_id) {
function save_template_content_meta_box($post_id) {
$selected_template = $_POST['_select_template'];
if (!empty($selected_template))
update_post_meta($post_id, '_select_template', esc_attr($selected_template));
else {
update_post_meta($post_id, '_select_template', '');
}
WC_Product_Template::bind_selected_template_to_product($selected_template, $post_id);
}
/**
* Get the template categories from bundle products and selected template
* Compare template categories and quantities that are required by the template with those in bundle products
*
* Admin error is added if validation is not satisfied
*
* @param $product WC_Product_Bundle
*/
public static function validate_bundle($product) {
if ($product->get_type() == 'bundle') {
$selected_template = $_POST['_select_template'];
$bundled_items = $product->get_bundled_items('view');
$products_form_template = self::show_template_products($selected_template);
$template_categories_form_template = self::show_template_products($selected_template);
$missing_categories = array();
$insufficient_product_quantities = array();
$missing_template_categories = array();
$insufficient_template_category_quantities = array();
$categories_form_template = self::get_categories_from_templates($products_form_template);
$categories_form_bundle = self::get_bundled_product_categories($bundled_items);
$categories_form_template = self::get_categories_from_templates($template_categories_form_template);
$categories_form_bundle = WC_Product_Template::extract_bundled_product_categories($bundled_items);
$bundle_category_keys = array_keys($categories_form_bundle);
if (!empty($categories_form_template)) {
foreach ($categories_form_template as $category) {
@@ -200,7 +194,7 @@ class Wiaas_Admin_Template_Selection {
if (!in_array($template_cat_id, $bundle_category_keys)) {
array_push($missing_categories, $category->name);
array_push($missing_template_categories, $category->name);
} else {
@@ -208,37 +202,25 @@ class Wiaas_Admin_Template_Selection {
$quantity_from_template = $category->quantity;
if ((int)($quantity_from_template) !== $product_from_bundle_quantity) {
array_push($insufficient_product_quantities, $category->name);
array_push($insufficient_template_category_quantities, $category->name);
}
}
}
}
$categories_message = implode(',', $missing_categories);
$quantity_message = implode(',', $insufficient_product_quantities);
$template_categories_message = implode(',', $missing_template_categories);
$quantity_message = implode(',', $insufficient_template_category_quantities);
if (!empty($missing_categories)) {
WC_PB_Meta_Box_Product_Data::add_admin_error(__(' <strong> WIAAS This product bundle does not correspond to selected template</strong> Categories missing: ' . $categories_message, 'woocommerce-product-bundles'));
if (!empty($missing_template_categories)) {
WC_PB_Meta_Box_Product_Data::add_admin_error(__(' <strong> WIAAS This product bundle does not correspond to selected template</strong> Categories missing: ' . $template_categories_message, 'woocommerce-product-bundles'));
}
if (!empty($insufficient_product_quantities)) {
if (!empty($insufficient_template_category_quantities)) {
WC_PB_Meta_Box_Product_Data::add_admin_error(__(' <strong> WIAAS This product bundle does not correspond to selected template</strong> Categories with different quantities: ' . $quantity_message, 'woocommerce-product-bundles'));
}
}
}
public static function get_category_ids_form_bundle($product) {
$products_form_budnle = $product->get_bundled_data_items();
$product_ids = array();
foreach ($products_form_budnle as $product) {
array_push($product_ids, $product->get_id());
}
return self::get_product_categories($product_ids);
}
}
Wiaas_Admin_Template_Selection::init();

View File

@@ -21,6 +21,10 @@ class Wiaas_Template_Admin_Ajax {
}
/**
* An ajax callback action for handling template selection
*/
public static function ajax_handle_template_selection() {
$selected_template_id = intval($_POST['selected_template']);
@@ -34,7 +38,7 @@ class Wiaas_Template_Admin_Ajax {
if (!empty($template_products)) {
ob_start();
Wiaas_Admin_Template_Selection::render_template_products($template_products['hardware']);
Wiaas_Admin_Template_Selection::render_template_products($template_products['service']);
Wiaas_Admin_Template_Selection::render_template_products($template_products['services']);
Wiaas_Admin_Template_Selection::render_template_products($template_products['installation']);
Wiaas_Admin_Template_Selection::render_template_products($template_products['software']);
@@ -53,7 +57,7 @@ class Wiaas_Template_Admin_Ajax {
check_ajax_referer('wc_bundles_add_bundled_product', 'security');
$loop = intval($_POST['id']);
$product_id = intval($_POST['product_id']);
$template_category_id = intval($_POST['template_category_id']);
$title = $_POST['title'];
$options = $_POST['options'];
@@ -70,13 +74,13 @@ class Wiaas_Template_Admin_Ajax {
}
/**
*
* Handles adding template categories search.
*/
public static function ajax_wiaas_template_category_search() {
$term = ($_POST['term']);
$term = wp_unslash($_GET['term']);
$response = array();
$terms = get_terms(array(
'taxonomy' => 'template_category',
'name__like' => $term

View File

@@ -7,7 +7,6 @@ class Wiaas_template {
public static function init() {
add_filter('product_type_selector', array(__CLASS__, 'add_template_product_type'));
add_action('admin_footer', array(__CLASS__, 'templates_custom_js'));
add_filter('woocommerce_product_data_tabs', array(__CLASS__, 'custom_product_tabs'));
add_action('woocommerce_product_data_panels', array(__CLASS__, 'wiaastemplate_product_tab_content_all'));
add_action('woocommerce_admin_process_product_object', array(__CLASS__, 'save_wiaastemplate'));
@@ -35,7 +34,7 @@ class Wiaas_template {
}
/**
* Add to product type drop down.
* Add template product type drop down.
*/
function add_template_product_type($types) {
@@ -48,27 +47,7 @@ class Wiaas_template {
/**
* Show pricing fields for template product.
*/
function templates_custom_js() {
if ('product' != get_post_type()) :
return;
endif;
?>
<script type='text/javascript'>
jQuery(document).ready(function () {
jQuery('.options_group.pricing').addClass('show_if_simple_template').show();
});
</script><?php
}
/**
* Add a custom product tab.
* Add template product, hardware, services, installation and software tabs product tab.
*/
function custom_product_tabs($tabs) {
@@ -100,6 +79,10 @@ class Wiaas_template {
}
/**
* Add content do template tabs
*/
public static function wiaastemplate_product_tab_content_all() {
self::wiaastemplate_product_tab_content('hardware');
@@ -110,8 +93,11 @@ class Wiaas_template {
/**
* Contents of the template options product tab.
* Html contents of the template options product tab.
*
* @param $options string main wiaas category
*/
public static function wiaastemplate_product_tab_content($options) {
global $post;
@@ -128,7 +114,7 @@ class Wiaas_template {
foreach ($template_items as $item) {
$product_id = $item['template_category_id'];
$template_category_id = $item['template_category_id'];
$title = $item['template_category_title'];
$quantity = $item['quantity'];
@@ -142,7 +128,7 @@ class Wiaas_template {
<select class="wiaas-term-search" id="wiaastemplate_products<?php echo '_' . $options ?>" style="width: 250px;"
name="template_product"
data-placeholder="<?php _e('Add product to template&hellip;', 'wiaas'); ?>"
data-action="woocommerce_json_search_products" multiple="multiple" data-limit="500">
multiple="multiple" data-limit="500">
<option></option>
</select>
<?php echo wc_help_tip(__('Search for a product and add it to this template by clicking its name in the results list.', 'wiaas')); ?>
@@ -154,7 +140,7 @@ class Wiaas_template {
/**
* Save the custom fields.
* Save the template categories that are bind to template.
*/
function save_wiaastemplate($post_id) {
@@ -163,14 +149,21 @@ class Wiaas_template {
$posted_template_data_installation = isset($_POST['template_data_installation']) ? $_POST['template_data_installation'] : false;
$posted_template_data_software = isset($_POST['template_data_software']) ? $_POST['template_data_software'] : false;
self::save_template_product_meta($post_id, $posted_template_data_hardware, 'hardware');
self::save_template_product_meta($post_id, $posted_template_data_services, 'services');
self::save_template_product_meta($post_id, $posted_template_data_installation, 'installation');
self::save_template_product_meta($post_id, $posted_template_data_software, 'software');
self::process_and_save_template_product_meta($post_id, $posted_template_data_hardware, 'hardware');
self::process_and_save_template_product_meta($post_id, $posted_template_data_services, 'services');
self::process_and_save_template_product_meta($post_id, $posted_template_data_installation, 'installation');
self::process_and_save_template_product_meta($post_id, $posted_template_data_software, 'software');
}
public static function save_template_product_meta($post_id, $posted_template_data, $option) {
/**
* Get extract posted data and save them to meta
*
* @param $post_id integer id of the template
* @param $posted_template_data mixed
* @param $option string indicating main wiaas category
*/
public static function process_and_save_template_product_meta($post_id, $posted_template_data, $option) {
$processed_template_data = array();
// Sort posted data by menu order.
@@ -178,24 +171,24 @@ class Wiaas_template {
foreach ($posted_template_data as $data) {
$product_id = isset($data['product_id']) ? absint($data['product_id']) : false;
$product_title = isset($data['product_title']) ? $data['product_title'] : false;
$template_category_id = isset($data['template_category_id']) ? absint($data['template_category_id']) : false;
$template_category_title = isset($data['template_category_title']) ? $data['template_category_title'] : false;
$quantity = isset($data['quantity']) ? absint($data['quantity']) : false;
$item_data = array(
'template_category_id' => $product_id,
'template_category_title' => trim($product_title),
'template_category_id' => $template_category_id,
'template_category_title' => trim($template_category_title),
'quantity' => $quantity
);
$processed_template_data[$product_id] = $item_data;
$processed_template_data[$template_category_id] = $item_data;
}
update_post_meta($post_id, '_template_items_' . $option, $processed_template_data);
WC_Product_Template::save_template_product_meta($post_id, $option, $processed_template_data);
}
public static function menu_sort_order($a, $b) {
@@ -208,7 +201,7 @@ class Wiaas_template {
/**
* Hide Attributes data panel.
* Hide default WC_Product data panels.
*/
function hide_attributes_data_panel($tabs) {

View File

@@ -18,8 +18,8 @@ if (!defined('ABSPATH')) {
?><input type="hidden" name="template_data_<?php echo $options?>[<?php echo $loop; ?>][item_id]" class="item_id" value="<?php echo $item_id; ?>" /><?php
}
?><input type="hidden" name="template_data_<?php echo $options?>[<?php echo $loop; ?>][product_title]" class="product_title" value="<?php echo $title; ?>" /><?php
?><input type="hidden" name="template_data_<?php echo $options?>[<?php echo $loop; ?>][product_id]" class="product_id" value="<?php echo $product_id; ?>" />
?><input type="hidden" name="template_data_<?php echo $options?>[<?php echo $loop; ?>][template_category_title]" class="product_title" value="<?php echo $title; ?>" /><?php
?><input type="hidden" name="template_data_<?php echo $options?>[<?php echo $loop; ?>][template_category_id]" class="product_id" value="<?php echo $template_category_id; ?>" />
</div><?php

View File

@@ -6,348 +6,325 @@ class Wiaas_Cart_API {
*
* @var string
*/
private static $namespace = 'wiaas/cart';
private static $namespace = 'wiaas';
private static $rest_base = 'cart';
public static function register_routes() {
register_rest_route( self::$namespace, 'count', array(
'methods' => 'GET',
register_rest_route( self::$namespace, '/' . self::$rest_base . '/count', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array(__CLASS__, 'get_cart_count'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
'permission_callback' => 'is_user_logged_in',
) );
register_rest_route( self::$namespace, 'items', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'get_cart_items'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
register_rest_route( self::$namespace, '/' . self::$rest_base . '/items', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array(__CLASS__, 'get_cart_items'),
'permission_callback' => 'is_user_logged_in',
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array(__CLASS__, 'add_package_to_cart'),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'package_id' => array(
'description' => __( 'Wiaas package ID.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'price_id' => array(
'description' => __( 'Selected price ID for Wiaas package.', 'wiaas' ),
'type' => 'string',
'enum' => array_keys(Wiaas_Package_Pricing::get_available_pay_types()),
'sanitize_callback' => 'sanitize_key',
),
'options_ids' => array(
'description' => __( 'Wiaas package options IDs.', 'wiaas' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
'sanitize_callback' => 'absint',
)
),
'addons_ids' => array(
'description' => __( 'Wiaas package addons IDs.', 'wiaas' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
'sanitize_callback' => 'absint',
)
)
)
),
) );
register_rest_route( self::$namespace, 'documents', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'get_cart_documents'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
register_rest_route( self::$namespace, '/' . self::$rest_base . '/items/(?P<key>[\w-]+)', array(
'args' => array(
'key' => array(
'description' => __( 'Unique key identifier for cart package item.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array(__CLASS__, 'remove_package_from_cart'),
'permission_callback' => 'is_user_logged_in',
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array(__CLASS__, 'update_package_quantity'),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'quantity' => array(
'description' => __( 'New quantity cart package item.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
)
)
)
) );
register_rest_route( self::$namespace, 'add', array(
'methods' => 'post',
'callback' => array(__CLASS__, 'add_package_to_cart'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
) );
register_rest_route(self::$namespace, '/' . self::$rest_base . '/documents', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array(__CLASS__, 'get_cart_documents'),
'permission_callback' => 'is_user_logged_in',
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array(__CLASS__, 'upload_cart_document'),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'doc_type' => array(
'description' => __( 'Category of uploaded document.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'required' => true
),
'package_key' => array(
'description' => __( 'Unique key identifier for cart package item.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'required' => true
),
'type' => array(
'default' => 'wiaas_doc'
)
)
)
));
register_rest_route( self::$namespace, 'remove', array(
'methods' => 'post',
'callback' => array(__CLASS__, 'remove_package_from_cart'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
) );
register_rest_route(self::$namespace, '/' . self::$rest_base . '/items/(?P<key>[\w-]+)/documents/(?P<type>[\w-]+)', array(
'args' => array(
'key' => array(
'description' => __( 'Unique key identifier for cart package item.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
'type' => array(
'description' => __( 'Cart document Type.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array(__CLASS__, 'download_cart_document'),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'document_key' => array(
'description' => __( 'Unique key identifier for cart document.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'required' => true
),
)
),
));
register_rest_route( self::$namespace, 'update-quantity', array(
'methods' => 'post',
'callback' => array(__CLASS__, 'update_package_quantity'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
register_rest_route( self::$namespace, '/' . self::$rest_base . '/checkout', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array(__CLASS__, 'checkout'),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'vat' => array(
'description' => __( 'Vat Code for new order.', 'wiaas' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_key',
),
'company' => array(
'description' => __( 'Company name for new order.', 'wiaas' ),
'type' => 'string',
'required' => true,
'sanitize_callback' => 'sanitize_key',
),
'reference' => array(
'description' => __( 'Location details for new order.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
'tender' => array(
'description' => __( 'Invoice reference for new order.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
'project_id' => array(
'description' => __( 'Order project ID for new order.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'delivery_address_id' => array(
'description' => __( 'ID of delivery address for new order.', 'wiaas' ),
'type' => 'integer',
'required' => true,
'sanitize_callback' => 'absint',
),
'billing_address_id' => array(
'description' => __( 'ID of billing address for new order.', 'wiaas' ),
'type' => 'integer',
'required' => true,
'sanitize_callback' => 'absint',
),
)
) );
register_rest_route( self::$namespace, 'place-order', array(
'methods' => 'post',
'callback' => array(__CLASS__, 'place_order'),
'permission_callback' => array( __CLASS__, 'permission_check' ),
) );
}
public static function permission_check() {
if (!is_user_logged_in()) {
return new WP_Error( 'wiaas_rest_authorization_required',
__( 'Sorry, only authorized users can access!', 'wiaas' ),
array( 'status' => rest_authorization_required_code() ) );
}
return true;
}
/**
* Get cart count
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
* @return WP_REST_Response
*/
public static function get_cart_count() {
$items = WC()->cart->get_cart_contents();
$count = 0;
foreach ($items as $key => $item) {
if (isset($item['_wiaas_standard_package'])) {
$count++;
}
}
return new WP_REST_Response(array(
'count' => $count,
return rest_ensure_response(array(
'count' => Wiaas_Cart::get_cart_packages_count(),
));
}
/**
* Get cart items
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
*
* @return WP_REST_Response
*/
public static function get_cart_items() {
$items = WC()->cart->get_cart_contents();
$result = array();
foreach ($items as $key => $item) {
if (!isset($item['_wiaas_standard_package'])) {
continue;
}
$package = wc_get_product($item['product_id']);
// Retrieve package addons
$addon_cart_items = wiaas_get_cart_item_addons($item);
$additional_packages = array();
foreach ($addon_cart_items as $addon_cart_item) {
$additional_package = wc_get_product($addon_cart_item['product_id']);
$additional_packages[] = array(
'idAdditionalPackage' => $additional_package->get_id(),
'packageName' => $additional_package->get_title(),
'prices' => array(
'fixedExtra' => $addon_cart_item['_wiaas_payment']['fixed_extra'],
'recurrentExtra' => $addon_cart_item['_wiaas_payment']['recurrent_extra'],
'servicesExtra' => $addon_cart_item['_wiaas_payment']['services_extra'],
)
);
}
// Retrieve package options
$option_cart_items = wiaas_get_cart_item_options($item);
$package_options = array();
foreach ($option_cart_items as $option_cart_item) {
$option_package = wc_get_product($option_cart_item['product_id']);
$package_options[] = array(
'idOptionPackage' => $option_package->get_id(),
'groupName' => $option_cart_item['_wiaas_option_group_name'],
'packageName' => $option_package->get_title(),
'prices' => array(
'fixedExtra' => $option_cart_item['_wiaas_payment']['fixed_extra'],
'recurrentExtra' => $option_cart_item['_wiaas_payment']['recurrent_extra'],
'servicesExtra' => $option_cart_item['_wiaas_payment']['services_extra'],
)
);
}
$totalPrices = Wiaas_Cart::get_cart_item_total($item);
$country = Wiaas_Countries::get_package_country($package);
return rest_ensure_response(array(
'items' => Wiaas_Cart::get_cart_packages(),
'raw' => WC()->cart->get_cart_contents(),
));
}
$result[] = array(
'idPackage' => $item['product_id'],
'key' => $item['key'],
'packageName' => $package->get_title(),
'additionalPackages' => $additional_packages,
'areAdditionalAvailable' => true,
'areOptionsAvailable' => true,
'bids' => array(),
'commercialLead' => 'Coor Service Management',
'country' => array(
'currency' => $country['currency']
),
'options' => $package_options,
'quantity' => $item['quantity'],
/**
* @param WP_REST_Request $request Request data.
*
* @return WP_REST_Response
*/
public static function add_package_to_cart($request) {
'idPayType' => $item['_wiaas_payment']['id'],
'payType' => $item['_wiaas_payment']['payment_type'],
'periodUnit' => $item['_wiaas_payment']['period_unit'],
'idPrice' => $item['_wiaas_payment']['id'],
'fixedPrice' => $item['_wiaas_payment']['fixed_extra'],
'recurrentPrice' => $item['_wiaas_payment']['recurrent_extra'],
'servicesPrice' => $item['_wiaas_payment']['services_extra'],
'totalPrices' => array(
'fixedPrice' => $totalPrices['fixed_extra'],
'recurrentPrice' => $totalPrices['recurrent_extra'],
'servicesPrice' => $totalPrices['services_extra'],
),
'status' => 'available',
'idCommercialLead' => 14,
);
}
return new WP_REST_Response(
array(
'cartItems' => $result,
'items' => $items,
'totalPrice' => ''
)
$success = Wiaas_Cart::add_package_to_cart(
$request['package_id'],
$request['price_id'],
$request['addons_ids'],
$request['options_ids']
);
if (!$success) {
return (wc_notice_count('error') > 0) ?
wiaas_api_cart_error_notices() :
wiaas_api_notice('PACKAGE_ALREADY_IN_CART', 'error');
}
return wiaas_api_notice('PACKAGE_ADDED', 'success');
}
/**
* Get cart documents
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
* @param WP_REST_Request $request Request data.
*
* @return WP_REST_Response
*/
public static function get_cart_documents() {
return new WP_REST_Response(array(
'areFilesUploaded' => true,
'templates' => array(),
'uploaded' => array()
));
}
public static function remove_package_from_cart($request) {
/**
* Add package to cart
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
* @return WP_REST_Response
* @throws Exception
*/
public static function add_package_to_cart() {
$package_id = $_POST['package_id'];
$success = Wiaas_Cart::remove_package_from_cart($request['key']);
$success = WC()->cart->add_to_cart($package_id, 1, 0, array(), array(
'_wiaas_standard_package' => true
));
if ($success) {
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'success',
'message' => 'PACKAGE_ADDED'
)
)
));
if (!$success) {
return (wc_notice_count('error') > 0) ?
wiaas_api_cart_error_notices() :
wiaas_api_notice('INVALID_PACKAGE_FOR_REMOVE', 'error');
}
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'error',
'message' => 'PACKAGE_ALREADY_IN_CART'
)
)
));
}
/*
* Remove package from cart
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
*/
public static function remove_package_from_cart() {
$package_cart_key = $_POST['package_item_key'];
$success = WC()->cart->remove_cart_item($package_cart_key);
if ($success) {
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'success',
'message' => 'PACKAGE_REMOVED_FROM_CART'
)
)
));
}
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'error',
'message' => 'INVALID_PACKAGE_FOR_REMOVE'
)
)
));
return wiaas_api_notice('PACKAGE_REMOVED_FROM_CART', 'success');
}
/**
* Update package quantity in cart
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
* @return WP_REST_Response
*/
public static function update_package_quantity() {
$package_item_key = $_POST['package_item_key'];
$new_quantity = $_POST['quantity'];
public static function update_package_quantity($request) {
$success = WC()->cart->set_quantity($package_item_key, $new_quantity, true);
$success = Wiaas_Cart::update_package_quantity($request['key'], $request['quantity']);
if ($success) {
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'success',
'message' => 'QUANTITY_UPDATED'
)
)
));
if (!$success) {
return (wc_notice_count('error') > 0) ?
wiaas_api_cart_error_notices() :
wiaas_api_notice('QUANTITY_NOT_UPDATED', 'error');
}
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'error',
'message' => 'QUANTITY_NOT_UPDATED'
)
)
));
return wiaas_api_notice('QUANTITY_UPDATED', 'success');
}
/**
* Placing order as part of checkout process
* TODO: This implementation is temporary to enable flow trough basic checkout process and should be changed
* @return WP_REST_Response
* @throws Exception
* Retrive cart documents info
*
* @return mixed|WP_REST_Response
*/
public static function place_order() {
public static function get_cart_documents() {
return rest_ensure_response( Wiaas_Cart::get_cart_documents());
}
$details = $_POST['details'];
$vat_code = $_POST['vat'];
$company_name = $_POST['companyName'];
$delivery_address = $_POST['delivery'];
$billing_address = $_POST['billing'];
/**
* Upload document to cart
* @param WP_REST_Request $request
*
* @return mixed|WP_REST_Response
*/
public static function upload_cart_document($request) {
$success = Wiaas_Cart::upload_cart_document($request['doc_type'], $request['package_key']);
$order_id = WC()->checkout()->create_order(array());
$order = wc_get_order( $order_id );
// set order currency
$line_items = $order->get_items();
foreach ($line_items as $line_item) {
if (isset($line_item['wiaas_currency'])) {
$order->set_currency($line_item['wiaas_currency']);
break;
}
if (!$success) {
return (wc_notice_count('error') > 0) ?
wiaas_api_cart_error_notices() :
wiaas_api_generate_error('UPLOAD_ERROR');
}
$order->set_shipping_city($delivery_address['city']);
$order->set_shipping_country($delivery_address['countryName']);
$order->set_shipping_address_1($delivery_address['detailedAddress']);
$order->set_shipping_postcode($delivery_address['zipCode']);
return wiaas_api_notice('FILE_UPLOADED', 'success');
}
$order->set_billing_city($billing_address['city']);
$order->set_billing_country($billing_address['countryName']);
$order->set_billing_address_1($billing_address['detailedAddress']);
$order->set_billing_postcode($billing_address['zipCode']);
$order->set_billing_first_name($billing_address['firstName']);
$order->set_billing_last_name($billing_address['lastName']);
$order->payment_complete();
/**
* Download cart document
* @param WP_REST_Request $request
*/
public static function download_cart_document($request) {
Wiaas_Document_Download::download_cart_document(
$request['key'],
$request['type'],
$request['document_key']);
}
add_post_meta($order_id, '_wiaas_vat_code', $vat_code);
add_post_meta($order_id, '_wiaas_company_name', $company_name);
add_post_meta($order_id, '_wiaas_project_id', $details['idProject']);
add_post_meta($order_id, '_wiaas_reference', $details['reference']);
add_post_meta($order_id, '_wiaas_tender', $details['tender']);
/**
* @param WP_REST_Request $request Request data.
*
* @return WP_REST_Response
*/
public static function checkout($request) {
// $order->get_li
Wiaas_Checkout::process_checkout($request->get_body_params());
WC()->cart->empty_cart( true );
if (wc_notice_count('error') > 0) {
return wiaas_api_cart_error_notices();
}
return new WP_REST_Response(array(
'messages' => array(
array(
'code' => 'success',
'message' => 'ORDER_PLACED'
)
),
'details' => $details
));
return wiaas_api_notice('ORDER_PLACED', 'success');
}
}

View File

@@ -17,26 +17,73 @@ class Wiaas_Document_API {
private static $namespace = 'wiaas';
public static function register_routes() {
register_rest_route( self::$namespace, 'download-package-file', array(
register_rest_route( self::$namespace, 'documents', array(
'methods' => 'GET',
'permission_callback' => 'is_user_logged_in',
'callback' => array(__CLASS__, 'download_package_file'),
'args' => array(
'document_id' => array(
'description' => __( 'Document ID.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
)
)
) );
register_rest_route( self::$namespace, 'documents/order/(?P<id>\d+)/(?P<type>[\w-]+)', array(
'args' => array(
'id' => array(
'description' => __( 'Order ID.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'type' => array(
'description' => __( 'Order document type.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
),
),
array(
'methods' => 'GET',
'permission_callback' => 'is_user_logged_in',
'callback' => array(__CLASS__, 'download_order_document'),
'args' => array(
'item_id' => array(
'description' => __( 'Package Order Item ID.', 'wiaas' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'document_key' => array(
'description' => __( 'Unique key identifier for order document.', 'wiaas' ),
'type' => 'string',
'sanitize_callback' => 'sanitize_key',
'required' => true
),
)
)
) );
}
/**
* Download package document
*
* @param WP_REST_Request $request
*/
public static function download_package_file() {
$document_id = $_GET['document_id'];
$package_id = $_GET['package_id'];
public static function download_package_file($request) {
$document_id = $request['document_id'];
$package = wc_get_product($package_id);
Wiaas_Document_Download::download_document($document_id);
}
$file = $package->get_file($document_id);
if ($file) {
WC_Download_Handler::download_file_force($package->get_file_download_path($document_id), $file->get_name());
}
/**
* Download order document
* @param WP_REST_Request $request
*/
public static function download_order_document($request) {
Wiaas_Document_Download::download_order_item_document(
$request['id'],
$request['item_id'],
$request['type'],
$request['document_key']);
}
}

View File

@@ -0,0 +1,83 @@
<?php
class Wiaas_Order_Projects_API {
/**
* Endpoint namespace.
*
* @var string
*/
private static $namespace = 'wiaas';
private static $rest_base = 'order-projects';
public static function register_routes() {
register_rest_route( self::$namespace, '/' . self::$rest_base, array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( __CLASS__, 'get_order_projects' ),
'permission_callback' => 'is_user_logged_in',
'args' => array(),
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( __CLASS__, 'create_order_project' ),
'permission_callback' => 'is_user_logged_in',
'args' => array(
'name' => array(
'type' => 'string',
'description' => __( 'Order project name.', 'wiaas' ),
'required' => true,
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => function($param, $request, $key) {
if ($param === '') {
return new WP_Error(
'rest_invalid_param',
'Order project name cannot be empty!'
);
}
if (strlen($param) > 100) {
return new WP_Error(
'rest_invalid_param',
'Order project name cannot be longer than 100 characters!'
);
}
},
),
),
)
) );
}
/**
* Retrieves available order projects
*
* @return WP_REST_Response
*/
public static function get_order_projects() {
$projects = Wiaas_Order_Project::get_available_order_projects();
return rest_ensure_response($projects);
}
/**
* Creates new available order project
*
* @param WP_REST_Request $request Request data.
*
* @return WP_REST_Response
*/
public static function create_order_project($request) {
$name = $request['name'];
$success = Wiaas_Order_Project::add_order_project($name);
if ($success) {
return wiaas_api_notice('PROJECT_ADDED', 'success');
}
return wiaas_api_notice('INVALID_DATA', 'error');
}
}

View File

@@ -0,0 +1,79 @@
<?php
class Wiaas_Package_API {
private static $namespace = 'wiaas';
public static function init() {
add_filter('woocommerce_rest_product_object_query', array(__CLASS__, 'filter_packages'), 10, 2);
}
public static function register_routes() {
// TODO: Handle this when assigment of customer to commercial lead is done
register_rest_route( self::$namespace, '/commercial-leads', array(
'methods' => WP_REST_Server::READABLE,
'callback' => array(__CLASS__, 'get_customer_commercial_leads'),
'permission_callback' => 'is_user_logged_in'
) );
}
// TODO: Handle this when assigment of customer to commercial lead is done
public static function get_customer_commercial_leads() {
$commercial_leads = array();
foreach (wiaas_get_commercial_leads() as $id => $name) {
$commercial_leads[] = array(
'id' => $id,
'name' => $name
);
}
return rest_ensure_response($commercial_leads);
}
/**
* Filter woocommerce REST API query so only valid wiaas packages are returned to the customer
*
* @param $args
* @param $request
*
* @return mixed
*/
public static function filter_packages($args, $request) {
if ( empty($query['tax_query']) ){
$query['tax_query'] = array();
}
// Retrieve only packages with available package status
$query['tax_query'][] = array(
'taxonomy' => 'package_status',
'field' => 'name',
'terms' => Wiaas_Package_Status::AVAILABLE
);
$commercial_lead_id = absint($request['cl_id']);
$customer_id = wiaas_get_current_user_organization_id();
$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());
$price_search_terms = array();
foreach ($pay_types as $pay_type) {
$price_search_terms[] = '_' . $commercial_lead_id . '_' . $pay_type . '_default';
$price_search_terms[] = '_' . $commercial_lead_id . '_' . $pay_type . '_customer_' . $customer_id;
}
$args['tax_query'][] = array(
'taxonomy' => '_wiaas_shop_prices',
'terms' => $price_search_terms,
'field' => 'slug'
);
return $args;
}
}
Wiaas_Package_API::init();

View File

@@ -0,0 +1,153 @@
<?php
class Wiaas_REST_Customer_API {
/**
* Endpoint namespace.
*
* @var string
*/
private static $namespace = 'wiaas';
public function __construct() {
include_once dirname( __FILE__ ) . '/../user/class-wiaas-customer.php';
include_once dirname( __FILE__ ) . '/helper/class-rest-helper-functions.php';
}
public static function register_routes() {
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/profile-addresses', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_profile_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/profile-addresses/(?P<address_id>\d+)', array(
'methods' => 'DELETE',
'callback' => array(__CLASS__, 'delete_customer_profile_address'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/billing-addresses', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_billing_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/billing-addresses/(?P<address_id>\d+)', array(
'methods' => 'DELETE',
'callback' => array(__CLASS__, 'delete_customer_billing_addresses'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/personal-info', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_personal_info'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'customer/(?P<id>\d+)/company-info', array(
'methods' => 'PUT',
'callback' => array(__CLASS__, 'update_customer_company_info'),
'permission_callback' => 'is_user_logged_in'
) );
}
public static function update_customer_profile_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$new_address = json_decode($params['profile_address']);
if (!Wiaas_Customer::update_customer_profile_addresses($customer_id, $new_address)){
return wiaas_api_notice('PROFILE_ADDRESS_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('PROFILE_ADDRESS_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function delete_customer_profile_address(WP_REST_Request $request){
$customer_id = $request['id'];
$address_id = $request['address_id'];
if (!Wiaas_Customer::delete_customer_profile_address($customer_id, $address_id)){
return wiaas_api_notice('ADDRESS_ERROR', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('ADDRESS_REMOVED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_billing_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$new_address = json_decode($params['billing_address']);
if (!Wiaas_Customer::update_customer_billing_addresses($customer_id, $new_address)){
return wiaas_api_notice('BILLING_ADDRESS_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('BILLING_ADDRESS_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function delete_customer_billing_addresses(WP_REST_Request $request){
$customer_id = $request['id'];
$address_id = $request['address_id'];
if (!Wiaas_Customer::delete_customer_billing_address($customer_id, $address_id)){
return wiaas_api_notice('ADDRESS_ERROR', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('ADDRESS_REMOVED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_personal_info(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$first_name = $params['first_name'];
$last_name = $params['last_name'];
$phone = $params['phone'];
$name = $first_name . ' ' . $last_name;
if (!is_string($name) || strlen($name) === 1){
return wiaas_api_notice('ADD_NAME', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!is_string($phone) || strlen($phone) < 1){
return wiaas_api_notice('ADD_PHONE_NUMBER', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!Wiaas_Customer::update_customer_profile_info($customer_id, $first_name, $last_name, $phone)){
return wiaas_api_notice('PROFILE_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('PROFILE_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
public static function update_customer_company_info(WP_REST_Request $request){
$customer_id = $request['id'];
$params = $request->get_body_params();
$company_name = $params['company_name'];
$vat_code = $params['vat_code'];
if (!is_string($company_name) || strlen($company_name) < 1){
return wiaas_api_notice('ADD_COMPANY_NAME', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!is_string($vat_code) || strlen($vat_code) < 1){
return wiaas_api_notice('ADD_VAT', 'error', Wiaas_Customer::get_customer_info($customer_id));
}
if (!Wiaas_Customer::update_customer_company_info($customer_id, $company_name, $vat_code)){
return wiaas_api_notice('COMPANY_NOT_CHANGED', 'warning', Wiaas_Customer::get_customer_info($customer_id));
}
return wiaas_api_notice('COMPANY_UPDATED', 'success', Wiaas_Customer::get_customer_info($customer_id));
}
}

View File

@@ -93,15 +93,13 @@ class Wiass_REST_Delivery_Process_API {
);
}
$response = new WP_REST_Response( $data );
return $response;
return rest_ensure_response($data);
}
public static function get_customer_acceptance(WP_REST_Request $request){
$entry = GFAPI::get_entry($request['entry_id']);
if (is_wp_error($entry)){
return self::generate_error('Customer acceptance entry not found', 404);
return wiaas_api_generate_error('Customer acceptance entry not found', 404);
}
$acceptance_documents = array();
@@ -130,27 +128,25 @@ class Wiass_REST_Delivery_Process_API {
$acceptance_status = ($entry[self::ACCEPTANCE_STATUS_FIELD_ID] === 'accept') ? 1 : -1;
}
$result = array(
return rest_ensure_response(array(
'documents' => $acceptance_documents,
'expiration' => $entry[self::EXPIRATION_DATE_FIELD_ID],
'status' => $acceptance_status,
'decline_reason' => $entry[self::DECLINE_REASON_FIELD_ID]
);
return new WP_REST_Response($result);
));
}
public static function submit_customer_acceptance(WP_REST_Request $request){
$entry = GFAPI::get_entry($request['entry_id']);
if (is_wp_error($entry)){
return self::generate_error('Customer acceptance entry not found', 404);
return wiaas_api_generate_error('Customer acceptance entry not found', 404);
}
$status = $request['actionType'];
$reason = $request['declineReason'];
if (!in_array($status, self::ACCEPTABLE_STATUS)){
return self::generate_wiaas_response('ACCEPTANCE_STATUS_MISSING', 'error');
return wiaas_api_notice('ACCEPTANCE_STATUS_MISSING', 'error');
}
$installation_declined = ($status === self::DECLINE_STATUS_LABEL);
@@ -158,25 +154,25 @@ class Wiass_REST_Delivery_Process_API {
$uploaded_files = json_decode($entry[self::UPLOADED_FILES_FIELD_ID]);
if ($installation_declined && $reason === ''){
return self::generate_wiaas_response('DECLINE_REASON_EMPTY', 'error');
return wiaas_api_notice('DECLINE_REASON_EMPTY', 'error');
}
if (!$installation_declined && (count($uploaded_files)===0)){
return self::generate_wiaas_response('ACCEPTANCE_NOT_UPLOADED', 'error');
return wiaas_api_notice('ACCEPTANCE_NOT_UPLOADED', 'error');
}
$entry[self::DECLINE_REASON_FIELD_ID] = $reason;
$entry[self::ACCEPTANCE_STATUS_FIELD_ID] = $status;
if (!GFAPI::update_entry( $entry )){
return self::generate_wiaas_response('INTERNAL_SERVER_ERROR', 'error');
return wiaas_api_notice('INTERNAL_SERVER_ERROR', 'error');
}
//Check if step is already completed, to not submit again
$gf_api = new Gravity_Flow_API($entry['form_id']);
$current_step = $gf_api->get_current_step($entry);
if ($current_step->get_name() !== self::USER_INPUT_STEP_NAME){
return self::generate_wiaas_response('ACCEPTANCE_STATUS_UPDATED', 'success');
return wiaas_api_notice('ACCEPTANCE_STATUS_UPDATED', 'success');
}
if ( $current_step ) {
@@ -195,20 +191,20 @@ class Wiass_REST_Delivery_Process_API {
if ($installation_declined){
return self::generate_wiaas_response('INSTALLATION_DECLINED', 'success');
return wiaas_api_notice('INSTALLATION_DECLINED', 'success');
}
return self::generate_wiaas_response('INSTALLATION_ACCEPTED', 'success');
return wiaas_api_notice('INSTALLATION_ACCEPTED', 'success');
}
public static function upload_file(WP_REST_Request $request){
$files = $request->get_file_params();
if (!$files[self::FILE_KEY_NAME]){
return self::generate_wiaas_response('NO_FILES_UPLOADED', 'error');
return wiaas_api_notice('NO_FILES_UPLOADED', 'error');
}
$entry = GFAPI::get_entry($request['entry_id']);
if (is_wp_error($entry)){
return self::generate_error('Customer acceptance entry not found', 404);
return wiaas_api_generate_error('Customer acceptance entry not found', 404);
}
$form = GFAPI::get_form($entry['form_id']);
@@ -223,12 +219,12 @@ class Wiass_REST_Delivery_Process_API {
$file_path_details = pathinfo($file_name);
if ( GFCommon::file_name_has_disallowed_extension( $file_name ) ) {
return self::generate_wiaas_response('INVALID_FILE_ACCEPTANCE', 'error');
return wiaas_api_notice('INVALID_FILE_ACCEPTANCE', 'error');
}
$allowed_extensions = ! empty( $upload_file_field->allowedExtensions ) ? GFCommon::clean_extensions( explode( ',', strtolower( $upload_file_field->allowedExtensions ) ) ) : array();
if ( ! empty( $allowed_extensions ) ) {
if ( ! GFCommon::match_file_extension( $file_name, $allowed_extensions ) ) {
return self::generate_wiaas_response('INVALID_FILE_ACCEPTANCE', 'error');
return wiaas_api_notice('INVALID_FILE_ACCEPTANCE', 'error');
}
}
@@ -236,13 +232,13 @@ class Wiass_REST_Delivery_Process_API {
// Bypasses security checks when running unit tests.
if ( defined( 'WP_TEST_IN_PROGRESS' ) && WP_TEST_IN_PROGRESS ) {
return self::generate_wiaas_response('FILE_UPLOADED', 'success');
return wiaas_api_notice('FILE_UPLOADED', 'success');
}
if ( move_uploaded_file($files[self::FILE_KEY_NAME]['tmp_name'], $target_path . $new_file_name ) ) {
GFFormsModel::set_permissions( $target_path . $new_file_name );
} else {
return self::generate_wiaas_response('INTERNAL_SERVER_ERROR', 'error');
return wiaas_api_notice('INTERNAL_SERVER_ERROR', 'error');
}
//Extract path relative to the root
@@ -269,35 +265,9 @@ class Wiass_REST_Delivery_Process_API {
$entry[self::UPLOADED_FILES_FIELD_ID] = json_encode($uploaded_files);
if (GFAPI::update_entry( $entry )) {
return self::generate_wiaas_response('FILE_UPLOADED','success');
return wiaas_api_notice('FILE_UPLOADED','success');
}
return self::generate_wiaas_response('NOT_UPLOADED', 'error');
}
//Helper function
private static function generate_error($message, $code = 500){
$error = array(
'status' => $code,
'message' => $message,
);
$result = new WP_REST_Response($error);
$result->set_status($code);
return $result;
}
private static function generate_wiaas_response($message, $code, $data = NULL){
$response = array(
'messages' => [
array(
'code' => $code,
'message' => $message
)
],
'data' => $data
);
return new WP_REST_Response($response);
return wiaas_api_notice('NOT_UPLOADED', 'error');
}
}

View File

@@ -0,0 +1,50 @@
<?php
class Wiass_REST_User_API {
/**
* Endpoint namespace.
*
* @var string
*/
private static $namespace = 'wiaas';
public function __construct() {
include_once dirname( __FILE__ ) . '/../class-wiaas-countries.php';
}
public static function register_routes() {
register_rest_route( self::$namespace, 'user/validate-token', array(
'methods' => 'POST',
'callback' => array(__CLASS__, 'validate_token'),
'permission_callback' => 'is_user_logged_in'
) );
register_rest_route( self::$namespace, 'user/get-countries', array(
'methods' => 'GET',
'callback' => array(__CLASS__, 'get_countries'),
'permission_callback' => 'is_user_logged_in'
) );
}
public static function validate_token() {
$user = wp_get_current_user();
return rest_ensure_response(array(
'userInfo' => array(
'wiaas_id_user' => $user->ID,
'wiaas_is_company_admin' => 1, //TODO: don't hardcode this
'wiaas_user_full_name' => $user->first_name . ' ' . $user->last_name,
'wiaas_user_type' => $user->roles,
'wiaas_username' => $user->data->user_login
)
));
}
public static function get_countries(){
$countries = Wiaas_Countries::get_list_of_countries();
return rest_ensure_response($countries);
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* Generates REST API notice response
*
* @param string $message
* @param string $code
* @param array|null $data
*
* @return WP_REST_Response
*/
function wiaas_api_notice($message, $code, $data = null) {
return rest_ensure_response(array(
'messages' => [
array(
'code' => $code,
'message' => $message
)
],
'data' => $data
));
}
/**
* Generates REST API notice responses with wc error notices
*
* @param array|null $data
*
* @return WP_REST_Response
*/
function wiaas_api_cart_error_notices($data = null) {
return wiaas_api_cart_notices('error', $data);
}
/**
* Generates REST API notice responses with wc warning notices
*
* @param array|null $data
*
* @return WP_REST_Response
*/
function wiaas_api_cart_warning_notices($data = null) {
return wiaas_api_cart_notices('notice', $data);
}
/**
* Generates REST API notice responses with wc notices
*
* @param string $types Notice types (error, success)
* @param array|null $data
*
* @return WP_REST_Response
*/
function wiaas_api_cart_notices($types, $data = null) {
$types = is_array($types) ? $types : array( $types );
$messages = array();
foreach ($types as $type) {
$messages = array_merge($messages, wc_get_notices($type));
}
wc_clear_notices();
$messages = array_map(function($message) {
return array(
'code' => 'error',
'message' => $message
);
}, $messages);
return rest_ensure_response(array(
'messages' => $messages,
'data' => $data
));
}
/**
* Generate REST API error
*
* @param string $message
* @param int $code
*
* @return WP_REST_Response
*/
function wiaas_api_generate_error($message, $code = 500) {
$response = rest_ensure_response(array(
'status' => $code,
'message' => $message,
));
$response->set_status($code);
return $response;
}

View File

@@ -0,0 +1,36 @@
<?php
class Wiaas_Cart_Documents {
private static $document_types = array(
'template_questionaire' => 'template_agreement',
'order_questionaire' => 'order_agreement'
);
public static function get_cart_documents() {
$packages_data = Wiaas_Cart::get_cart_packages();
$templates = array();
foreach ($packages_data as $package_data) {
$package = wc_get_product($packages_data['package_id']);
$documents = $package->get_downloads();
}
get_terms(array(
'taxonomy' => 'wiaas_document_types',
'include' => 'template_questionaire, order_questionaire'
));
}
private static function _get_packages_templates($packages) {
$documents_ids = array_map(function($package) {
return array_keys($package->get_downloads());
}, $packages);
wp_get_object_terms($documents_ids, 'wiaas_document_types', array(
));
}
}

View File

@@ -0,0 +1,51 @@
<?php
class Wiaas_Access_Management {
public static function init() {
add_action( 'save_post', array( __CLASS__, 'maybe_handle_product_access' ), 999, 2 );
}
/**
* Automatize access control for product and packages
*
* @param int $post_id
* @param WP_Post $post
*/
public static function maybe_handle_product_access($post_id, $post) {
// $post_id and $post are required
if ( empty( $post_id ) || empty( $post ) || $post->post_type !== 'product') {
return;
}
$product = wc_get_product($post_id);
$admin_access_group = Groups_Group::read_by_name('admin');
$access_group_ids = array();
if ($admin_access_group) {
$access_group_ids[] = $admin_access_group->group_id;
}
// allow commercial lead to see published bundle products
$cl_access_group = Groups_Group::read_by_name('commercial_lead');
if ($product->get_type() === 'bundle' &&
$product->get_status() === 'publish' &&
$cl_access_group) {
$access_group_ids[] = $cl_access_group->group_id;
}
Groups_Post_Access::update(
array(
'post_id' => $product->get_id(),
'groups_read' => $access_group_ids
) );
}
}
Wiaas_Access_Management::init();

View File

@@ -12,7 +12,26 @@ class Wiaas_Admin {
require_once dirname(__FILE__) . '/admin/template/class-wiaas-admin-template-selection.php';
require_once dirname(__FILE__) . '/admin/template/class-wiaas-template-products.php';
require_once dirname(__FILE__) . '/admin/template/class-wiaas-template-admin-ajax.php';
// Admin order projects interface
require_once dirname(__FILE__) . '/admin/class-wiaas-admin-order-projects.php';
// Admin documents
require_once dirname(__FILE__) . '/admin/class-wiaas-admin-documents.php';
// Admin organization interface
require_once dirname(__FILE__) . '/admin/class-wiaas-admin-organization.php';
require_once dirname(__FILE__) . '/admin/class-wiaas-admin-cl.php';
add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 100 );
}
public static function enqueue_scripts() {
$plugin_url = untrailingslashit( plugins_url( '/', WIAAS_FILE ) );
wp_enqueue_style( 'wiaas_admin_menu', $plugin_url . '/assets/css/menu.css' );
wp_enqueue_style( 'wiaas_admin_packages', $plugin_url . '/assets/css/package.css' );
}
}
Wiaas_Admin::init();

View File

@@ -34,13 +34,31 @@ class Wiaas_API {
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-delivery-process-api.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-cart-api.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-document-api.php';
#User controller
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-user-api.php';
#Customer controller
include_once dirname( __FILE__ ) . '/api/class-wiaas-rest-customer.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-order-projects-api.php';
include_once dirname( __FILE__ ) . '/api/class-wiaas-package-api.php';
// API functions
include_once dirname( __FILE__ ) . '/api/wiaas-api-functions.php';
}
public static function register_rest_routes() {
$controllers = array(
'Wiass_REST_Delivery_Process_API',
'Wiaas_Cart_API',
'Wiaas_Document_API'
'Wiaas_Document_API',
'Wiass_REST_User_API',
'Wiaas_REST_Customer_API',
'Wiaas_Order_Projects_API',
'Wiaas_Package_API'
);
foreach ( $controllers as $controller ) {

View File

@@ -0,0 +1,200 @@
<?php
/**
* Handles user authentication for wiaas
*
* User roles are inherited from organization
*
* Class Wiaas_Authentication
*/
class Wiaas_Authentication {
const SUPER_ADMIN_USER_ID = 1;
public static function init() {
// authenticate current user
add_action('determine_current_user', array(__CLASS__, 'authenticate_current_user'), 999);
// authenticates user on login
add_filter( 'authenticate', array( __CLASS__, 'authenticate_user_on_login' ), 999, 3);
// retrieve preferred user role for user
add_filter('get_user_metadata', array(__CLASS__, 'maybe_filter_user_roles'), 10, 3);
// redirect to dashboard after login
add_filter( 'login_redirect', array( __CLASS__, 'login_redirect' ) );
// add role selector to login form
add_action('login_form', array(__CLASS__, 'pick_role_on_login'));
}
/**
* Redirect admin user to dashboard
*
* @return string
*/
public static function login_redirect() {
return admin_url('index.php') ;
}
/**
* Add role selector to login form
*/
public static function pick_role_on_login() {
?>
<p>
<label for="user_role"><?php esc_html_e( 'Role' , 'wiaas'); ?><br />
<select id="user_role" class="input" name="role">
<option value="administrator"><?php esc_html_e('Administrator', 'wiaas') ?></option>
<option value="supplier"><?php esc_html_e('Supplier', 'wiaas') ?></option>
<option value="commercial_lead"><?php esc_html_e('Commercial Lead', 'wiaas') ?></option>
</select>
</p>
<?php
}
/**
* Authenticate current user based on roles assigned to organization
*
* @param int|false $user_id
* @return int|false|WP_Error
*/
public static function authenticate_current_user($user_id) {
// do nothing if user not authenticated, user is super admin or this is REST API request
if (! $user_id || $user_id === self::SUPER_ADMIN_USER_ID) {
return $user_id;
}
$is_rest_api = strpos($_SERVER['REQUEST_URI'], rest_get_url_prefix());
$role = $is_rest_api ?
'customer' :
get_user_meta($user_id, '_wiaas_current_user_admin_role', true);
$result = self::_can_user_have_role($user_id, $role, $is_rest_api);
if (is_wp_error($result)) {
return false;
}
return $user_id;
}
/**
* Authenticate wiaas user on login based on roles assigned to organization
*
* @param WP_User $user
* @return WP_User|WP_Error
*/
public static function authenticate_user_on_login($user) {
// check if rest request
$is_rest_api = strpos($_SERVER['REQUEST_URI'], rest_get_url_prefix());
// do nothing if there is an error already,
// user is super admin or
// this is rest request
if (is_wp_error($user) || $user->ID === 1 || $is_rest_api) {
return $user;
}
if (empty($_POST['role'])) {
return new WP_Error('error', 'You must selected role to login!');
}
// get selected role
$requested_role = sanitize_key($_POST['role']);
// validate can user have requested role
$result = self::_can_user_have_role($user->ID, $requested_role, false);
// if user organization has no requested role prevent access
if (is_wp_error($result)) {
return $result;
}
// remember role for user and continue
update_user_meta($user->ID, '_wiaas_current_user_admin_role', $requested_role);
return $user;
}
/**
*
* Filters user roles retrieval so that selected user role is retrieved for admin panel
* and customer role is retrieved for JSON API request
*
* @param $null
* @param int $user_id
* @param string $meta_key
* @return array|null
*/
public static function maybe_filter_user_roles($null, $user_id, $meta_key) {
global $wpdb;
if ($user_id !== 0 && $user_id !== self::SUPER_ADMIN_USER_ID && $meta_key === $wpdb->get_blog_prefix() . 'capabilities') {
$is_rest_api = strpos($_SERVER['REQUEST_URI'], rest_get_url_prefix());
$role = $is_rest_api ?
'customer' :
get_user_meta($user_id, '_wiaas_current_user_admin_role', true);
return array( array ( "$role" => true ));
}
return null;
}
// PRIVATE
/**
* Determines if user can have requested role based on his organization roles
*
* @param int $user_id
* @param string $user_role
* @param bool $is_rest_api
* @return bool|WP_Error
*/
private static function _can_user_have_role($user_id, $user_role, $is_rest_api) {
// check if role valid for access
if (! wp_roles()->is_role($user_role)) {
return new WP_Error('error', 'Role is not valid!');
}
// only customer role can access API
if ($is_rest_api && $user_role !== 'customer') {
return new WP_Error('error', 'No access!');
}
// customer role cannot access admin backend
if (! $is_rest_api && $user_role === 'customer') {
return new WP_Error('error', 'No access!');
}
// import organization functions (during user authentication it is not yet loaded)
require_once dirname( __FILE__ ) . '/user/wiaas-organization-functions.php';
// get user organization
$organization_id = wiaas_get_user_organization_id($user_id);
// validate if user has organization
if (empty( $organization_id)) {
return new WP_Error('error', 'Account not completed!');
}
// get organization roles
$roles = wiaas_get_organization_roles($organization_id);
// validate if user has organization roles
if (!in_array($user_role, $roles)) {
return new WP_Error( 'error', 'Your account is not authorized for requested role. Please contact us for help.' );
}
return true;
}
}
Wiaas_Authentication::init();

View File

@@ -6,121 +6,249 @@ if ( ! defined( 'ABSPATH' ) ) {
/**
* TODO: This implementation is temporary and will probably be changed during implementation of currently pending cart task
* Handles Wiaas Cart specific tasks
*
* Class Wiaas_Cart
*/
class Wiaas_Cart {
private static $cart_doc_types = array(
'template_questionaire' => 'order_questionaire',
'template_agreement' => 'order_agreement'
);
public static function init() {
add_action( 'woocommerce_checkout_create_order_line_item', array( __CLASS__, 'add_order_item_meta' ), 10, 3 );
add_filter( 'woocommerce_hidden_order_itemmeta', array( __CLASS__, 'hidden_order_item_meta' ) );
add_filter( 'woocommerce_add_cart_item_data', array( __CLASS__, 'add_cart_item_data' ), 10, 2 );
add_action( 'woocommerce_before_calculate_totals', array( __CLASS__, 'on_calculate_totals' ), 99, 1);
add_action( 'woocommerce_cart_loaded_from_session', array( __CLASS__, 'on_calculate_totals' ), 99, 1);
// Add options and addons to cart.
add_action( 'woocommerce_add_to_cart', array( __CLASS__, 'add_additional_packages_to_cart' ), 10, 6 );
}
/**
* Retrieve cart documents (templates and uploded documents)
* @return array
*/
public static function get_cart_documents() {
$templates = self::_get_cart_templates();
$uploaded_documents = self::_get_cart_uploaded_documents();
$has_pending_uploads = false;
foreach ($templates as $type => $package_documents) {
$uploaded_type = self::$cart_doc_types[$type];
if (!isset($uploaded_documents[$uploaded_type])) {
$has_pending_uploads = true;
break;
}
$uploaded_package_documents = $uploaded_documents[$uploaded_type];
foreach ($package_documents as $package_id => $package_document) {
if (!isset($uploaded_package_documents[$package_id])) {
$has_pending_uploads = true;
break;
}
}
}
return array(
'templates' => $templates,
'uploaded' => $uploaded_documents,
'pending' => $has_pending_uploads
);
}
/** Uploaded document for cart
*
* @param $doc_type
* @param $package_item_key
*
* @return string | WP_Error
*/
public static function upload_cart_document($doc_type, $package_item_key) {
try {
$result = Wiaas_Document_Upload::upload_document_version();
// File upload failed
if (is_wp_error($result)) {
$code = $result->get_error_code();
if ($code === 'wiaas_upload_error_missing_file' || $code === 'wiaas_upload_error_invalid_extension') {
wc_add_notice($result->get_error_message(), 'error');
} else {
wc_add_notice('File upload failed!', 'error');
}
return false;
}
// save uploaded cart documents info to cart item
WC()->cart->cart_contents[ $package_item_key ]['_wiaas_documents'][$doc_type] = array(
'version' => $result,
'key' => wp_generate_uuid4(),
);;
// persist changes
WC()->cart->calculate_totals();
return true;
} catch( Exception $e) {
wc_add_notice('Could not upload cart document!', 'error');
return false;
}
}
/**
* Handles adding standard wiaas package to cart along with selected addons and options
*
* Extend cart item data with wiaas package payment info and addons and options
*
* Every package cart item will be extended with its payment info but only standard package type
* will be extended with addons and options arrays
*
* @param $cart_item_data
* @param $package_id
* @param int $package_id Package ID of selected package
* @param string $price_id Price ID of selected package payment
* @param array $addons_ids Array of selected additional packages IDs
* @param array $options_ids Array of selected option packages IDs
*
* @return array
* @return bool TRUE if all packages are succesfully added to cart, FALSE otherwise
*/
public static function add_cart_item_data($cart_item_data, $package_id) {
public static function add_package_to_cart($package_id, $price_id, $addons_ids, $options_ids) {
// try adding package to cart
try {
// Check if package is in cart
if (self::_is_package_in_cart($package_id)) {
wc_add_notice('Package already in cart!', 'error');
return false;
}
$is_valid = isset( $_POST[ 'price_id' ]) &&
WC_Product_Factory::get_product_type( $package_id ) === 'bundle';
//Check if package exists
$package = wc_get_product( $package_id );
if (!$package) {
wc_add_notice('Package does not exists!', 'error');
return false;
}
if (!$is_valid) {
return $cart_item_data;
//Check if package is available for adding to cart
if (Wiaas_Package_Status::get_package_status($package_id) !== Wiaas_Package_Status::AVAILABLE){
wc_add_notice('Package cannot be purchased at the moment', 'error');
return false;
}
// Retrieve package country
$country = Wiaas_Countries::get_package_country($package);
// TODO: Change this so commercial lead is sent via request
$customer_id = wiaas_get_current_user_organization_id();
$commercial_lead_id = array_keys(wiaas_get_commercial_leads())[0];
// Retrieve package price
$package_prices = Wiaas_Pricing::get_standard_package_customer_prices($package, $customer_id, $commercial_lead_id);
$selected_price_index = array_search($price_id, array_column($package_prices, 'id'));
// Initialize additional cart item data for wiaas packages
$wiaas_cart_item_data = array(
'_wiaas_standard_package' => true,
'_wiaas_addon_items' => array(),
'_wiaas_option_items' => array(),
'_wiaas_currency' => isset($country) ? $country['currency'] : get_woocommerce_currency(),
'_wiaas_payment' => $package_prices[$selected_price_index] ? $package_prices[$selected_price_index] : null,
'_wiaas_documents' => array()
);
$cart_item_key = WC()->cart->add_to_cart($package_id, 1, 0, array(), $wiaas_cart_item_data);
if (!$cart_item_key) {
wc_add_notice('Package could not be added to cart!', 'error');
return false;
}
// Add selected additional packages and options
self::_add_additional_packages_to_cart($cart_item_key, $price_id, $addons_ids, $options_ids);
// Trigger calculation of total prices after additional packages are added
WC()->cart->calculate_totals();
return true;
} catch( Exception $e) {
return false;
}
}
/**
* Remove given package item key from cart
*
* @param string $package_cart_item_key
*
* @return bool
*/
public static function remove_package_from_cart($package_cart_item_key) {
$cart_item = WC()->cart->get_cart_item($package_cart_item_key);
if (!$cart_item) {
return false;
}
$package_type = Wiaas_Package_Type::get_package_type($package_id);
$package_addon_item_keys = $cart_item['_wiaas_addon_items'];
$package_option_item_keys = $cart_item['_wiaas_option_items'];
$package = wc_get_product( $package_id );
$success = WC()->cart->remove_cart_item($package_cart_item_key);
switch ($package_type) {
case 'standard':
if ($success) {
foreach ($package_addon_item_keys as $package_addon_item_key) {
WC()->cart->remove_cart_item($package_addon_item_key);
}
$cart_item['_wiaas_standard_package'] = true;
// Prepare addons additional data for later use.
if ( ! isset( $cart_item_data['_wiaas_addon_items'] ) ) {
$cart_item_data['_wiaas_addon_items' ] = array();
}
// Prepare options additional data for later use.
if ( ! isset( $cart_item_data['_wiaas_option_items'] ) ) {
$cart_item_data['_wiaas_option_items' ] = array();
}
$country = Wiaas_Countries::get_package_country($package);
if (isset($country)) {
$cart_item_data['_wiaas_currency'] = $country['currency'];
}
$package_prices = Wiaas_Pricing::get_standard_package_customer_prices($package);
break;
case 'add_on':
$parent_key = $cart_item_data['_wiaas_addon_for'];
$parent_item = WC()->cart->get_cart_item($parent_key);
$package_prices = Wiaas_Pricing::get_addon_package_customer_price($package, $parent_item['data']);
break;
case 'option':
$parent_key = $cart_item_data['_wiaas_option_for'];
$parent_item = WC()->cart->get_cart_item($parent_key);
$option_group_name = Wiaas_Package_Option_Groups::get_group_name_for_package_option($parent_item['data'], $package);
$cart_item_data['_wiaas_option_group_name' ] = $option_group_name;
$package_prices = Wiaas_Pricing::get_option_package_customer_price($package, $parent_item['data']);
break;
foreach ($package_option_item_keys as $package_option_item_key) {
WC()->cart->remove_cart_item($package_option_item_key);
}
}
$selected_price_index = array_search($_POST['price_id'], array_column($package_prices, 'id'));
if (is_numeric($selected_price_index) && isset($package_prices[$selected_price_index])) {
$cart_item_data['_wiaas_payment'] = $package_prices[$selected_price_index];
}
return $cart_item_data;
return $success;
}
/**
* Add selected package options and addons after parent standard package is added to cart
* Update quantity of package in cart
* @param string $package_cart_item_key
* @param int $new_quantity
*
* @param $cart_item_key
* @param $package_id
* @param $quantity
* @param $variation_id
* @param $variation
* @param $cart_item_data
* @return bool
*/
public static function add_additional_packages_to_cart($cart_item_key, $package_id, $quantity, $variation_id, $variation, $cart_item_data) {
public static function update_package_quantity($package_cart_item_key, $new_quantity) {
$cart_item = WC()->cart->get_cart_item($package_cart_item_key);
remove_action( 'woocommerce_add_to_cart', array( __CLASS__, 'add_additional_packages_to_cart' ));
if (!$cart_item) {
return false;
}
self::_add_options_to_cart($cart_item_key, $package_id, $cart_item_data);
$package_addon_item_keys = $cart_item['_wiaas_addon_items'];
$package_option_item_keys = $cart_item['_wiaas_option_items'];
self::_add_addons_to_cart($cart_item_key, $package_id, $cart_item_data);
$success = WC()->cart->set_quantity($package_cart_item_key, $new_quantity, true);
add_action( 'woocommerce_add_to_cart', array( __CLASS__, 'add_additional_packages_to_cart' ), 10, 6 );
if ($success) {
foreach ($package_addon_item_keys as $package_addon_item_key) {
WC()->cart->set_quantity($package_addon_item_key, $new_quantity, true);
}
foreach ($package_option_item_keys as $package_option_item_key) {
WC()->cart->set_quantity($package_option_item_key, $new_quantity, true);
}
}
return $success;
}
/**
* Update package cart item with `minimal_fixed_price` as its price
* so resulting totals would be sum of these prices
@@ -150,7 +278,7 @@ class Wiaas_Cart {
* @param $cart_item
* @param $order
*
* @return array
* @return WC_Order_Item
*/
public static function add_order_item_meta( $order_item, $cart_item_key, $cart_item ) {
if (wc_pb_is_bundle_container_cart_item($cart_item) && isset($cart_item['_wiaas_payment'])) {
@@ -193,6 +321,40 @@ class Wiaas_Cart {
if (isset($cart_item['_wiaas_addon_for'])) {
$order_item->add_meta_data( '_wiaas_addon_for', $cart_item['_wiaas_addon_for'], true );
}
// add documents associated with the item
$cart_documents = isset($cart_item['_wiaas_documents']) ? $cart_item['_wiaas_documents'] : array();
$attachment_document_ids = wiaas_get_object_attached_documents($cart_item['product_id']);
$item_documents = array();
foreach ($cart_documents as $type => $cart_document) {
$item_documents[] = array(
'key' => $cart_document['key'],
'version' => $cart_document['version'],
'type' => $type
);
}
foreach ($attachment_document_ids as $attachment_document_id) {
$doc_info = Wiaas_Document::get_doc_info($attachment_document_id);
// add customer visible attachment documents to order
if ($doc_info['visible'] || !$doc_info['type']) {
$item_documents[] = array(
'key' => wp_generate_uuid4(),
'name' => $doc_info['name'],
'version' => $doc_info['version'],
'type' => $doc_info['type']['id'],
);
}
}
if (count($item_documents) > 0) {
$order_item->add_meta_data( '_wiaas_documents', $item_documents, true );
}
return $order_item;
}
/**
@@ -218,6 +380,7 @@ class Wiaas_Cart {
'_wiaas_option_group_name',
'_wiaas_standard_package',
'_wiaas_currency',
'_wiaas_documents'
) );
}
@@ -264,72 +427,329 @@ class Wiaas_Cart {
);
}
/**
* Retrieves count of wiaas standard packages in cart
*
* @return int Number of wiaas standard packages in cart
*/
public static function get_cart_packages_count() {
$items = WC()->cart->get_cart_contents();
return array_reduce($items, function($count, $item) {
if (isset($item['_wiaas_standard_package'])) {
$count++;
}
return $count;
}, 0);
}
/**
* Retrieves packages data from cart
* @return array
*/
public static function get_cart_packages() {
$items = WC()->cart->get_cart_contents();
$package_items = array();
foreach ($items as $key => $item) {
if (!isset($item['_wiaas_standard_package'])) {
continue;
}
$package = wc_get_product($item['product_id']);
// Collect additional packages
$additional_packages = array_map(
function($addon_cart_item) {
$additional_package = wc_get_product($addon_cart_item['product_id']);
return array(
'package_id' => $additional_package->get_id(),
'package_name' => $additional_package->get_title(),
'prices' => array(
'fixed_extra' => $addon_cart_item['_wiaas_payment']['fixed_extra'],
'recurrent_extra' => $addon_cart_item['_wiaas_payment']['recurrent_extra'],
'services_extra' => $addon_cart_item['_wiaas_payment']['services_extra'],
)
);
},
wiaas_get_cart_item_addons($item));
// Collect package options
$package_options = array_map(
function($option_cart_item) {
$option_package = wc_get_product($option_cart_item['product_id']);
return array(
'package_id' => $option_package->get_id(),
'group_name' => $option_cart_item['_wiaas_option_group_name'],
'package_name' => $option_package->get_title(),
'prices' => array(
'fixed_extra' => $option_cart_item['_wiaas_payment']['fixed_extra'],
'recurrent_extra' => $option_cart_item['_wiaas_payment']['recurrent_extra'],
'services_extra' => $option_cart_item['_wiaas_payment']['services_extra'],
)
);
},
wiaas_get_cart_item_options($item));
$package_items[] = array(
'package_id' => $item['product_id'],
'key' => $item['key'],
'package_name' => $package->get_title(),
'quantity' => $item['quantity'],
'commercial_lead_id' => 14,
'commercial_lead' => 'Coor Service Management',
'country' => Wiaas_Countries::get_package_country($package),
'are_additional_available' => true,
'additional_packages' => $additional_packages,
'are_options_available' => true,
'options' => $package_options,
'bids' => array(),
'payment_info' => array(
'id' => $item['_wiaas_payment']['id'],
'type' => $item['_wiaas_payment']['payment_type'],
'period_unit' => $item['_wiaas_payment']['period_unit'],
'fixed_extra' => $item['_wiaas_payment']['fixed_extra'],
'recurrent_extra' => $item['_wiaas_payment']['recurrent_extra'],
'services_extra' => $item['_wiaas_payment']['services_extra'],
),
'total_prices' => Wiaas_Cart::get_cart_item_total($item),
'status' => 'available',
);
}
return $package_items;
}
//PRIVATE
/**
* Add selected package options to cart
* @param $cart_item_key
* @param $package_id
* @param $cart_item_data
*
* @throws Exception
* Retrieve cart templates
* @return array
*/
private static function _add_options_to_cart($cart_item_key, $package_id, $cart_item_data) {
$is_option_parent = $_POST['package_id'] = $package_id && isset($cart_item_data['_wiaas_option_items']);
$has_selected_options = isset($_POST['options']) && is_array($_POST['options']);
private static function _get_cart_templates() {
$items = WC()->cart->get_cart_contents();
if ($is_option_parent && $has_selected_options) {
$documents_ids = array();
$options_ids = $_POST['options'];
foreach ($items as $key => $item) {
if (!isset($item['_wiaas_standard_package'])) {
continue;
}
foreach ($options_ids as $option_id) {
$option_package = wc_get_product($option_id);
if (is_object($option_package)) {
$package_documents_ids = get_post_meta(
$item['product_id'],
'_wiaas_attached_documents',
true);
$option_cart_item_key = WC()->cart->add_to_cart($option_id, 1, 0, array(), array(
'_wiaas_option_for' => $cart_item_key
));
if ($option_cart_item_key) {
WC()->cart->cart_contents[ $cart_item_key ]['_wiaas_option_items'][] = $option_cart_item_key;
}
}
foreach ($package_documents_ids as $package_document_id) {
$package_document_id = absint($package_document_id);
$documents_ids[$package_document_id] ?: array();
$documents_ids[$package_document_id][] = $item['product_id'];
}
}
$q = new WP_Query();
$retrieved_items = $q->query(array(
'post_status' => 'publish',
'post_type' => 'wiaas_doc',
'post__in' => array_keys($documents_ids),
'tax_query' => array(
array(
'taxonomy' => 'wiaas_doc_type',
'field' => 'slug',
'terms' => array_keys(self::$cart_doc_types),
)
)
));
$cart_documents = array();
foreach ($retrieved_items as $retrieved_item) {
$doc_info = Wiaas_Document::get_doc_info($retrieved_item->ID);
$type = $doc_info['type']['id'];
$cart_documents[$type] ?: array();
$package_ids = $documents_ids[$doc_info['id']] ?: array();
foreach ($package_ids as $package_id) {
$cart_documents[$type][$package_id] = array(
'id' => $doc_info['id'],
'name' => $doc_info['name'],
'type' => $type,
'extension' => $doc_info['extension']
);
}
}
return $cart_documents;
}
/**
* Add selected package addons to cart
*
* @param $cart_item_key
* @param $package_id
* @param $cart_item_data
*
* @throws Exception
* Retrieve cart uploaded documents
* @return array
*/
private static function _add_addons_to_cart($cart_item_key, $package_id, $cart_item_data) {
private static function _get_cart_uploaded_documents() {
$items = WC()->cart->get_cart_contents();
$is_addon_parent = $_POST['package_id'] = $package_id && isset($cart_item_data['_wiaas_addon_items']);
$has_selected_addons = isset($_POST['addons']) && is_array($_POST['addons']);
$cart_documents = array();
if ($is_addon_parent && $has_selected_addons) {
$addons_ids = $_POST['addons'];
foreach ($items as $key => $item) {
if (!isset($item['_wiaas_standard_package'])) {
continue;
}
foreach ($addons_ids as $addon_id) {
$addon_package = wc_get_product($addon_id);
if (is_object($addon_package)) {
$package_id = $item['product_id'];
$addon_cart_item_key = WC()->cart->add_to_cart($addon_id, 1, 0, array(), array(
'_wiaas_addon_for' => $cart_item_key
));
$documents = isset($item['_wiaas_documents']) ? $item['_wiaas_documents'] : array();
if ($addon_cart_item_key) {
WC()->cart->cart_contents[ $cart_item_key ]['_wiaas_addon_items'][] = $addon_cart_item_key;
}
}
foreach ($documents as $type => $document) {
$cart_documents[$type] ?: array();
$cart_documents[$type][$package_id] = array(
'key' => $document['key'],
'name' => wiaas_get_doc_version_filename($document['version']),
'type' => $type,
'extension' => wiaas_get_doc_version_extension($document['version'])
);
}
}
return $cart_documents;
}
/**
* Add selected package options and addons after parent standard package is added to cart
*
* @param string $package_cart_item_key
* @param int $price_id
* @param array $addons_ids
* @param array $options_ids
*
* @throws Exception if any of the addons or options cannot be added to cart
*/
private static function _add_additional_packages_to_cart($package_cart_item_key, $price_id, $addons_ids, $options_ids) {
$parent_item = WC()->cart->get_cart_item($package_cart_item_key);
$addon_items_keys = array();
$option_items_keys = array();
// TODO: Change this so commercial lead is sent via request
$customer_id = wiaas_get_current_user_organization_id();
$commercial_lead_id = array_keys(wiaas_get_commercial_leads())[0];
// Try adding package addons to cart
foreach ($addons_ids as $addon_id) {
//Check if addon package exists
$addon_package = wc_get_product($addon_id);
if (!$addon_package) {
throw new Exception( __( 'Sorry, additional package does not exist.', 'wiaas' ) );
}
// Retrieve addon package price
$package_prices = Wiaas_Pricing::get_addon_package_customer_price(
$addon_package,
$parent_item['data'],
$customer_id,
$commercial_lead_id
);
$selected_price_index = array_search($price_id, array_column($package_prices, 'id'));
// Initialize additional cart item data for wiaas addon packages
$wiaas_addon_cart_item_data = array(
'_wiaas_addon_for' => $package_cart_item_key,
'_wiaas_payment' => $package_prices[$selected_price_index] ? $package_prices[$selected_price_index] : null
);
$addon_cart_item_key = WC()->cart->add_to_cart($addon_id,
1,
0,
array(),
$wiaas_addon_cart_item_data
);
if (!$addon_cart_item_key) {
throw new Exception( __( 'Sorry, additional package could not be added to cart.', 'wiaas' ) );
}
$addon_items_keys[] = $addon_cart_item_key;
}
// Try adding package options to cart
foreach ($options_ids as $option_id) {
//Check if option package exists
$option_package = wc_get_product($option_id);
if (!$option_package) {
throw new Exception( __( 'Sorry, option package does not exist.', 'wiaas' ) );
}
// Retrieve option package price
$package_prices = Wiaas_Pricing::get_option_package_customer_price(
$option_package,
$parent_item['data'],
$customer_id,
$commercial_lead_id);
$selected_price_index = array_search($price_id, array_column($package_prices, 'id'));
// Retrieve option package group name
$option_group_name = Wiaas_Package_Option_Groups::get_group_name_for_package_option($parent_item['data'], $option_package);
// Initialize additional cart item data for wiaas option packages
$wiaas_option_cart_item_data = array(
'_wiaas_option_for' => $package_cart_item_key,
'_wiaas_payment' => $package_prices[$selected_price_index] ? $package_prices[$selected_price_index] : null,
'_wiaas_option_group_name' => $option_group_name,
);
$option_cart_item_key = WC()->cart->add_to_cart($option_id,
1,
0,
array(),
$wiaas_option_cart_item_data
);
if (!$option_cart_item_key) {
throw new Exception( __( 'Sorry, package option could not be added to cart.', 'wiaas' ) );
}
$option_items_keys[] = $option_cart_item_key;
}
WC()->cart->cart_contents[ $package_cart_item_key ]['_wiaas_addon_items'] = $addon_items_keys;
WC()->cart->cart_contents[ $package_cart_item_key ]['_wiaas_option_items'] = $option_items_keys;
}
/**
* Check if package is added to cart
* @param int $package_id
*
* @return bool
*/
private static function _is_package_in_cart($package_id) {
$cart_item = WC()->cart->get_cart_contents();
foreach ($cart_item as $item) {
if($item['product_id'] === $package_id) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,108 @@
<?php
class Wiaas_Checkout {
public static function init(){
add_action( 'woocommerce_check_cart_items', array(__CLASS__, 'validate_wiaas_packages'));
}
public static function validate_wiaas_packages(){
//check if any package became invalid
$items = WC()->cart->get_cart();
foreach($items as $item) {
$item_id = $item['data']->get_id();
if (wc_pb_is_bundle_container_cart_item($item) &&
(Wiaas_Package_Status::get_package_status($item_id) !== Wiaas_Package_Status::AVAILABLE)){
wc_add_notice( 'Package ' . $item['data']->get_title() . ' cannot be purchased at the moment', 'error' );
return false;
}
}
}
/**
* Process the order checkout.
*
* @param array $data Posted data.
*
* @return bool
*/
public static function process_checkout($data) {
try {
wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
wc_set_time_limit( 0 );
do_action( 'woocommerce_before_checkout_process' );
// Check if cart empty before proceeding
if (WC()->cart->is_empty()) {
return false;
}
do_action( 'woocommerce_checkout_process' );
// Validate cart items before proceeding
WC()->checkout()->check_cart_items();
// if something is wrong bail out
if(wc_notice_count( 'error' ) > 0) {
return false;
}
// try processing order
$order_id = WC()->checkout()->create_order($data);
$order = wc_get_order( $order_id );
if ( is_wp_error( $order_id ) ) {
throw new Exception( $order_id->get_error_message() );
}
if ( ! $order ) {
throw new Exception( __( 'Unable to create order.', 'woocommerce' ) );
}
self::_add_wiaas_checkout_data($order, $data);
do_action( 'woocommerce_checkout_order_processed', $order_id, array(), $order );
$order->payment_complete();
WC()->cart->empty_cart( true );
return true;
} catch (Exception $e) {
wc_add_notice( $e->getMessage(), 'error' );
return false;
}
}
/**
* Add additional wiaas checkout info for order
* @param $order
* @param array $data
*/
private static function _add_wiaas_checkout_data($order, $data) {
// save currency
$line_items = $order->get_items();
foreach ($line_items as $line_item) {
if (isset($line_item['wiaas_currency'])) {
$order->set_currency($line_item['wiaas_currency']);
break;
}
}
// save additional wiaas order info
Wiaas_Order::set_order_vat($order->get_id(), $data['vat']);
Wiaas_Order::set_order_company($order->get_id(), $data['company_name']);
Wiaas_Order::set_order_reference($order->get_id(), $data['reference']);
Wiaas_Order::set_order_tender($order->get_id(), $data['tender']);
// add order to project
if (isset($data['project_id'])) {
Wiaas_Order_Project::set_project_for_order($order->get_id(), $data['project_id']);
}
}
}
Wiaas_Checkout::init();

View File

@@ -17,18 +17,21 @@ class Wiaas_Countries {
*/
private static $available_countries = array(
'Sweden' => array(
'id' => 1,
'name' => 'Sweden',
'code' => 'se',
'vat' => 9 ,
'currency' => 'SEK'
),
'Denmark' => array(
'id' => 2,
'name' => 'Denmark',
'code' => 'dk',
'vat' => 9 ,
'currency' => 'DKK'
),
'Finland' => array(
'id' => 3,
'name' => 'Finland',
'code' => 'fi',
'vat' => 9 ,
@@ -41,6 +44,24 @@ class Wiaas_Countries {
add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_product_countries_taxonomy'));
}
public static function get_list_of_countries(){
$result = [];
foreach(self::$available_countries as $country){
array_push($result, array(
'country_id' => $country['id'],
'country_name' => $country['name']
));
}
return $result;
}
public static function get_country_name_by_id($id){
foreach(self::$available_countries as $country){
if ($country['id'] == $id) return $country['name'];
}
return '';
}
/**
* Registers product taxonomy for avaiable countries
*/

View File

@@ -8,12 +8,19 @@ class Wiaas_DB_Update {
'20180728222206' => 'wiaas_db_update_enable_product_by_user_role',
'20180801222206' => 'wiaas_db_update_setup_gravity',
'20180802222206' => 'wiaas_db_update_add_delivery_process_forms',
'20180807222206' => 'wiaas_db_update_setup_customer_capabilities',
'20180811134511' => 'wiaas_db_update_enable_orders_access_management',
'20180813134511' => 'wiaas_db_update_enable_order_numbers',
'20180826153509' => 'wiaas_create_broker_access_group',
'20180911101010' => 'wiaas_db_setup_exclusive_taxonomies',
'20180912101010' => 'wiaas_db_setup_default_cl'
'20181003164100' => 'wiaas_db_setup_customer_capabilities',
'201810111644700' => 'wiaas_db_update_add_organization_info_ui_fields',
'201810121644700' => 'wiaas_db_update_add_user_organization_ui_fields',
'201810171645700' => 'wiaas_db_update_create_default_roles',
'201810171745700' => 'wiaas_db_import_aam_role_settings',
'201810173045700' => 'wiaas_db_update_update_commercial_lead_capabilities',
'201810173145700' => 'wiaas_db_update_update_supplier_capabilities',
'201810173245700' => 'wiaas_db_update_update_admin_capabilities',
'201810173345700' => 'wiaas_create_role_access_groups'
);
public static function execute() {

View File

@@ -5,98 +5,21 @@ if ( ! defined( 'ABSPATH' ) ) {
}
/**
* Implements Wiaas Document types
* Implements Wiaas Documents
*
* Class Wiaas_Documents
*/
class Wiaas_Documents {
/**
* Default available document types for wiaas
* @var array
*/
private static $available_doc_types = array(
'template_questionaire' => array(
'name' => 'Template Questionaire',
'is_special_type' => false,
),
'order_questionaire' => array(
'name' => 'Order Questionaire',
'is_special_type' => true,
),
'configuration' => array(
'name' => 'Configuration',
'is_special_type' => true,
),
'install_guide' => array(
'name' => 'Install guide',
'is_special_type' => false,
),
'customer_acceptance' => array(
'name' => 'Customer acceptance',
'is_special_type' => true,
),
'template_agreement' => array(
'name' => 'Template Agreement',
'is_special_type' => false,
),
'order_agreement' => array(
'name' => 'Order Agreement',
'is_special_type' => true,
),
'installation_protocol' => array(
'name' => 'Installation protocol',
'is_special_type' => true,
),
'statements' => array(
'name' => 'Statements',
'is_special_type' => false,
),
'customer_acceptance_template' => array(
'name' => 'Customer acceptance template',
'is_special_type' => false,
),
);
public static function init() {
add_action( 'init', array( __CLASS__, 'register_wiaas_document_types' ));
}
/**
* Registers taxonomy and default values for wiaas document types
*/
public static function register_wiaas_document_types() {
$labels = array(
'name' => _x( 'Document type', 'taxonomy general name', 'wiaas' ),
'singular_name' => _x( 'Document type', 'taxonomy singular name', 'wiaas' ),
'menu_name' => _x( 'Document types', 'Admin menu name', 'wiaas' ),
'search_items' => __( 'Search Document types', 'wiaas' ),
'all_items' => __( 'All Document types', 'wiaas' ),
'parent_item' => __( 'Parent Document type', 'wiaas' ),
'parent_item_colon' => __( 'Parent Document type:', 'wiaas' ),
'edit_item' => __( 'Edit Document type', 'wiaas' ),
'update_item' => __( 'Update Document type', 'wiaas' ),
'add_new_item' => __( 'Add New Document type', 'wiaas' ),
'new_item_name' => __( 'New Document type Name', 'wiaas' ),
);
require_once dirname( __FILE__ ) . '/document/class-wiaas-document.php';
$args = array(
'hierarchical' => false,
'label' => __( 'Document types', 'wiaas' ),
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wiaas_document_types' ),
);
require_once dirname( __FILE__ ) . '/document/class-wiaas-document-upload.php';
register_taxonomy( 'wiaas_document_types', array( 'attachment' ), $args );
require_once dirname( __FILE__ ) . '/document/class-wiaas-document-download.php';
foreach (self::$available_doc_types as $key => $available_doc_type) {
wp_insert_term($available_doc_type['name'], 'wiaas_document_types', array(
'slug' => $key
));
}
require_once dirname( __FILE__ ) . '/document/wiaas-document-functions.php';
}
}

View File

@@ -16,6 +16,9 @@ class Wiaas_Order {
private static $object_order_type = 'shop_order';
public static function init() {
require_once dirname( __FILE__ ) . '/order/class-wiaas-order-project.php';
add_action('woocommerce_new_order', array( __CLASS__, 'assign_order_to_organization' ));
add_filter('woocommerce_rest_check_permissions', array( __CLASS__, 'check_order_access'), 10, 4);
@@ -115,6 +118,8 @@ class Wiaas_Order {
$data = self::_append_order_process($data, $order, $request);
$data = self::_append_order_comments($data, $order, $request);
$data = self::_append_documents($data, $order, $request);
}
$response->set_data($data);
@@ -122,6 +127,38 @@ class Wiaas_Order {
return $response;
}
public static function set_order_vat($order_id, $vat_code) {
add_post_meta($order_id, '_wiaas_vat_code', $vat_code);
}
public static function get_order_vat($order_id) {
return get_post_meta($order_id, '_wiaas_vat_code', true);
}
public static function set_order_company($order_id, $company_name) {
add_post_meta($order_id, '_wiaas_company_name', $company_name);
}
public static function get_order_company($order_id) {
return get_post_meta($order_id, '_wiaas_company_name', true);
}
public static function set_order_reference($order_id, $reference) {
add_post_meta($order_id, '_wiaas_reference', $reference);
}
public static function get_order_reference($order_id) {
return get_post_meta($order_id, '_wiaas_reference', true);
}
public static function set_order_tender($order_id, $tender) {
add_post_meta($order_id, '_wiaas_tender', $tender);
}
public static function get_order_tender($order_id) {
return get_post_meta($order_id, '_wiaas_tender', true);
}
/**
* PRIVATE
*/
@@ -133,7 +170,12 @@ class Wiaas_Order {
* @param $request
*/
private static function _append_wiaas_order_details($data, $order, $request) {
$data['reference'] = get_post_meta($order->get_id(), '_wiaas_reference', true);
$data['reference'] = self::get_order_reference($order->get_id());
$data['tender'] = self::get_order_tender($order->get_id());
$data['vat'] = self::get_order_vat($order->get_id());
$data['company_name'] = self::get_order_company($order->get_id());
$data['project_name'] = Wiaas_Order_Project::get_project_name_for_order($order->get_id());
return $data;
}
@@ -202,7 +244,6 @@ class Wiaas_Order {
// add only product lines that represent product bundles
if (isset($item['wiaas_standard_package'])) {
# get payment type info
$product_line['payment_type'] = $item['wiaas_payment_type'];
$product_line['service_price'] = floatval($item['wiaas_services_extra']);
@@ -311,6 +352,27 @@ class Wiaas_Order {
}
}
return $data;
}
/** Append downloadable documents from order products if single order is requested
* @param $data
* @param $order
* @param $request
*/
private static function _append_documents($data, $order, $request) {
// Go trough available line items and append documents for wiaas standard packages line items
foreach ($data['line_items'] as $index => $product_line) {
$order_item = $order->get_item($product_line['id']);
if (wiaas_is_order_item__standard_package($order_item)) {
$documents = wiaas_get_standard_package_order_item_documents($order, $product_line['id']);
$data['line_items'][$index] ['documents'] = $documents;
}
}
return $data;
}
}

View File

@@ -12,6 +12,7 @@ class Wiaas_Package {
require_once dirname( __FILE__ ) . '/package/class-wiaas-package-option-groups.php';
require_once dirname( __FILE__ ) . '/package/class-wiaas-package-type.php';
require_once dirname( __FILE__ ) . '/package/class-wiaas-package-status.php';
require_once dirname( __FILE__ ) . '/package/wiaas-package-functions.php';
@@ -54,15 +55,11 @@ class Wiaas_Package {
*/
private static function _append_documents_info($data, $package, $request) {
unset($data['downloads']);
$data['documents'] = array_map(function($download) {
return array(
'id' => $download->get_id(),
'name' => $download->get_name(),
'extension' => $download->get_file_extension(),
);
}, array_values($package->get_downloads()));
$data['documents'] = array_map(function($doc) {
unset($doc['url']);
unset($doc['version']);
return $doc;
}, wiaas_get_standard_package_documents($package, true));
return $data;
}
@@ -96,6 +93,9 @@ class Wiaas_Package {
* @return array
*/
private static function _append_additional_packages($data, $package, $request) {
// TODO: Change this so commercial lead is sent via request
$customer_id = wiaas_get_current_user_organization_id();
$commercial_lead_id = array_keys(wiaas_get_commercial_leads())[0];
$data['additional_packages'] = array();
$addons = Wiaas_Package_Addon::get_package_addons($package);
@@ -104,7 +104,7 @@ class Wiaas_Package {
'id' => $addon->get_id(),
'name' => $addon->get_name(),
'description' => $addon->get_description(),
'prices' => Wiaas_Pricing::get_addon_package_customer_price($addon, $package),
'prices' => Wiaas_Pricing::get_addon_package_customer_price($addon, $package, $customer_id, $commercial_lead_id),
);
}
@@ -125,7 +125,7 @@ class Wiaas_Package {
'name' => $option_package->get_name(),
'description' => $option_package->get_description(),
'default' => $default_option_id === $option_package->get_id(),
'prices' => Wiaas_Pricing::get_option_package_customer_price($option_package, $package),
'prices' => Wiaas_Pricing::get_option_package_customer_price($option_package, $package, $customer_id, $commercial_lead_id),
);
}
}
@@ -142,7 +142,11 @@ class Wiaas_Package {
* @return array
*/
private static function _append_package_prices($data, $package, $request) {
$data['prices'] = Wiaas_Pricing::get_standard_package_customer_prices($package);
// TODO: Change this so commercial lead is sent via request
$customer_id = wiaas_get_current_user_organization_id();
$commercial_lead_id = array_keys(wiaas_get_commercial_leads())[0];
$data['prices'] = Wiaas_Pricing::get_standard_package_customer_prices($package, $customer_id, $commercial_lead_id);
return $data;
}

View File

@@ -1,7 +1,7 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
exit; // Exit if accessed directly
}
/**
@@ -9,233 +9,240 @@ if ( ! defined( 'ABSPATH' ) ) {
*/
class Wiaas_Pricing {
/**
* Wiaas interest rate
*/
const INTEREST_RATE = 0.58;
/**
* Wiaas interest rate
*/
const INTEREST_RATE = 0.58;
const COMMERCIAL_LEAD_NAME = 'Coor Service Management';
public static function init() {
require_once dirname( __FILE__ ) . '/pricing/class-wiaas-product-pricing.php';
require_once dirname( __FILE__ ) . '/pricing/class-wiaas-package-pricing.php';
require_once dirname( __FILE__ ) . '/pricing/class-wiaas-package-cl-pricing.php';
require_once dirname( __FILE__ ) . '/pricing/wiaas-pricing-functions.php';
}
public static function init() {
require_once dirname( __FILE__ ) . '/pricing/class-wiaas-product-pricing.php';
require_once dirname( __FILE__ ) . '/pricing/class-wiaas-package-pricing.php';
require_once dirname( __FILE__ ) . '/pricing/wiaas-pricing-functions.php';
}
/**
* Calculates total cost for product
* @param WC_Product_Simple $product
*
* @return float
*/
public static function get_product_total_cost($product) {
$product_price = Wiaas_Product_Pricing::get_product_price($product);
/**
* Calculates total cost for product
* @param $product
*
* @return float
*/
public static function get_product_total_cost($product) {
$product_price = Wiaas_Product_Pricing::get_product_price($product);
return $product_price['is_recurring'] ?
$product_price['price'] * $product_price['pay_period'] :
$product_price['price'];
}
return $product_price['is_recurring'] ?
$product_price['price'] * $product_price['pay_period'] :
$product_price['price'];
}
/**
* Calculates total cost for package
* @param WC_Product_Bundle $package
*
* @return float
*/
public static function get_package_total_cost($package) {
/**
* Calculates total cost for package
* @param $package
*
* @return float
*/
public static function get_package_total_cost($package) {
$total_cost_per_category = array();
$total_cost_per_category = array();
$bundled_items = $package->get_bundled_items();
foreach ($bundled_items as $bundled_item) {
$bundled_items = $package->get_bundled_items();
foreach ($bundled_items as $bundled_item) {
$product = $bundled_item->product;
$product_cat = Wiaas_Product_Category::get_category($product);
$product = $bundled_item->product;
$product_cat = Wiaas_Product_Category::get_category($product);
if (!isset($total_cost_per_category[$product_cat])) {
$total_cost_per_category[$product_cat] = 0;
}
if (!isset($total_cost_per_category[$product_cat])) {
$total_cost_per_category[$product_cat] = 0;
}
$total_item_cost = self::get_product_total_cost($product) * $bundled_item->get_quantity();
$total_item_cost = self::get_product_total_cost($product) * $bundled_item->get_quantity();
if (Wiaas_Product_Category::is_installation($product)) {
$total_cost_per_category[$product_cat] = $total_cost_per_category[$product_cat] < $total_item_cost ?
$total_item_cost :
$total_cost_per_category[$product_cat];
} else {
$total_cost_per_category[$product_cat] += $total_item_cost;
}
}
if (Wiaas_Product_Category::is_installation($product)) {
$total_cost_per_category[$product_cat] += $total_cost_per_category[$product_cat] < $total_item_cost ?
$total_item_cost :
$total_cost_per_category[$product_cat];
} else {
$total_cost_per_category[$product_cat] += $total_item_cost;
}
}
return array_sum(array_values($total_cost_per_category));
}
return array_sum(array_values($total_cost_per_category));
}
/**
* Calculates customer prices for wiaas standard package
* @param WC_Product_Bundle $package
* @param int $customer_id
* @param int $commercial_lead_id
*
* @return array
*/
public static function get_standard_package_customer_prices($package, $customer_id, $commercial_lead_id) {
/**
* Calculates customer price for wiaas standard package
* @param $package
*
* @return array
*/
public static function get_standard_package_customer_prices($package) {
return self::_get_package_customer_prices(
$package,
(100 - Wiaas_Package_Pricing::get_package_pricing_commission($package)) / 100, // commercial lead commission
self::get_package_total_cost($package), // total cost of package items
$customer_id,
$commercial_lead_id);
$is_same_company_as_cl = self::_is_customer_same_company_as_cl();
$package_prices = Wiaas_Package_Pricing::get_package_prices($package);
$cl_commision = (100 - Wiaas_Package_Pricing::get_package_pricing_commission($package)) / 100;
$total_cost = self::get_package_total_cost($package);
}
$customer_package_prices = array();
/**
* Calculates customer prices for wiaas addon package
*
* @param WC_Product_Bundle $addon_package
* @param WC_Product_Bundle $parent_package
* @param int $customer_id
* @param int $commercial_lead_id
*
* @return array
*/
public static function get_addon_package_customer_price($addon_package, $parent_package, $customer_id, $commercial_lead_id) {
foreach ($package_prices as $type => $package_price) {
$customer_package_prices[] = self::_get_package_customer_price(
$package_price,
$cl_commision,
$total_cost,
$is_same_company_as_cl);
}
$parent_total_cost = self::get_package_total_cost($parent_package);
$parent_cl_commision = (100 - Wiaas_Package_Pricing::get_package_pricing_commission($parent_package)) / 100;
return $customer_package_prices;
return self::_get_package_customer_prices(
$addon_package,
$parent_cl_commision, // commercial lead commission of parent package
$parent_total_cost, // total cost of parent package items
$customer_id,
$commercial_lead_id);
}
}
/**
* Calculates customer prices for wiaas option package
*
* @param WC_Product_Bundle $option_package
* @param WC_Product_Bundle $parent_package
* @param int $customer_id
* @param int $commercial_lead_id
*
* @return array
*/
public static function get_option_package_customer_price($option_package, $parent_package, $customer_id, $commercial_lead_id) {
/**
* Calculates customer price for wiaas addon package
* @param $addon_package
* @param $parent_package
*
* @return array
*/
public static function get_addon_package_customer_price($addon_package, $parent_package) {
$parent_total_cost = self::get_package_total_cost($parent_package);
$parent_cl_commision = (100 - Wiaas_Package_Pricing::get_package_pricing_commission($parent_package)) / 100;
$is_same_company_as_cl = self::_is_customer_same_company_as_cl();
$parent_total_cost = self::get_package_total_cost($parent_package);
$parent_cl_commision = (100 - Wiaas_Package_Pricing::get_package_pricing_commission($parent_package)) / 100;
$addon_package_prices = Wiaas_Package_Pricing::get_package_prices($addon_package);
return self::_get_package_customer_prices(
$option_package,
$parent_cl_commision, // commercial lead commission of parent package
$parent_total_cost, // total cost of parent package items
$customer_id,
$commercial_lead_id);
}
$customer_package_prices = array();
foreach ($addon_package_prices as $type => $addon_package_price) {
$customer_package_prices[] = self::_get_package_customer_price(
$addon_package_price,
$parent_cl_commision,
$parent_total_cost,
$is_same_company_as_cl);
}
return $customer_package_prices;
}
/**
* Calculates customer price for wiaas option package
* @param $option_package
* @param $parent_package
*
* @return array
*/
public static function get_option_package_customer_price($option_package, $parent_package) {
// PRIVATE SECTION
$is_same_company_as_cl = self::_is_customer_same_company_as_cl();
$parent_total_cost = self::get_package_total_cost($parent_package);
$parent_cl_commision = (100 - Wiaas_Package_Pricing::get_package_pricing_commission($parent_package)) / 100;
$option_package_prices = Wiaas_Package_Pricing::get_package_prices($option_package);
$customer_package_prices = array();
/**
* Calculates customer prices for all package payment types
*
* @param WC_Product_Bundle $package
* @param int $cl_commision
* @param int $total_cost
* @param int $customer_id
* @param int $commercial_lead_id
*
* @return array
*/
private static function _get_package_customer_prices($package, $cl_commision, $total_cost, $customer_id, $commercial_lead_id) {
$is_same_company_as_cl = $customer_id === $commercial_lead_id;
foreach ($option_package_prices as $type => $option_package_price) {
$customer_package_prices[] = self::_get_package_customer_price(
$option_package_price,
$parent_cl_commision,
$parent_total_cost,
$is_same_company_as_cl);
}
$package_prices = Wiaas_Package_Pricing::get_package_prices($package);
return $customer_package_prices;
}
$customer_package_prices = array();
// PRIVATE
foreach ($package_prices as $type => $package_price) {
$cl_package_extras = Wiaas_Package_CL_Pricing::get_extras_for_customer(
$commercial_lead_id,
$package_price['id'],
$package->get_id(),
$customer_id
);
/**
* Determines if customer and commercial lead are in the same company
* For now this is hardcoded and we have only one CL
*
* TODO: This should be changed after customer leads are handled
* @return bool
*/
private static function _is_customer_same_company_as_cl() {
$current_user = wp_get_current_user();
$user_organization = Wiaas_User_Organization::get_user_organization($current_user->ID);
$is_same_company_as_cl = $user_organization->name === self::COMMERCIAL_LEAD_NAME;
// commercial lead did not set prices for this payment type so it must not be visible for customer
if (empty($cl_package_extras)) {
continue;
}
return $is_same_company_as_cl;
}
$customer_package_prices[] = self::_get_package_customer_price(
$package_price,
$total_cost,
$cl_package_extras,
$cl_commision,
$is_same_company_as_cl);
}
/**
* Calculates customer price for wiaas package
* @param $package_price
* @param $cl_commision
* @param $total_cost
* @param $is_same_company_as_cl
*
* @return array
*/
private static function _get_package_customer_price($package_price, $cl_commision, $total_cost, $is_same_company_as_cl) {
return $customer_package_prices;
}
$package_total_margin = wiaas_get_price_margin(
$package_price['minimal_fixed_price'],
$package_price['principal_amount'],
$total_cost);
$cl_margin = $package_total_margin > 0 ? $package_total_margin * $cl_commision : 0;
/**
* Calculates customer price for single package payment type
*
* @param array $package_price
* @param int $total_cost
* @param array $cl_package_extras
* @param int $cl_commision
* @param bool $is_same_company_as_cl
*
* @return array
*/
private static function _get_package_customer_price($package_price, $total_cost, $cl_package_extras, $cl_commision, $is_same_company_as_cl) {
$package_total_margin = wiaas_get_price_margin(
$package_price['minimal_fixed_price'],
$package_price['principal_amount'],
$total_cost);
$cl_margin = $package_total_margin > 0 ? $package_total_margin * $cl_commision : 0;
$cl_package_prices = array(
'fixed_extra' => 0,
'recurrent_extra' => 0,
'services_extra' => 0
);
$customer_package_price = array(
'id' => $package_price['id'],
'payment_type' => $package_price['payment_type'],
'max_contract_period' => $package_price['max_contract_period'],
'package_pay_period' => $package_price['package_pay_period'],
'period_unit' => $package_price['period_unit'],
'services_contract_period' => $package_price['services_contract_period'],
$interest_rate = self::INTEREST_RATE;
'fixed_extra' => 0,
'recurrent_extra' => 0,
'services_extra' => 0
);
$customer_price = array(
'id' => $package_price['id'],
'payment_type' => $package_price['payment_type'],
'max_contract_period' => $package_price['max_contract_period'],
'package_pay_period' => $package_price['package_pay_period'],
'period_unit' => $package_price['period_unit'],
'services_contract_period' => $package_price['services_contract_period'],
if ($is_same_company_as_cl) {
'fixed_extra' => 0,
'recurrent_extra' => 0,
'services_extra' => 0
);
if ($package_price['package_pay_period'] > 0) {
$customer_package_price['fixed_extra'] = $package_price['minimal_fixed_price'];
$customer_package_price['recurrent_extra'] = wiaas_get_recurrent_price_mortage(
$package_price['principal_amount'],
$package_price['package_pay_period'],
$cl_margin,
self::INTEREST_RATE);
} else {
$customer_package_price['fixed_extra'] = $package_price['minimal_fixed_price'] - $cl_margin;
$customer_package_price['recurrent_extra'] = 0;
}
$customer_package_price['services_extra'] = $package_price['minimal_services_price'];
if ($is_same_company_as_cl) {
} else {
if ($package_price['package_pay_period'] > 0) {
$customer_price['fixed_extra'] = $package_price['minimal_fixed_price'];
$customer_price['recurrent_extra'] = wiaas_get_recurrent_price_mortage(
$package_price['principal_amount'],
$package_price['package_pay_period'],
$cl_margin,
$interest_rate);
} else {
$customer_price['fixed_extra'] = $package_price['minimal_fixed_price'] - $cl_margin;
$customer_price['recurrent_extra'] = 0;
}
$customer_price['services_extra'] = $package_price['minimal_services_price'];
$customer_package_price['fixed_extra'] = $cl_package_extras['fixed'] + $package_price['minimal_fixed_price'];
$customer_package_price['recurrent_extra'] = $package_price['package_pay_period'] > 0 ?
$cl_package_extras['recurrent'] + wiaas_get_recurrent_price_mortage(
$package_price['principal_amount'],
$package_price['package_pay_period'],
0,
self::INTEREST_RATE)
: 0;
$customer_package_price['services_extra'] = $cl_package_extras['services'] + $package_price['minimal_services_price'];
}
} else {
$customer_price['fixed_extra'] = $cl_package_prices['fixed_extra'] + $package_price['minimal_fixed_price'];
$customer_price['recurrent_extra'] = $package_price['package_pay_period'] > 0 ?
$cl_package_prices['recurrent_extra'] + wiaas_get_recurrent_price_mortage(
$package_price['principal_amount'],
$package_price['package_pay_period'],
0,
$interest_rate)
: 0;
$customer_price['services_extra'] = $cl_package_prices['services_extra'] + $package_price['minimal_services_price'];
}
return $customer_price;
}
return $customer_package_price;
}
}
Wiaas_Pricing::init();

View File

@@ -4,6 +4,31 @@ class Wiaas_Product {
public static function init() {
require_once dirname( __FILE__ ) . '/product/class-wiaas-product-category.php';
require_once dirname( __FILE__ ) . '/product/class-wiaas-product-supplier.php';
add_filter('woocommerce_register_post_type_product', array(__CLASS__, 'define_product_capabilities'));
}
/**
* Define capabilities for editing products so we can easily control read/edit/create access for them
*
* @param $args
*
* @return mixed
*/
public static function define_product_capabilities($args) {
$args['capabilities'] = array(
'edit_post' => 'edit_product',
'read_post' => 'read_product',
'delete_post' => 'delete_product',
'edit_posts' => 'edit_products',
'edit_others_posts' => 'edit_others_products',
'publish_posts' => 'publish_products',
'read_private_posts' => 'read_private_products',
'create_posts' => 'create_products', // use `create_products` instead of default `edit_products`
);
return $args;
}
}

View File

@@ -0,0 +1,75 @@
<?php
class Wiaas_Shop {
public static function init() {
// registers special prices taxonomy that will enable package search based on
// set and visible price types (default and customer specific ones)
add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_prices_taxonomy'));
// update prices search terms for package after prices extras have been updated
add_action('wiaas_package_prices_extras_set', array(__CLASS__, 'update_package_prices_search_terms'), 10, 4);
}
/**
* Register special prices taxonomy to enable search of packages by prices inside every shop
*/
public static function register_prices_taxonomy() {
$args = array(
'hierarchical' => false,
'query_var' => true,
'rewrite' => false,
'public' => true,
'capabilities' => array(
'manage_terms' => 'manage_wiaas_package_price_terms',
'edit_terms' => 'edit_wiaas_package_price_terms',
'delete_terms' => 'delete_wiaas_package_price_terms',
'assign_terms' => 'assign_wiaas_package_price_terms',
),
);
register_taxonomy( '_wiaas_shop_prices', array( 'product' ), $args );
}
/**
* Relate pricing search terms to package so customer can retrieve packages with default or
* their own specific prices.
* (ex: Package which will be hidden fro Customer 1 because default price
* is hidden can be visible for Customer 2 because specific prices are set for that customer)
*
* @param int $owner_id
* @param int $package_id
* @param array $cl_extras {
* $extra_price_payment_type => {
* @type bool visible Indicates if payment type is visible to customer
* }
* }
* @param array $old_cl_extras {
* $extra_price_payment_type => {
* @type bool visible Indicates if payment type is visible to customer
* }
* }
*/
public static function update_package_prices_search_terms($owner_id, $package_id, $cl_extras, $old_cl_extras) {
// remove pricing terms for previous prices
if (! empty($old_cl_extras)) {
$old_visible_price_types = array_keys(wp_list_filter($old_cl_extras, array( 'visible' => true )));
$old_terms_names = preg_filter('/^/', '_' . $owner_id . '_', $old_visible_price_types);
wp_remove_object_terms($package_id, $old_terms_names, '_wiaas_shop_prices');
}
// get visible price types set by shop owner (commercial lead)
$visible_price_types = array_keys(wp_list_filter($cl_extras, array('visible' => true)));
$new_terms_names = preg_filter('/^/', '_' . $owner_id . '_', $visible_price_types);
// create term for every visible pricing type and link them to package so package can be queried
wp_set_object_terms($package_id, $new_terms_names, '_wiaas_shop_prices');
}
}
Wiaas_Shop::init();

View File

@@ -8,13 +8,20 @@ defined( 'ABSPATH' ) || exit;
class Wiaas_User {
public static function init() {
include_once dirname( __FILE__ ) . '/class-wiaas-countries.php';
include_once dirname( __FILE__ ) . '/user/class-wiaas-customer.php';
add_action('init', array(__CLASS__, 'load_user_organization'));
add_action('plugins_loaded', array(__CLASS__, 'remove_default_user_groups'), 30);
add_filter('woocommerce_rest_prepare_customer', array(__CLASS__, 'transform_rest_customer'), 10, 3);
add_filter('jwt_auth_token_before_dispatch', array(__CLASS__, 'transform_jwt_token_response'), 10, 2);
}
public static function load_user_organization() {
if (class_exists('WP_User_Taxonomy')) {
require_once dirname( __FILE__ ) . '/user/class-wiaas-user-organization.php';
require_once dirname( __FILE__ ) . '/user/wiaas-organization-functions.php';
new Wiaas_User_Organization();
}
@@ -24,6 +31,47 @@ class Wiaas_User {
remove_action( 'init', 'wp_register_default_user_group_taxonomy' );
remove_action( 'init', 'wp_register_default_user_type_taxonomy' );
}
/**
* Apply wiaas custom transformation on retrieved JSON customer object
*
* @param $response
* @param $order
* @param $request
*
* @return mixed
*/
public static function transform_rest_customer($response, $order, $request) {
$data = $response->get_data();
$user_id = $data['id'];
$customer_info = Wiaas_Customer::get_customer_info($user_id);
return new WP_REST_Response($customer_info);
}
/**
* Apply wiaas custom transformation on JWT token response
*
* @param $data
* @param $user
*
* @return mixed
*/
public static function transform_jwt_token_response($data, $user) {
return new WP_REST_Response(array(
'token' => $data['token'],
'userInfo' => array(
'wiaas_id_user' => $user->ID,
'wiaas_is_company_admin' => 1, //TODO: don't hardcode this
'wiaas_user_full_name' => $user->first_name . ' ' . $user->last_name,
'wiaas_user_type' => $user->roles,
'wiaas_username' => $user->data->user_login
)
));
}
}
Wiaas_User::init();

View File

@@ -33,7 +33,9 @@ class Wiaas_CLI_Update_DB_Command {
$wpdb->hide_errors();
include_once WIAAS_DIR . '/includes/class-wiaas-db-update.php';
include_once WIAAS_DIR . '/includes/db-updates/wiaas-db-update-functions.php';
include_once WIAAS_DIR . '/includes/db-updates/wiaas-db-update-general.php';
include_once WIAAS_DIR . '/includes/db-updates/wiaas-db-update-roles.php';
include_once WIAAS_DIR . '/includes/db-updates/wiaas-db-update-ui-fields.php';
$pending_db_updates = Wiaas_DB_Update::get_pending_db_updates();

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,90 @@
[
{
"key": "group_5bbe558ba265c",
"title": "Organization Info",
"fields": [
{
"key": "field_5bbe5c0d1f1a7",
"label": "Phone",
"name": "_wiaas_organization_phone",
"type": "text",
"instructions": "",
"required": 1,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"default_value": "",
"placeholder": "",
"prepend": "",
"append": "",
"maxlength": ""
},
{
"key": "field_5bbe5c291f1a8",
"label": "VAT Code",
"name": "_wiaas_organization_vat",
"type": "text",
"instructions": "",
"required": 1,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"default_value": "",
"placeholder": "",
"prepend": "",
"append": "",
"maxlength": ""
},
{
"key": "field_5bbe559d66d17",
"label": "Roles",
"name": "_wiaas_organization_roles",
"type": "select",
"instructions": "",
"required": 1,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"choices": {
"administrator": "Administrator",
"supplier": "Supplier",
"commercial_lead": "Commercial Lead",
"customer": "Customer"
},
"default_value": [],
"allow_null": 0,
"multiple": 1,
"ui": 1,
"ajax": 1,
"return_format": "label",
"placeholder": ""
}
],
"location": [
[
{
"param": "taxonomy",
"operator": "==",
"value": "wiaas-user-organization"
}
]
],
"menu_order": 0,
"position": "normal",
"style": "seamless",
"label_placement": "top",
"instruction_placement": "field",
"hide_on_screen": "",
"active": 1,
"description": ""
}
]

View File

@@ -0,0 +1,52 @@
[
{
"key": "group_5bbce9f38f149",
"title": "User Organization",
"fields": [
{
"key": "field_5bbe54366aac1",
"label": "Organization",
"name": "_wiaas_organization_id",
"type": "taxonomy",
"instructions": "Select Organization for user",
"required": 1,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"taxonomy": "wiaas-user-organization",
"field_type": "select",
"allow_null": 0,
"add_term": 0,
"save_terms": 1,
"load_terms": 1,
"return_format": "id",
"multiple": 0
}
],
"location": [
[
{
"param": "user_form",
"operator": "==",
"value": "edit"
},
{
"param": "current_user_role",
"operator": "==",
"value": "administrator"
}
]
],
"menu_order": 0,
"position": "normal",
"style": "seamless",
"label_placement": "left",
"instruction_placement": "field",
"hide_on_screen": "",
"active": 1,
"description": ""
}
]

View File

@@ -1,9 +1,9 @@
<?php
/**
* Wiaas DB updates
* General Wiaas DB updates
*
* Functions for updating database to latest version
* General functions for updating wiaas database to latest version
*/
@@ -78,16 +78,6 @@ function wiaas_db_update_add_delivery_process_forms() {
do_action('gform_forms_post_import', $created_forms);
}
function wiaas_db_update_setup_customer_capabilities() {
$customer_role = get_role('customer');
$customer_role->add_cap('read_private_shop_orders');
$customer_role->add_cap('read_private_products');
$customer_role->add_cap('read_shop_order');
$customer_role->add_cap('publish_shop_orders');
}
function wiaas_db_update_enable_orders_access_management() {
$post_types_option = Groups_Options::get_option( Groups_Post_Access::POST_TYPES, array() );
@@ -123,6 +113,16 @@ function wiaas_db_setup_exclusive_taxonomies() {
));
}
function wiaas_db_setup_default_cl() {
wp_insert_term(Wiaas_Pricing::COMMERCIAL_LEAD_NAME, Wiaas_User_Organization::TAXONOMY_NAME);
function wiaas_db_setup_customer_capabilities() {
$customer_role = get_role('customer');
$customer_role->add_cap('read_private_shop_orders');
$customer_role->add_cap('read_private_products');
$customer_role->add_cap('read_shop_order');
$customer_role->add_cap('publish_shop_orders');
// user
$customer_role->add_cap('list_users');
$customer_role->add_cap('edit_users');
}

View File

@@ -0,0 +1,176 @@
<?php
/**
* Roles Wiaas DB updates
*
* Functions for updating wiaas roles in database
*
*/
function wiaas_db_update_create_default_roles() {
$roles = array(
'customer', // this role will be created by woocommerce so we do not have to create it here
'supplier',
'commercial_lead'
);
// remove wordpress default roles
remove_role('author');
remove_role('contributor');
remove_role('editor');
remove_role('subscriber');
// remove woocoommerce shop manager role
remove_role('shop_manager');
// Dummy gettext calls to get strings in the catalog.
/* translators: user role */
_x( 'Supplier', 'User role', 'wiaas' );
/* translators: user role */
_x( 'Commercial Lead', 'User role', 'wiaas' );
// Add wiaas roles
add_role(
'commercial_lead',
'Commercial Lead',
array(
'read' => true,
)
);
add_role(
'supplier',
'Supplier',
array(
'read' => true,
)
);
add_role(
'user',
'User',
array(
'read' => true
)
);
// set default wiaas role
update_option('default_role', 'user');
// capabilities
$capabilities = array();
$capability_types = array( 'wiaas_doc' );
foreach ( $capability_types as $capability_type ) {
$capabilities[ $capability_type ] = array(
// Post type.
"edit_{$capability_type}",
"read_{$capability_type}",
"delete_{$capability_type}",
"edit_{$capability_type}s",
"edit_others_{$capability_type}s",
"publish_{$capability_type}s",
"read_private_{$capability_type}s",
"delete_{$capability_type}s",
"delete_private_{$capability_type}s",
"delete_published_{$capability_type}s",
"delete_others_{$capability_type}s",
"edit_private_{$capability_type}s",
"edit_published_{$capability_type}s",
// Terms.
"manage_{$capability_type}_terms",
"edit_{$capability_type}_terms",
"delete_{$capability_type}_terms",
"assign_{$capability_type}_terms",
);
}
foreach ( $capabilities as $cap_group ) {
foreach ( $cap_group as $cap ) {
wp_roles()->add_cap( 'administrator', $cap );
wp_roles()->add_cap( 'commercial_lead', $cap );
}
}
}
function wiaas_db_import_aam_role_settings() {
// update role settings that are imported
$content = file_get_contents( dirname( __FILE__ ) . '/data/aam-settings.json' );
$importer = new AAM_Core_Importer($content);
$importer->run();
// update toolbar settins manually since it does not get imported
update_option('aam_toolbar_default', array (
'about' => '1',
'toolbar-wp-logo' => '1',
'wporg' => '1',
'documentation' => '1',
'support-forums' => '1',
'feedback' => '1',
'toolbar-site-name' => '0',
'view-site' => '1',
'view-store' => '1',
'toolbar-updates' => '1',
'toolbar-comments' => '1',
'toolbar-new-content' => '1',
'new-post' => '1',
'new-media' => '1',
'new-page' => '1',
'new-product' => '1',
'new-shop_order' => '1',
'new-shop_coupon' => '1',
'new-wiaas_doc' => '1',
'new-user' => '1',
'gravityforms-new-form' => '1',
)
);
}
function wiaas_db_update_update_commercial_lead_capabilities() {
// add commercial lead specific roles
wp_roles()->add_cap( 'commercial_lead', 'manage_wiaas_cl_products' );
wp_roles()->add_cap( 'commercial_lead', 'view_admin_dashboard' );
wp_roles()->add_cap( 'commercial_lead', 'read' );
wp_roles()->add_cap( 'commercial_lead', 'upload_files' );
wp_roles()->add_cap( 'commercial_lead', 'edit_products' );
wp_roles()->add_cap( 'commercial_lead', 'edit_others_products' );
}
function wiaas_db_update_update_supplier_capabilities() {
// add supplier specific roles
wp_roles()->add_cap( 'supplier', 'view_admin_dashboard' );
wp_roles()->add_cap( 'supplier', 'read' );
}
function wiaas_db_update_update_admin_capabilities() {
wp_roles()->add_cap( 'administrator', 'create_products' );
}
function wiaas_create_role_access_groups() {
Groups_Group::create(array(
'name' => 'admin',
));
Groups_Group::create(array(
'name' => 'commercial_lead',
));
Groups_Group::create(array(
'name' => 'supplier',
));
Groups_Group::create(array(
'name' => 'customer',
));
}

View File

@@ -0,0 +1,19 @@
<?php
function wiaas_db_update_add_organization_info_ui_fields() {
$ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-organization-info.json' );
$ui_json = json_decode( $ui_json, true );
acf_import_field_group($ui_json[0]);
}
function wiaas_db_update_add_user_organization_ui_fields() {
$ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-user-organization.json' );
$ui_json = json_decode( $ui_json, true );
acf_import_field_group($ui_json[0]);
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* Handle download requests for wiaas documents
*
* Class Wiaas_Document_Download
*/
class Wiaas_Document_Download {
public static function init() {
// register download trigger for downloads from admin panel
if ( isset($_GET['wiaasdoc']) ) {
add_action( 'init', array( __CLASS__, 'admin_download' ) );
}
}
/**
* Since only REST api uses JWT Authentication this endpoint will work only for users
* that are logged in directly to wordpress
*/
public static function admin_download() {
if (!is_user_logged_in()) {
wp_die( __( 'No Access.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 403 ) );
}
$document_id = (int)$_GET['wiaasdoc'];
if ($document_id <= 0) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$version = isset($_GET['v']) ? (int)$_GET['v'] : null;
self::download_document($document_id, $version);
}
/**
* Download latest or specific document version
* @param $document_id
* @param null $version_id
*/
public static function download_document($document_id, $version_id = null) {
$version = Wiaas_Document::get_doc_version($document_id, $version_id);
$file_path = wiaas_get_document_version_path($version);
if (!file_exists($file_path)) {
wp_die( __( 'Document not found.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 404 ) );
}
WC_Download_Handler::download_file_force(
$file_path,
pathinfo( $file_path, PATHINFO_FILENAME ) . '.' . pathinfo( $file_path, PATHINFO_EXTENSION )
);
}
/**
* Download document related to order item
*
* @param $order_id
* @param $item_id
* @param $type
* @param $document_key
*/
public static function download_order_item_document($order_id, $item_id, $type, $document_key) {
$order = wc_get_order($order_id);
if (!$order) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$item = $order->get_item($item_id);
if (!$item) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$item_documents = wiaas_get_standard_package_order_item_documents($order, $item_id);
$order_document = null;
foreach ($item_documents as $item_document) {
if ($item_document['key'] === $document_key && $item_document['type'] === $type) {
$order_document = $item_document;
break;
}
}
if (!isset($order_document)) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$file_path = wiaas_get_document_version_path($order_document['version']);
if (!file_exists($file_path)) {
wp_die( __( 'Document not found.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 404 ) );
}
WC_Download_Handler::download_file_force(
$file_path,
pathinfo( $file_path, PATHINFO_FILENAME ) . '.' . pathinfo( $file_path, PATHINFO_EXTENSION )
);
}
/**
* Download cart document
*
* @param $item_key
* @param $type
* @param $document_key
*/
public static function download_cart_document($item_key, $type, $document_key) {
$item = WC()->cart->get_cart_item($item_key);
if (!isset($item)) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$item_documents = $item['_wiaas_documents'];
if (!isset($item_documents) ||
empty($item_documents) ||
!array_key_exists($type, $item_documents)) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$cart_document = $item_documents[$type];
if ($cart_document['key'] !== $document_key) {
wp_die( __( 'Invalid Document Request.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 400 ) );
}
$file_path = wiaas_get_document_version_path($cart_document['version']);
if (!file_exists($file_path)) {
wp_die( __( 'Document not found.', 'wiaas' ), __( 'Download Error', 'wiaas' ), array( 'response' => 404 ) );
}
WC_Download_Handler::download_file_force(
$file_path,
pathinfo( $file_path, PATHINFO_FILENAME ) . '.' . pathinfo( $file_path, PATHINFO_EXTENSION )
);
}
}
Wiaas_Document_Download::init();

View File

@@ -0,0 +1,88 @@
<?php
class Wiaas_Document_Upload {
private static $allowed_extensions = array(
'pdf','docx','doc','xlsx','xls','odt','ods', 'zip'
);
public static function init() {
add_filter( 'upload_dir', array( __CLASS__, 'upload_dir' ) );
}
/**
* Allowed extensions for wiaas documents uploads
* @return array
*/
public static function allowed_extensions() {
return self::$allowed_extensions;
}
/**
* Handle wiaas document upload
*
* @param string $file_id
*
* @return int|WP_Error
*/
public static function upload_document_version($file_id = 'file') {
wc_maybe_define_constant( 'WIAAS_DOCUMENT_UPLOAD', true );
// validate file
if (!isset($_FILES[$file_id])) {
return new WP_Error( 'wiaas_upload_error_missing_file', 'No file!' );
}
$file_name = $_FILES[$file_id]['name'];
$name = esc_attr($file_name);
$ext = explode('.', $name);
$ext = end($ext);
$ext = strtolower($ext);
if(!in_array($ext, self::$allowed_extensions)) {
return new WP_Error( 'wiaas_upload_error_invalid_extension', 'Invalid file extension!' );
}
$file = wp_handle_upload(
$_FILES[$file_id],
array( 'test_form' => false ),
current_time('mysql'));
if ( isset($file['error']) )
return new WP_Error( 'wiaas_upload_error', $file['error'] );
return wiaas_get_doc_version_from_path($file['file']);
}
/**
* Updates wordpress upload dir so that wiaas documents are uploaded to wiaas specific upload dir
* @param $pathdata
*
* @return mixed
*/
public static function upload_dir( $pathdata ) {
if (defined('WIAAS_DOCUMENT_UPLOAD') ) {
if ( empty( $pathdata['subdir'] ) ) {
$pathdata['path'] = $pathdata['path'] . wiaas_documents_base_dir();
$pathdata['url'] = $pathdata['url'] . wiaas_documents_base_dir();
$pathdata['subdir'] = wiaas_documents_base_dir();
} else {
$new_subdir = wiaas_documents_base_dir() . $pathdata['subdir'];
$pathdata['path'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['path'] );
$pathdata['url'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['url'] );
$pathdata['subdir'] = str_replace( $pathdata['subdir'], $new_subdir, $pathdata['subdir'] );
}
}
return $pathdata;
}
}
Wiaas_Document_Upload::init();

View File

@@ -0,0 +1,412 @@
<?php
/**
* Class Wiaas_Document
*/
class Wiaas_Document {
/**
* Default available document types for wiaas
* @var array
*/
private static $available_doc_types = array(
'template_questionaire' => array(
'name' => 'Template Questionaire',
'is_special_type' => false,
),
'order_questionaire' => array(
'name' => 'Order Questionaire',
'is_special_type' => true,
),
'configuration' => array(
'name' => 'Configuration',
'is_special_type' => true,
),
'install_guide' => array(
'name' => 'Install guide',
'is_special_type' => false,
),
'customer_acceptance' => array(
'name' => 'Customer acceptance',
'is_special_type' => true,
),
'template_agreement' => array(
'name' => 'Template Agreement',
'is_special_type' => false,
),
'order_agreement' => array(
'name' => 'Order Agreement',
'is_special_type' => true,
),
'installation_protocol' => array(
'name' => 'Installation protocol',
'is_special_type' => true,
),
'statements' => array(
'name' => 'Statements',
'is_special_type' => false,
),
'customer_acceptance_template' => array(
'name' => 'Customer acceptance template',
'is_special_type' => false,
),
);
private static $special_doc_types= array(
'order_questionaire', 'configuration', 'customer_acceptance', 'order_agreement', 'installation_protocol'
);
public static function init() {
add_action('registered_taxonomy', array( __CLASS__, 'register_wiaas_doc_categories' ));
add_action('init', array(__CLASS__, 'register_wiaas_document'));
}
/**
* Retrieve available categories for wiaas documents
*
* @return array Array of available document categories
*/
public static function get_available_doc_types() {
$terms = get_terms(array(
'taxonomy' => 'wiaas_doc_type',
'hide_empty' => false,
));
return array_map(function($term) {
$is_special = array_key_exists($term->slug, self::$available_doc_types) ?
self::$available_doc_types[$term->slug]['is_special_type'] :
false;
return array(
'id' => $term->slug,
'name' => $term->name,
'is_special_type' => $is_special,
);
}, $terms);
}
/**
* Create new document
* @param $name
* @param $path
* @param bool $visible
*
* @return bool|int|WP_Error
*/
public static function add_document($name, $path, $visible = false) {
// create
$id = wp_insert_post( array(
'post_title' => $name,
'post_author' => wp_get_current_user()->ID,
'post_type' => 'wiaas_doc',
'post_status' => 'publish',
) );
if ( is_wp_error( $id ) ) {
return false;
}
error_log(gettype($visible));
update_post_meta($id, '_wiaas_doc_versions', array( $path ));
self::set_is_doc_visible($id, $visible);
return $id;
}
/**
* Add new version for document
* @param $doc_id
* @param $url
*/
public static function add_document_version($doc_id, $url) {
$versions = get_post_meta($doc_id, '_wiaas_doc_versions', true);
$versions[] = $url;
update_post_meta($doc_id, '_wiaas_doc_versions', $versions);
}
/**
* Assign type to document
* @param $id
* @param $type
*/
public static function set_doc_type($id, $type) {
wp_set_object_terms($id, $type, 'wiaas_doc_type');
}
/**
* Set if document visible to customer
* @param $id
* @param $is_visible
*/
public static function set_is_doc_visible($id, $is_visible) {
update_post_meta($id, '_wiaas_doc_visible', $is_visible ? 'yes' : 'no');
}
/**
* Retrieve document type
* @param $id
*
* @return array|null
*/
public static function get_doc_type($id) {
$terms = wp_get_object_terms($id, 'wiaas_doc_type');
if (is_wp_error($terms) || count($terms) === 0) {
return null;
}
$term = $terms[0];
return array(
'id' => $term->slug,
'name' => $term->name,
'is_special_type' => in_array($term->slug, self::$special_doc_types),
);
}
/**
* Retrieve if document visible to customer
* @param $id
*
* @return bool
*/
public static function is_doc_visible($id) {
return get_post_meta($id, '_wiaas_doc_visible', true) === 'yes';
}
/**
* Retrieve all versions for document
* @param $doc_id
*
* @return mixed
*/
public static function get_document_versions($doc_id) {
return get_post_meta($doc_id, '_wiaas_doc_versions', true);
}
/**
* Get latest or specific document version
* @param $id
* @param null $version_id
*
* @return null
*/
public static function get_doc_version($id, $version_id = null) {
$versions = self::get_document_versions($id);
if (count($versions) === 0) {
return null;
}
return isset($versions[$version_id]) ?
$versions[$version_id] : $versions[count($versions) - 1];
}
/**
* Get document download link for latest or specified version
* @param $id
* @param null $version
*
* @return string
*/
public static function get_doc_download_link($id, $version = null) {
$permalink = get_permalink($id);
$sap = strpos($permalink, '?')?'&':'?';
$ver = isset($version) ? "&v={$version}" : '';
return $permalink.$sap."wiaasdoc={$id}{$ver}";
}
/**
* Retrieve document informations
* @param $id
*
* @return array|null
*/
public static function get_doc_info($id) {
$post = get_post($id, ARRAY_A);
if (!$post) {
return null;
}
$version = self::get_doc_version($id);
return array(
'id' => $id,
'name' => $post['post_title'],
'url' => self::get_doc_download_link($id),
'type' => self::get_doc_type($id),
'version' => $version,
'visible' => self::is_doc_visible($id),
'extension' => wiaas_get_doc_version_extension($version),
);
}
/**
* Search document by name
* @param $name
* @param int $limit
* @param bool $include_special
*
* @return array
*/
public static function search($name, $limit = 10, $include_special = false) {
$query = new WP_Query();
$args = array(
'post_status' => 'publish',
'post_type' => 'wiaas_doc',
'posts_per_page' => $limit,
's' => $name
);
if (!$include_special) {
$args['tax_query'] = array(
array(
'taxonomy' => 'wiaas_doc_type',
'field' => 'slug',
'operator' => 'NOT IN',
'terms' => self::$special_doc_types,
)
);
}
$items = $query->query($args);
return array_map(function($item) {
$id = $item->ID;
return array(
'id' => $id,
'name' => $item->post_title,
);
}, $items);
}
/**
* Registers taxonomy and default values for wiaas document types
*/
public static function register_wiaas_doc_categories($taxonomy) {
if ($taxonomy !== 'wpdmcategory') {
return;
}
foreach (self::$available_doc_types as $key => $available_doc_type) {
wp_insert_term($available_doc_type['name'], 'wpdmcategory', array(
'slug' => $key
));
}
}
public static function register_wiaas_document() {
// Register document object
self::_register_document();
// Register document types taxonomy
self::_register_doc_types();
}
// PRIVATE
/**
* Register wiaas_doc post type
*/
private static function _register_document() {
$labels = array(
'name' => __('Documents','wiaas'),
'singular_name' => __('Document','wiaas'),
'add_new' => __('Add New','wiaas'),
'add_new_item' => __('Add New Document','wiaas'),
'edit_item' => __('Edit Document','wiaas'),
'new_item' => __('New Document','wiaas'),
'all_items' => __('All Documents','wiaas'),
'view_item' => __('View Document','wiaas'),
'search_items' => __('Search Documents','wiaas'),
'not_found' => __('No Document Found','wiaas'),
'not_found_in_trash' => __('No Documents found in Trash','wiaas'),
'parent_item_colon' => '',
'menu_name' => __('Documents','wiaas')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'query_var' => true,
'rewrite' => array('slug' => 'wiaas_doc', 'with_front' => false),
'capability_type' => 'wiaas_doc',
'has_archive' => false,
'hierarchical' => false,
'taxonomies' => array(),
'menu_icon' => 'dashicons-media-document',
'exclude_from_search' => false,
'supports' => array('title'),
);
register_post_type('wiaas_doc', $args);
}
/**
* Register wiaas_doc_type taxonomy for wiaas_doc post type
*/
private static function _register_doc_types() {
$labels = array(
'name' => _x( 'Document type', 'taxonomy general name', 'wiaas' ),
'singular_name' => _x( 'Document type', 'taxonomy singular name', 'wiaas' ),
'menu_name' => _x( 'Document types', 'Admin menu name', 'wiaas' ),
'search_items' => __( 'Search Document types', 'wiaas' ),
'all_items' => __( 'All Document types', 'wiaas' ),
'parent_item' => __( 'Parent Document type', 'wiaas' ),
'parent_item_colon' => __( 'Parent Document type:', 'wiaas' ),
'edit_item' => __( 'Edit Document type', 'wiaas' ),
'update_item' => __( 'Update Document type', 'wiaas' ),
'add_new_item' => __( 'Add New Document type', 'wiaas' ),
'new_item_name' => __( 'New Document type Name', 'wiaas' ),
);
$args = array(
'hierarchical' => false,
'label' => __( 'Document type', 'wiaas' ),
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'wiaas_doc_type' ),
'capabilities' => array(
'manage_terms' => 'manage_wiaas_doc_terms',
'edit_terms' => 'edit_wiaas_doc_terms',
'delete_terms' => 'delete_wiaas_doc_terms',
'assign_terms' => 'assign_wiaas_doc_terms',
),
);
register_taxonomy( 'wiaas_doc_type', array( 'wiaas_doc' ), $args );
foreach (self::$available_doc_types as $key => $available_doc_type) {
wp_insert_term($available_doc_type['name'], 'wiaas_doc_type', array(
'slug' => $key
));
}
}
}
Wiaas_Document::init();

View File

@@ -0,0 +1,190 @@
<?php
/**
* Base directory for wiaas document uploads
* @return string
*/
function wiaas_documents_base_dir() {
return '/woocommerce_uploads';
}
/**
* Upload directory for wiaas document uploads
* @return string
*/
function wiaas_documents_upload_dir() {
$wp_uploads = wp_upload_dir();
$wp_uploads_dir = $wp_uploads['basedir'];
return $wp_uploads_dir . wiaas_documents_base_dir();
}
/**
* Retrieve upload path for wiaas document version
* @param string $version
*
* @return string
*/
function wiaas_get_document_version_path($version) {
return wiaas_documents_upload_dir() . '/' . $version;
}
/**
* Retrieve if wiaas document version exists
* @param string $version
*
* @return bool
*/
function wiaas_document_version_exists($version) {
return file_exists(wiaas_get_document_version_path($version));
}
/**
* Retrieve wiaas document version from file path
* (that is relative path from wiaas document upload dir)
* @param string $path
*
* @return string
*/
function wiaas_get_doc_version_from_path($path) {
return str_replace(wiaas_documents_upload_dir() . '/', '', $path);
}
/**
* Retrieve filename for wiaas document version
* @param string $version
*
* @return string
*/
function wiaas_get_doc_version_filename($version) {
return pathinfo( $version, PATHINFO_FILENAME );
}
/**
* Retrieve extension for wiaas document version
* @param string $version
*
* @return string
*/
function wiaas_get_doc_version_extension($version) {
return pathinfo( $version, PATHINFO_EXTENSION );
}
/**
* Attach wiaas document to post object
* @param int $object_id
* @param array $document_ids
*/
function wiaas_attach_documents_to_object($object_id, $document_ids) {
update_post_meta($object_id, '_wiaas_attached_documents', $document_ids);
}
/**
* Retrieve wiaas documents ids for post object
* @param int $object_id
*
* @return array
*/
function wiaas_get_object_attached_documents($object_id) {
$document_ids = get_post_meta($object_id, '_wiaas_attached_documents', true);
return isset($document_ids) && !empty($document_ids) ? $document_ids : array();
}
/**
* Retrieve all documents for single standard wiaas package
*
* this includes:
* - package linked documents
* - addons linked documents
* - options linked documents
* - all documents attacked to bundled products of package, addons and options
*
* @param int $package
* @param bool $only_visible
*
* @return array
*/
function wiaas_get_standard_package_documents($package, $only_visible = false) {
// retrieve addons and option packages ids
$all_package_ids = array_merge(
Wiaas_Package_Addon::get_package_addons_ids($package),
Wiaas_Package_Option_Groups::get_package_option_ids($package),
array($package->get_id())
);
// retrieve all bundled products from all relevant packages
$all_product_ids = array_values(
WC_PB_DB::query_bundled_items(array(
'return' => 'id=>product_id',
'bundle_id' => $all_package_ids
))
);
$all_object_ids = array_unique(array_merge($all_package_ids, $all_product_ids));
// retrieve document ids from all packages and products
$document_ids = array();
foreach ($all_object_ids as $object_id) {
$document_ids = array_merge(
$document_ids,
wiaas_get_object_attached_documents($object_id));
}
$document_ids = array_unique($document_ids);
// filter only visible if needed and retrieve documents info
$documents = array();
foreach ($document_ids as $document_id) {
if ($only_visible && Wiaas_Document::is_doc_visible($document_id) || !$only_visible) {
$documents[] = Wiaas_Document::get_doc_info($document_id);
}
}
return $documents;
}
/**
* Retrieve all documents for single order standard package item
*
* @param WC_Order $order
* @param int $package_item_id
*
* @return array
*/
function wiaas_get_standard_package_order_item_documents($order, $package_item_id) {
$order_items = $order->get_items( 'line_item' );
$package_order_item = $order->get_item($package_item_id);
// retrieve package order item addons and options
$all_package_order_items = array_merge(
wiaas_get_order_item_addons($order_items, $package_order_item),
wiaas_get_order_item_options($order_items, $package_order_item),
array( $package_order_item )
);
$all_order_items = $all_package_order_items;
// retrieve bundled product items for each package
foreach ($all_package_order_items as $item) {
$all_order_items = array_merge(
$all_order_items,
wc_pb_get_bundled_order_items($item, $order)
);
}
$order_documents = array();
foreach ($all_order_items as $order_item) {
$order_documents = array_merge(
$order_documents,
isset($order_item['wiaas_documents']) ? $order_item['wiaas_documents'] : array()
);
}
return array_map(function($doc) {
// append document extension and name information
$doc['extension'] = wiaas_get_doc_version_extension($doc['version']);
$doc['name'] = isset($doc['name']) ? $doc['name'] : wiaas_get_doc_version_filename($doc['version']);
return $doc;
}, $order_documents);
}

View File

@@ -0,0 +1,151 @@
<?php
class Wiaas_Order_Project {
public static function init() {
add_action('woocommerce_after_register_taxonomy', array(__CLASS__, 'register_order_project_taxonomy'));
}
/**
* Register order project taxonomy
*/
public static function register_order_project_taxonomy() {
$labels = array(
'name' => _x( 'Project', 'taxonomy general name', 'wiaas' ),
'singular_name' => _x( 'Project', 'taxonomy singular name', 'wiaas' ),
'search_items' => __( 'Search Order Projects', 'wiaas' ),
'all_items' => __( 'All Order Projects', 'wiaas' ),
'parent_item' => __( 'Parent Order Project', 'wiaas' ),
'parent_item_colon' => __( 'Parent Order Project:', 'wiaas' ),
'edit_item' => __( 'Edit Order Project', 'wiaas' ),
'update_item' => __( 'Update Order Project', 'wiaas' ),
'add_new_item' => __( 'Add New Order Project', 'wiaas' ),
'new_item_name' => __( 'New Order Project Name', 'wiaas' ),
'menu_name' => __( 'Order Project', 'wiaas' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'shop_order_project' ),
'update_count_callback' => array(__CLASS__, 'update_count_callback')
);
register_taxonomy( 'shop_order_project', array( 'shop_order' ), $args );
}
/**
* Callback to handle counting of number of orders inside every project
* This does not work out of the box for orders since they are marked as private post type
*
* @param array $project_ids
*/
public static function update_count_callback($project_ids) {
// Update counts
_update_generic_term_count( $project_ids, get_taxonomy('shop_order_project') );
}
/**
* Retrieves available order projects
* @return array List of available order projects
*/
public static function get_available_order_projects() {
$all_terms = get_terms(array(
'taxonomy' => 'shop_order_project',
'hide_empty' => false
));
if (is_wp_error($all_terms)) {
return array();
}
$available_terms = array();
foreach ($all_terms as $term) {
if (self::is_order_project_available($term->term_id)) {
$available_terms[] = array(
'id' => $term->term_id,
'name' => $term->name
);
}
}
return $available_terms;
}
/**
* Retrieves order project name
* @param int $order_id
*
* @return string|null Project name if order is assigned to project, null otherwise
*/
public static function get_project_name_for_order($order_id) {
$terms = wp_get_object_terms($order_id, 'shop_order_project');
return isset($terms[0]) ? $terms[0]->name : null;
}
/**
* Assigns giver order to given project
* @param int $order_id
* @param int $project_id
*/
public static function set_project_for_order($order_id, $project_id) {
wp_set_object_terms($order_id, $project_id, 'shop_order_project', false);
}
/**
* Adds new order project
* @param string $name Order Project name
* @param bool $is_available Flag indicating is order project available
*
* @return bool True on success, False on failure.
*/
public static function add_order_project($name, $is_available = true) {
$result = wp_create_term($name, 'shop_order_project');
if (is_wp_error($result)) {
return false;
}
// save is term available
$id = is_numeric($result) ? $result : $result['term_id'];
self::_save_available_field($id, $is_available);
return true;
}
/**
* @param int|WP_Term $project Order project or order project id
* @param bool $is_available
*/
public static function set_is_order_project_available($project, $is_available) {
$project_id = is_numeric($project) ? $project : $project->term_id;
self::_save_available_field($project_id, $is_available);
}
/**
* Retrieves if order project is available
* @param int|WP_Term $project Order project objects or id of order project
*
* @return bool TRUE if available, FALSE if not available
*/
public static function is_order_project_available($project) {
$project_id = is_numeric($project) ? $project : $project->term_id;
return get_term_meta($project_id, '_wiaas_is_available', true) === 'yes';
}
// PRIVATE
/**
* @param int $id Order project id
* @param bool $is_available
*/
private static function _save_available_field($id, $is_available) {
update_term_meta($id, '_wiaas_is_available', $is_available ? 'yes' : 'no');
}
}
Wiaas_Order_Project::init();

View File

@@ -49,6 +49,16 @@ class Wiaas_Package_Addon {
return $addons;
}
/**
* Retrieve ids of package addons
* @param int $package
*
* @return array
*/
public static function get_package_addons_ids($package) {
return $package->get_meta( '__wiaas_package_addons' );
}
/**
* Sets addons for provided wiaas standard package type
* @param $package

View File

@@ -81,6 +81,24 @@ class Wiaas_Package_Option_Groups {
return $option_groups;
}
/**
* Retrieve ids of all package options
* @param int $package
*
* @return array
*/
public static function get_package_option_ids($package) {
$groups_data = $package->get_meta( '_wiaas_package_option_groups' );
$options_ids = array();
foreach ($groups_data as $group_data) {
$options_ids = array_merge($options_ids, $group_data['options']);
}
return array_unique($options_ids);
}
/**
* Set groups of optional packages for provided package
* @param $package

View File

@@ -0,0 +1,105 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Class Wiaas_Package_Status
*/
class Wiaas_Package_Status {
const AVAILABLE = 'available';
const INVALID_MARGIN = 'margin_exceeded';
const INVALID_TEMPLATE = 'invalid_template';
public static function init() {
add_action('init', array( __CLASS__, 'register_package_status_taxonomy' ) );
}
/**
* Register wiaas package status taxonomy
*/
public static function register_package_status_taxonomy() {
$labels = array(
'name' => _x( 'Package status', 'taxonomy general name', 'wiaas' ),
'singular_name' => _x( 'Package status', 'taxonomy singular name', 'wiaas' ),
'search_items' => __( 'Search Package statuses', 'wiaas' ),
'all_items' => __( 'All Package statuses', 'wiaas' ),
'parent_item' => __( 'Parent Package status', 'wiaas' ),
'parent_item_colon' => __( 'Parent Package status:', 'wiaas' ),
'edit_item' => __( 'Edit Package status', 'wiaas' ),
'update_item' => __( 'Update Package status', 'wiaas' ),
'add_new_item' => __( 'Add New Package status', 'wiaas' ),
'new_item_name' => __( 'New Package status Name', 'wiaas' ),
'menu_name' => __( 'Package status', 'wiaas' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => false,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'package_status' ),
);
register_taxonomy( 'package_status', array( 'product' ), $args );
// Register available package statuses
$statuses = [self::AVAILABLE, self::INVALID_MARGIN, self::INVALID_TEMPLATE];
foreach ($statuses as $status) {
wp_insert_term($status, 'package_status');
}
}
/**
* Retrieve available wiaas package statuses
* @return array
*/
public static function get_available_package_statuses() {
$statuses = get_terms( array(
'taxonomy' => 'package_status',
'hide_empty' => false,
) );
return array_map(function($status) {
return $status->name;
}, $statuses);
}
/**
* Retrieve package status for provided package id
* @param $package_id
*
* @return null
*/
public static function get_package_status($package_id) {
$terms = wp_get_object_terms($package_id, 'package_status');
$package_status = isset($terms[0]) ? $terms[0]->name : null;
return $package_status;
}
/**
* Set package status for provided package id
* @param $package_id
* @param $status
*/
public static function set_package_status($package_id, $status) {
wp_delete_object_term_relationships( $package_id, 'package_status' );
if (isset($status)) {
wp_set_object_terms($package_id, $status, 'package_status', false);
}
}
}
Wiaas_Package_Status::init();

View File

@@ -88,4 +88,14 @@ function wiaas_get_cart_item_addons($cart_item) {
}
return $addon_cart_items;
}
/**
* Check if order item is wiaas standard package
* @param WC_Order_Item $item
*
* @return bool
*/
function wiaas_is_order_item__standard_package($item) {
return isset($item['wiaas_standard_package']);
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* Handles logic for setting and retrieving commercial lead extra prices
*
* Class Wiaas_Package_CL_Pricing
*/
class Wiaas_Package_CL_Pricing {
/**
* Sets package extra prices
*
* @param int $owner_id ID of the shop owner organization who set extra prices
* @param int $package_id
* @param array $cl_extras
*/
public static function set_extras($owner_id, $package_id, $cl_extras) {
foreach ($cl_extras as $extra_type => $cl_extra) {
unset($cl_extra['type']);
unset($cl_extra['customer']);
$cl_extras[$extra_type] = $cl_extra;
}
$old_extras = self::get_extras($owner_id, $package_id);
// Persist package price extras
update_term_meta(
$owner_id,
'_wiaas_cm_extras_'.$package_id,
$cl_extras);
do_action('wiaas_package_prices_extras_set', $owner_id, $package_id, $cl_extras, $old_extras);
}
/**
* Retrieves package catalogue extra prices
*
* @param int $owner_id ID of the shop owner organization who set extra prices
* @param int $package_id
*
* @return array|null
*/
public static function get_extras($owner_id, $package_id) {
$cl_extras = get_term_meta(
$owner_id,
'_wiaas_cm_extras_'.$package_id,
true);
return is_array($cl_extras) ? $cl_extras : null;
}
/**
* Retrieve catalogue package extra prices for provided customer
*
* If customer specific prices are set for the package, only those will be retrieved
* otherwise deafult prices exras will be retrieved
*
* @param int $owner_id ID of the shop owner organization who set extra prices
* @param string $pay_type Payment type for the pacakge
* @param int $package_id ID of the package
* @param int $customer_id ID of the customer
*
* @return array|null
*/
public static function get_extras_for_customer($owner_id, $pay_type, $package_id, $customer_id) {
$cl_extras = self::get_extras($owner_id, $package_id);
if (! empty($cl_extras)) {
// if customer specific prices are set for this package use only them
// else use default prices set for this package
if (self::_customer_specific_prices_exist($cl_extras, $customer_id)) {
$cl_pay_type = $pay_type . '_customer_' . $customer_id;
} else {
$cl_pay_type = $pay_type . '_default';
}
$cl_pay_type_extras = $cl_extras[$cl_pay_type];
// if commercial lead has default price for this package then use it
if (! empty($cl_pay_type_extras) && $cl_pay_type_extras['visible']) {
return array(
'fixed' => floatval($cl_pay_type_extras['fixed']),
'services' => floatval($cl_pay_type_extras['services']),
'recurrent' => floatval($cl_pay_type_extras['recurrent'])
);
}
}
// there are no prices set for this payment type
return null;
}
private static function _customer_specific_prices_exist($cl_extras, $customer_id) {
$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());
$cl_customer_pay_types = array();
foreach ($pay_types as $pay_type) {
$cl_customer_pay_types[] = $pay_type.'_customer_'.$customer_id;
}
foreach ($cl_extras as $cl_pay_type => $data) {
if (in_array($cl_pay_type, $cl_customer_pay_types)) {
return true;
}
}
return false;
}
}

View File

@@ -51,6 +51,8 @@ class Wiaas_Package_Pricing {
public static function init() {
add_filter('woocommerce_bundle_price_html', array( __CLASS__, 'get_package_price_html' ), 10, 2);
add_action('woocommerce_update_product', array(__CLASS__, 'on_product_update' ), 10, 1 );
}
public static function get_package_price_html($price_html, $package) {
@@ -101,21 +103,46 @@ class Wiaas_Package_Pricing {
return self::_get_package_pricing_commision($package);
}
public static function get_package_max_cost_margin($package){
return self::_get_package_max_cost_margin($package);
}
/**
* Persist payment prices configuration for package
* @param $package
* @param $pricing_rules
*/
public static function set_package_prices($package, $pricing_rules, $commision) {
public static function set_package_prices($package, $pricing_rules, $commision, $max_cost_margin) {
if ( isset( $pricing_rules ) ) {
$package->update_meta_data( '_wiaas_pricing_rules', $pricing_rules );
$package->update_meta_data('_package_pricing_commision', $commision, true);
$package->update_meta_data('_package_max_cost_margin', $max_cost_margin, true);
} else {
$package->delete_meta_data( '_wiaas_pricing_rules' );
}
$package->save_meta_data();
}
/**
* Executes when woocommerce product is updated
*/
public static function on_product_update($product_id) {
$product = wc_get_product($product_id);
if ($product->get_type() === WC_Product_Simple::get_type()){
$product_price = Wiaas_Product_Pricing::get_product_price($product);
$packages_containing_updated_product = wc_pb_get_bundled_product_map( $product );
foreach($packages_containing_updated_product as $index => $package_id){
$package = new WC_Product_Bundle($package_id);
self::_validate_package($package);
}
}else if ($product->get_type() === WC_Product_Bundle::get_type()){
self::_validate_package($product);
}
}
// PRIVATE
private static function _get_package_prices($package) {
@@ -140,6 +167,16 @@ class Wiaas_Package_Pricing {
'principal_amount' => floatval($pricing_rule['principal_amount']),
'minimal_services_price' => floatval($pricing_rule['minimal_services_price']),
);
$minimal_recurrent_price = $prices[$type]['minimal_services_price'];
if ($prices[$type]['principal_amount'] > 0 && $prices[$type]['package_pay_period'] > 0) {
$minimal_recurrent_price += wiaas_PMT(
Wiaas_Pricing::INTEREST_RATE,
$prices[$type]['package_pay_period'],
$prices[$type]['principal_amount']);
}
$prices[$type]['minimal_recurrent_price'] = round($minimal_recurrent_price);
}
return $prices;
@@ -154,6 +191,26 @@ class Wiaas_Package_Pricing {
return (float) $commision;
}
private static function _get_package_max_cost_margin($package) {
$max_cost_margin = $package->get_meta( '_package_max_cost_margin', true);
if (!isset($max_cost_margin) || $max_cost_margin === '') {
return 0;
}
return (float) $max_cost_margin;
}
private static function _validate_package($package){
$package_total_cost = Wiaas_Pricing::get_package_total_cost($package);
$package_max_cost_margin = Wiaas_Package_Pricing::get_package_max_cost_margin($package);
if (($package_max_cost_margin != 0) && ($package_total_cost > $package_max_cost_margin)){
Wiaas_Package_Status::set_package_status($package->get_id(), Wiaas_Package_Status::INVALID_MARGIN);
}else{
Wiaas_Package_Status::set_package_status($package->get_id(), Wiaas_Package_Status::AVAILABLE);
}
}
}
Wiaas_Package_Pricing::init();

View File

@@ -11,7 +11,7 @@ class Wiaas_Product_Pricing {
add_filter('woocommerce_get_price_html', array(__CLASS__, 'get_product_price_html'), 10, 2);
add_filter('woocommerce_bundled_item_price', array(__CLASS__, 'get_bundled_product_fixed_price'), 10, 4);
add_filter('woocommerce_bundled_item_price', array(__CLASS__, 'get_product_fixed_price'), 10, 2);
add_filter('woocommerce_bundled_item_is_priced_individually', array(__CLASS__, 'is_bundled_product_price_fixed'), 10, 2);
@@ -32,7 +32,7 @@ class Wiaas_Product_Pricing {
}
/**
* Checks if bunded product has fixed price
* Checks if bundled product has fixed price
* @param $is_priced_individually
* @param $bundled_item
*
@@ -51,12 +51,10 @@ class Wiaas_Product_Pricing {
* Retrives fixed price for bundled product
* @param $price
* @param $product
* @param $discount
* @param $bundled_item
*
* @return int
*/
public static function get_bundled_product_fixed_price($price, $product, $discount, $bundled_item) {
public static function get_product_fixed_price($price, $product) {
if (self::_get_is_product_price_recurring($product)) {
return 0;
}
@@ -108,6 +106,8 @@ class Wiaas_Product_Pricing {
*/
public static function set_product_price($product, $price, $is_recurring = false, $pay_period = 0) {
$product->set_price($price);
$product->set_regular_price($price);
self::_set_is_product_price_recurring($product, $is_recurring);
self::_set_product_price_pay_period($product, $pay_period);

View File

@@ -0,0 +1,64 @@
<?php
defined('ABSPATH') || exit;
class Wiaas_Product_Supplier {
public static function init() {
add_action('init', array(__CLASS__, 'register_supplier_taxonomy'));
add_action('created_' . 'wiaas-user-organization', array(__CLASS__, 'on_organization_added'));
}
/**
* Register wiaas template category taxonomy
*/
public static function register_supplier_taxonomy() {
$labels = array(
'name' => _x('Supplier', 'taxonomy general name', 'wiaas'),
'singular_name' => _x('Supplier', 'taxonomy singular name', 'wiaas'),
'search_items' => __('Search Suppliers', 'wiaas'),
'all_items' => __('All Suppliers', 'wiaas'),
'parent_item' => __('Parent Supplier', 'wiaas'),
'parent_item_colon' => __('Parent Supplier', 'wiaas'),
'edit_item' => __('Edit Supplier', 'wiaas'),
'update_item' => __('Update Supplier', 'wiaas'),
'add_new_item' => __('Add New Supplier', 'wiaas'),
'new_item_name' => __('New Supplier Name', 'wiaas'),
'menu_name' => __('Supplier', 'wiaas'),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array('slug' => 'template_category'),
);
register_taxonomy('supplier', array('product'), $args);
}
/**
* Create corresponding supplier term for organization
*
* @param $organization_id
*/
public static function on_organization_added($organization_id) {
$organization = get_term_by('id', $organization_id, 'wiaas-user-organization');
$supplier = term_exists($organization->slug, 'supplier');
if (! $supplier) {
$supplier = wp_insert_term($organization->name, 'supplier', array(
'slug' => $organization->slug
));
}
add_term_meta($supplier['term_id'], 'organisation_id', $organization->term_id);
}
}
Wiaas_Product_Supplier::init();

View File

@@ -27,7 +27,108 @@ function construct_template_products_class() {
return 'wiaastemplate';
}
/**
* Get template categories from template product meta
*
* @param $template_id integer
* @param $template_category_slug string the name of the main wiaas category
* @return mixed
*/
public static function get_template_categories_from_meta($template_id, $template_category_slug) {
return get_post_meta($template_id, $template_category_slug, true);
}
public static function extract_template_product_categories($category_meta) {
$category_objects = array();
if (empty($category_meta)) {
return array();
}
foreach ($category_meta as $meta) {
if (!empty($meta)) {
$category_template_id = $meta['template_category_id'];
$template_category_object = new Wiaas_Template_Category_Object(
$category_template_id,
$meta['template_category_title'],
$meta['quantity']);
$category_objects[$category_template_id] = $template_category_object;
}
}
return empty($category_objects) ? null : $category_objects;
}
/**
* Get template categories from bundled products items
*
* @param $bundled_items array
* @return array
*/
public static function extract_bundled_product_categories($bundled_items) {
$template_category_objects = array();
foreach ($bundled_items as $item_id => $item) {
$item_data = $item->get_data();
$post_terms = wp_get_object_terms($item->get_product_id(), 'template_category', array('fields' => 'id=>name'));
if (!empty($post_terms) && !is_wp_error($post_terms)) {
$cat = '';
$category_template_id = '';
foreach ($post_terms as $id => $term) {
$cat = $term;
$category_template_id = $id;
}
$template_category_object = new Wiaas_Template_Category_Object(
$category_template_id,
$cat,
$item_data['quantity_max']);
$template_category_objects[$category_template_id] = $template_category_object;
}
}
return $template_category_objects;
}
/**
* Save selected template to bundled product meta
*
* @param $selected_template integer
* @param $post_id integer
*/
public static function bind_selected_template_to_product($selected_template, $post_id) {
if (!empty($selected_template))
update_post_meta($post_id, '_select_template', esc_attr($selected_template));
else {
update_post_meta($post_id, '_select_template', '');
}
}
/**
* Save template categories to template product meta
*
* @param $post_id integer
* @param $option string a main wiaas category
* @param $processed_template_data array actual template category data
*/
public static function save_template_product_meta($post_id, $option, $processed_template_data) {
update_post_meta($post_id, '_template_items_' . $option, $processed_template_data);
}
}
}

View File

@@ -0,0 +1,252 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* Class Wiaas_Customer
*/
class Wiaas_Customer {
public function __construct() {
include_once dirname( __FILE__ ) . '/../class-wiaas-countries.php';
}
public static function get_customer_info($customer_id){
$user = get_userdata($customer_id);
$result = array(
'id' => $customer_id,
'company_id' => self::get_customer_company_id($customer_id),
'is_company_admin' => self::get_customer_company_admin_status($customer_id),
'mail' => $user->user_email,
'name' => $user->first_name . ' ' . $user->last_name,
'phone' => self::get_customer_phone_number($customer_id),
'company_name' => self::get_customer_company_name($customer_id),
'vat_code' => self::get_customer_vat_code($customer_id),
'billing_addresses' => self::get_customer_billing_addresses($customer_id),
'profile_addresses' => self::get_customer_profile_addresses($customer_id),
'user_type' => $user->roles
);
return $result;
}
public static function get_customer_profile_addresses($customer_id){
return get_user_meta($customer_id, 'profile_addresses', true) ?: [];
}
/**
* Get customer profile address by id
*
* @param int $customer_id
* @param int $address_id
*
* @return array|null
*/
public static function get_customer_profile_address($customer_id, $address_id) {
$profile_addresses = self::get_customer_profile_addresses($customer_id);
$index = array_search($address_id, array_column($profile_addresses, 'id'));
if (is_numeric($index)) {
return $profile_addresses[$index];
}
return null;
}
public static function get_customer_billing_addresses($customer_id){
return get_user_meta($customer_id, 'billing_addresses', true) ?: [];
}
/**
* Get customer billing address by id
*
* @param int $customer_id
* @param int $address_id
*
* @return array|null
*/
public static function get_customer_billing_address($customer_id, $address_id) {
$billing_addresses = self::get_customer_billing_addresses($customer_id);
$index = array_search($address_id, array_column($billing_addresses, 'id'));
if (is_numeric($index)) {
return $billing_addresses[$index];
}
return null;
}
public static function get_customer_vat_code($customer_id){
return get_user_meta($customer_id, 'vat_code', true) ?: '';
}
public static function get_customer_company_name($customer_id){
return get_user_meta($customer_id, 'company_name', true) ?: '';
}
public static function get_customer_company_id($customer_id){
return 0; //TODO: don't hardocde this
}
public static function get_customer_company_admin_status($customer_id){
return 1; //TODO: don't hardcode this
}
public static function get_customer_phone_number($customer_id){
return get_user_meta($customer_id, 'phone', true) ?: '';
}
public static function update_customer_profile_info($customer_id, $first_name, $last_name, $phone){
$user = array(
'ID' => $customer_id,
'first_name' => $first_name,
'last_name' => $last_name
);
if (is_wp_error(wp_update_user($user))){
return false;
}
update_user_meta( $customer_id, 'phone', $phone);
return true;
}
public static function update_customer_company_info($customer_id, $company_name, $vat_code){
$result1 = update_user_meta( $customer_id, 'company_name', $company_name);
$result2 = update_user_meta( $customer_id, 'vat_code', $vat_code );
return $result1 || $result2;
}
public static function update_customer_billing_addresses($customer_id, $new_address){
if (!self::validate_address($new_address)){
return false;
}
$billing_addresses = self::get_customer_billing_addresses($customer_id);
if ($new_address->id){
$updated = array(
'id' => $new_address->id,
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
foreach($billing_addresses as $key => $address){
if ($address['id'] === $new_address->id){
$billing_addresses[$key] = $updated;
break;
}
}
}else{
$new_billing_address = array(
'id' => time(),
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
array_push($billing_addresses, $new_billing_address);
}
return update_user_meta( $customer_id, 'billing_addresses', $billing_addresses);
}
public static function update_customer_profile_addresses($customer_id, $new_address){
if (!self::validate_address($new_address)){
return false;
}
$profile_addresses = self::get_customer_profile_addresses($customer_id);
if ($new_address->id){
$updated = array(
'id' => $new_address->id,
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
foreach($profile_addresses as $key => $address){
if ($address['id'] === $new_address->id){
$profile_addresses[$key] = $updated;
break;
}
}
}else{
$new_delivery_address = array(
'id' => time(),
'country_name' => Wiaas_Countries::get_country_name_by_id($new_address->id_country_selected),
'delivery_mail' => $new_address->delivery_mail,
'id_country_selected' => $new_address->id_country_selected,
'city' => $new_address->city,
'detailed_address' => $new_address->detailed_address,
'zip_code' => $new_address->zip_code,
'first_name' => $new_address->first_name,
'last_name' => $new_address->last_name,
'invoice_mail' => $new_address->invoice_mail
);
array_push($profile_addresses, $new_delivery_address);
}
return update_user_meta( $customer_id, 'profile_addresses', $profile_addresses);
}
public static function delete_customer_profile_address($customer_id, $address_id){
$profile_addresses = self::get_customer_profile_addresses($customer_id);
$counter = 0;
foreach($profile_addresses as $key => $address){
if ($address['id'] == $address_id){
array_splice($profile_addresses, $counter, 1);
break;
}
$counter++;
}
return update_user_meta( $customer_id, 'profile_addresses', $profile_addresses);
}
public static function delete_customer_billing_address($customer_id, $address_id){
$billing_addresses = self::get_customer_billing_addresses($customer_id);
$counter = 0;
foreach($billing_addresses as $key => $address){
if ($address['id'] == $address_id){
array_splice($billing_addresses, $counter, 1);
break;
}
$counter++;
}
return update_user_meta( $customer_id, 'billing_addresses', $billing_addresses);
}
/**
* Check if address is valid
*
* @param $address
*
* @return bool
*/
private static function validate_address($address){
if (empty($address->city)){
return false;
}
if (empty($address->detailed_address)){
return false;
}
return is_numeric($address->zip_code);
}
}

View File

@@ -32,13 +32,24 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
parent::hooks();
add_action('user_new_form', array( $this, 'show_organizations_selection' ));
add_action('user_register', array( $this, 'save_terms_for_user' ));
add_action( 'created_' . self::TAXONOMY_NAME, array( __CLASS__, 'on_organization_added' ));
add_action( 'pre_delete_term', array( __CLASS__, 'on_taxonomy_term_will_be_deleted' ), 10, 2);
add_action('set_object_terms', array( __CLASS__, 'on_taxonomy_term_assigned' ), 10, 4);
add_action('deleted_term_relationships', array( __CLASS__, 'on_taxonomy_term_unassigned' ), 10, 3);
// Remove bulk editor for organizations on users list
remove_filter( 'admin_notices', array( $this, 'bulk_notice'));
remove_filter( 'bulk_actions-users', array( $this, 'bulk_actions'));
remove_filter( 'bulk_actions-users', array( $this, 'bulk_actions_sort'));
remove_action( 'handle_bulk_actions-users', array( $this, 'handle_bulk_actions'));
// remove default organization info from profiles
// it will be handled by custom fields
remove_action( 'show_user_profile', array( $this, 'edit_user_relationships' ), 99);
remove_action( 'edit_user_profile', array( $this, 'edit_user_relationships' ), 99 );
}
// hooks functions
@@ -78,7 +89,7 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
if ($taxonomy === self::TAXONOMY_NAME) {
$user_id = $object_id;
$organization_id = $tt_ids[0];
add_user_meta($user_id, 'organization_id', $organization_id, true);
self::_add_user_to_access_group($user_id, $organization_id);
}
}
@@ -95,7 +106,7 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
if ($taxonomy === self::TAXONOMY_NAME) {
$user_id = $object_id;
$organization_id = $tt_ids[0];
delete_user_meta($user_id, 'organization_id');
self::_remove_user_from_organization_access_groups($user_id, $organization_id);
}
}
@@ -106,13 +117,13 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
* @param null $user_id
* @return mixed
*/
public static function get_user_organization($user_id = null) {
public static function get_user_organization_id($user_id = null) {
if (!isset($user_id)) {
$user = wp_get_current_user();
$user_id = $user->ID;
$user_id = get_current_user_id();
}
$terms = wp_get_object_terms($user_id, self::TAXONOMY_NAME);
return $terms[0];
$organization_id = get_user_meta($user_id, '_wiaas_organization_id', true);
return empty($organization_id) ? null : (int) $organization_id;
}
/**
@@ -124,8 +135,8 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
* @param $user_id
*/
public static function assign_post_to_user_organization($post_id, $user_id) {
$organization = self::get_user_organization($user_id);
self::_assign_post_to_organization($post_id, $organization->term_id);
$organization_id = self::get_user_organization_id($user_id);
self::_assign_post_to_organization($post_id, $organization_id);
}
@@ -240,73 +251,4 @@ class Wiaas_User_Organization extends WP_User_Taxonomy {
}
}
}
/**
* Show organizations selection on new user form
*/
function show_organizations_selection() {
$terms = get_terms( array(
'taxonomy' => self::TAXONOMY_NAME,
'hide_empty' => false,
) );
$taxonomy = get_taxonomy(self::TAXONOMY_NAME);
$this->table_contents(null, $taxonomy, $terms);
}
function edit_user_relationships($user = false) {
$tax = get_taxonomy( $this->taxonomy );
// Get the terms of the taxonomy.
$terms = get_terms( $this->taxonomy, array(
'hide_empty' => false
) );
$this->table_contents( $user, $tax, $terms );
}
function table_contents( $user, $tax, $terms ) {
$active_organization_id = -1;
if ($user) {
$active_organization = self::get_user_organization($user->ID);
$active_organization_id = $active_organization ? $active_organization->term_id : -1;
}
?>
<table class="form-table">
<tbody>
<tr class="form-field">
<th scope="row">
<label for="<?php echo esc_attr( $this->taxonomy ); ?>[]">
<?php echo esc_html( $tax->labels->singular_name ); ?>
</label>
</th>
<td>
<select name="<?php echo esc_attr( $this->taxonomy ); ?>[]" id="<?php echo esc_attr( $this->taxonomy ); ?>">
<?php
foreach ( $terms as $term ) :
$selected = $active_organization_id === $term->term_id;
?>
<option
value="<?php echo esc_attr( $term->slug ); ?>"
<?php selected( $selected ); ?>
>
<?php echo esc_attr( $term->name ); ?>
</option>
<?php
endforeach;
?>
</select>
<?php
wp_nonce_field( $this->taxonomy, $this->get_nonce_key() );
?>
</td>
</tr>
</tbody>
</table>
<?php
}
private function get_nonce_key() {
return "wp_user_taxonomy_{$this->taxonomy}";
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Retrieves name for provided organization_id
* @param int $organization_id
*
* @return string|null
*/
function wiaas_get_organization_name($organization_id) {
$term = get_term($organization_id);
if ($term instanceof WP_Term) {
return $term->name;
}
return null;
}
/**
* Retrieve array of organization role names
*
* @param int $organization_id
*
* @return array Array of organization roles
*/
function wiaas_get_organization_roles($organization_id) {
$roles = get_term_meta($organization_id, '_wiaas_organization_roles', true);
return empty($roles) ? array() : $roles;
}
/**
* @param int $organization_id
* @param array $roles
*/
function wiaas_set_organization_roles($organization_id, $roles) {
update_term_meta($organization_id, '_wiaas_organization_roles', $roles);
}
/**
* Retrieves list of organizations with provided role in [ 'id' => 'name'] format
* @param string $role
*
* @return array
*/
function wiaas_get_organizations_with_role($role) {
$terms = get_terms(array(
'taxonomy' => Wiaas_User_Organization::TAXONOMY_NAME,
'meta_key' => '_wiaas_organization_roles',
'meta_value' => $role,
'fields' => 'id=>name',
'meta_compare' => 'LIKE',
'hide_empty' => false
));
return is_array($terms) ? $terms : array();
}
/**
* Retrieves list of commercial lead organizations in [ 'id' => 'name' ] format
*
* @return array
*/
function wiaas_get_commercial_leads() {
return wiaas_get_organizations_with_role('commercial_lead');
}
/**
* Retrieves list of customer organizations in [ 'id' => 'name'] format
*
* @return array
*/
function wiaas_get_customers() {
return wiaas_get_organizations_with_role('customer');
}
/**
* Retrieves list of supplier organizations in [ 'id' => 'name'] format
*
* @return array
*/
function wiaas_get_suppliers() {
return wiaas_get_organizations_with_role('supplier');
}
/**
* Retrieves id of organization for provided user_id
*
* @param int $user_id
*
* @return int|null
*/
function wiaas_get_user_organization_id($user_id) {
$organization_id = get_user_meta($user_id, '_wiaas_organization_id', true);
return empty($organization_id) ? null : (int) $organization_id;
}
/**
* Retrieves id of current user organization
*
* @return int|null
*/
function wiaas_get_current_user_organization_id() {
return wiaas_get_user_organization_id(get_current_user_id());
}

View File

@@ -20,17 +20,36 @@ require_once $_tests_dir . '/includes/functions.php';
#load setup
tests_add_filter( 'muplugins_loaded', 'load_wiaas_test_setup' );
tests_add_filter( 'pre_option_active_plugins', 'load_active_plugins_list');
# Start up the WP testing environment.
require $_tests_dir . '/includes/bootstrap.php';
# Require Wiaas Unit Test case class
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/tests/wiaas-unit-test-case.php';
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/tests/wiaas-api-unit-test-case.php';
function load_active_plugins_list() {
return array(
'woocommerce/woocommerce.php',
'woocommerce-product-bundles/woocommerce-product-bundles.php',
'woocommerce-jetpack/woocommerce-jetpack.php',
'jwt-authentication-for-wp-rest-api/jwt-auth.php',
'gravityforms/gravityforms.php',
'gravityflow/gravityflow.php',
'groups/groups.php',
'wp-user-groups/wp-user-groups.php',
'wiaas/wiaas.php'
);
}
function load_wiaas_test_setup() {
# Activate plugins needed for testing
require_once '/tmp/wiaas-backend-test/app/plugins/woocommerce/woocommerce.php';
require_once '/tmp/wiaas-backend-test/app/plugins/woocommerce-product-bundles/woocommerce-product-bundles.php';
require_once '/tmp/wiaas-backend-test/app/plugins/gravityforms/gravityforms.php';
require_once '/tmp/wiaas-backend-test/app/plugins/gravityflow/gravityflow.php';
@@ -42,7 +61,8 @@ function load_wiaas_test_setup() {
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/wiaas.php';
# Require classes needed for db updates
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/includes/class-wiaas-db-update.php';
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/includes/db-updates/wiaas-db-update-functions.php';
require_once '/tmp/wiaas-backend-test/app/plugins/wiaas/includes/db-updates/wiaas-db-update-general.php';
}

View File

@@ -0,0 +1,81 @@
<?php
class Wiaas_Order_Project_API_Test extends Wiaas_API_Unit_Test_Case {
function setUp() {
parent::setUp();
}
/**
* @covers Wiaas_Order_Projects_API::get_order_projects()
*/
function test_get_order_projects_as_guest() {
$this->check_endpoint_forbidden_for_guest(
new WP_REST_Request( 'GET', '/wiaas/order-projects')
);
}
/**
* @covers Wiaas_Order_Projects_API::get_order_projects()
*/
function test_get_order_projects_as_customer() {
Wiaas_Order_Project::add_order_project('Test Available 1', true);
Wiaas_Order_Project::add_order_project('Test Available 2', true);
$customer_id = $this->create_new_customer();
wp_set_current_user($customer_id);
$data = $this->dispatch_endpoint_request(
new WP_REST_Request( 'GET', '/wiaas/order-projects')
);
$this->assertNotNull($data);
$this->assertTrue(is_array($data));
$this->assertCount(2, $data);
foreach ($data as $project) {
$this->assertArrayHasKey('id', $project);
$this->assertArrayHasKey('name', $project);
$this->assertContains($project['name'], array(
'Test Available 1',
'Test Available 2',
));
}
}
/**
* @covers Wiaas_Order_Projects_API::create_order_project()
*/
function test_create_order_project_as_guest() {
$request = new WP_REST_Request( 'POST', '/wiaas/order-projects');
$request->set_body_params(array(
'name' => 'Test'
));
$this->check_endpoint_forbidden_for_guest($request);
}
/**
* @covers Wiaas_Order_Projects_API::create_order_project()
*/
function test_create_valid_order_project_as_customer() {
$customer_id = $this->create_new_customer();
wp_set_current_user($customer_id);
$request = new WP_REST_Request( 'POST', '/wiaas/order-projects');
$request->set_body_params(array(
'name' => 'Test Project'
));
$data = $this->dispatch_endpoint_request($request);
$this->assertNotNull($data);
$this->assertTrue(is_array($data));
$this->assertArrayHasKey('messages', $data);
$this->assertNotEmpty($data['messages']);
$message = $data['messages'][0];
$this->assertArrayHasKey('code', $message);
$this->assertEquals('success', $message['code']);
}
}

View File

@@ -0,0 +1,597 @@
<?php
/**
* Wiaas_Customer_Test
*
* @package Wiaas
*/
class Wiass_REST_Customer_Api_Test extends Wiaas_Unit_Test_Case {
protected $server;
function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new \WP_REST_Server;
do_action( 'rest_api_init' );
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_update_customer_profile_addresses_as_guest() {
wp_set_current_user(0);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/0/profile-addresses');
$request->set_body_params(array(
'profile_address' => $dummy_address
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_add_customer_profile_addresses_with_valid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0]['city'], $dummy_address['city']);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_ADDRESS_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_profile_addresses
*/
function test_add_customer_profile_addresses_with_invalid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$dummy_address['zip_code'] = 'this is not a zip code';
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_ADDRESS_NOT_CHANGED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_update_customer_billing_addresses_as_guest() {
wp_set_current_user(0);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/0/billing-addresses');
$request->set_body_params(array(
'billing_address' => $dummy_address
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_add_customer_billing_addresses_with_valid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0]['city'], $dummy_address['city']);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'BILLING_ADDRESS_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_billing_addresses
*/
function test_add_customer_billing_addresses_with_invalid_address() {
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$dummy_address['zip_code'] = 'this is not a zip code';
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'BILLING_ADDRESS_NOT_CHANGED');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_billing_addresses
*/
function test_delete_customer_billing_addresses_as_guest() {
$address_id = self::insert_dummy_billing_address();
wp_set_current_user(0);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/billing-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_billing_addresses
*/
function test_delete_customer_billing_addresses() {
$address_id = self::insert_dummy_billing_address();
wp_set_current_user(1);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/billing-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('billing_addresses', $profile_info);
$this->assertEquals($profile_info['billing_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADDRESS_REMOVED');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_profile_addresses
*/
function test_delete_customer_delivery_addresses_as_guest() {
$address_id = self::insert_dummy_profile_address();
wp_set_current_user(0);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/profile-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::delete_customer_profile_addresses
*/
function test_delete_customer_profile_addresses() {
$address_id = self::insert_dummy_profile_address();
wp_set_current_user(1);
$request = new WP_REST_Request( 'DELETE', '/wiaas/customer/1/profile-addresses/' . $address_id);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('profile_addresses', $profile_info);
$this->assertEquals($profile_info['profile_addresses'][0], NULL);
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADDRESS_REMOVED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => 11111
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_with_empty_phone() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => ''
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertEquals($profile_info['phone'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_PHONE_NUMBER');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info_with_empty_name() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => '',
'last_name' => '',
'phone' => '23232'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertEquals($profile_info['phone'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_NAME');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_personal_info
*/
function test_update_customer_personal_info() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/personal-info');
$request->set_body_params(array(
'first_name' => 'Trunks',
'last_name' => 'Goten',
'phone' => '3434'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('phone', $profile_info);
$this->assertArrayHasKey('name', $profile_info);
$this->assertEquals($profile_info['phone'], '3434');
$this->assertEquals($profile_info['name'], 'Trunks Goten');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'PROFILE_UPDATED');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => '12345'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_with_empty_company_name() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => '',
'vat_code' => '12345'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], '');
$this->assertEquals($profile_info['vat_code'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_COMPANY_NAME');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info_with_empty_vat() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => ''
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], '');
$this->assertEquals($profile_info['vat_code'], '');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'ADD_VAT');
}
/**
* @covers Wiass_REST_Customer_API::update_customer_company_info
*/
function test_update_customer_company_info() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/company-info');
$request->set_body_params(array(
'company_name' => 'Saburly',
'vat_code' => '123'
));
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertArrayHasKey('data', $data);
$this->assertArrayHasKey('messages', $data);
$profile_info = $data['data'];
$messages = $data['messages'][0];
$this->assertArrayHasKey('company_name', $profile_info);
$this->assertArrayHasKey('vat_code', $profile_info);
$this->assertEquals($profile_info['company_name'], 'Saburly');
$this->assertEquals($profile_info['vat_code'], '123');
$this->assertArrayHasKey('message', $messages);
$this->assertEquals($messages['message'], 'COMPANY_UPDATED');
}
//Helper functions
private function create_dummy_address(){
return array(
'country_name' => 'Sweden',
'delivery_mail' => 'delivery@email.com',
'id_country_selected' => 1,
'city' => 'Stockholm',
'detailed_address' => 'Dummy Street 7',
'zip_code' => 124443,
'first_name' => 'Tester',
'last_name' => 'Retset',
'invoice_mail' => 'invoice@mail.com'
);
}
private function insert_dummy_billing_address(){
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/billing-addresses');
$request->set_body_params(array(
'billing_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
return $response->get_data()['data']['billing_addresses'][0]['id'];
}
private function insert_dummy_profile_address(){
wp_set_current_user(1);
$dummy_address = self::create_dummy_address();
$request = new WP_REST_Request( 'PUT', '/wiaas/customer/1/profile-addresses');
$request->set_body_params(array(
'profile_address' => json_encode($dummy_address)
));
$response = $this->server->dispatch( $request );
return $response->get_data()['data']['profile_addresses'][0]['id'];
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Wiaas_Delivery_Process_Step_Test
*
* @package Wiaas
*/
class Wiass_REST_User_Api_Test extends Wiaas_Unit_Test_Case {
protected $server;
function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new \WP_REST_Server;
do_action( 'rest_api_init' );
}
/**
* @covers Wiass_REST_User_API::validate_token
*/
function test_validate_token_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'POST', '/wiaas/user/validate-token');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_User_API::validate_token
*/
function test_validate_token_with_valid_user() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'POST', '/wiaas/user/validate-token');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$user_info = $response->get_data()['userInfo'];
$this->assertNotNull($user_info);
$this->assertTrue(is_array($user_info));
$this->assertArrayHasKey('wiaas_id_user', $user_info);
$this->assertArrayHasKey('wiaas_is_company_admin', $user_info);
$this->assertArrayHasKey('wiaas_user_full_name', $user_info);
$this->assertArrayHasKey('wiaas_user_type', $user_info);
$this->assertArrayHasKey('wiaas_username', $user_info);
$this->assertEquals($user_info['wiaas_id_user'], '1');
$this->assertEquals($user_info['wiaas_is_company_admin'], '1');
$this->assertEquals($user_info['wiaas_username'], 'admin');
}
/**
* @covers Wiass_REST_User_API::get_countries
*/
function test_get_countries_as_guest() {
wp_set_current_user(0);
$request = new WP_REST_Request( 'GET', '/wiaas/user/get-countries');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* @covers Wiass_REST_User_API::get_countries
*/
function test_get_countries() {
wp_set_current_user(1);
$request = new WP_REST_Request( 'GET', '/wiaas/user/get-countries');
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertFalse($response->is_error());
$this->assertEquals($response->get_status(), 200);
$data = $response->get_data();
$this->assertNotNull($data);
$this->assertTrue(is_array($data));
$country = $data[0];
$this->assertNotNull($country);
$this->assertTrue(is_array($country));
$this->assertArrayHasKey('country_id', $country);
$this->assertArrayHasKey('country_name', $country);
}
}

View File

@@ -0,0 +1,120 @@
<?php
class Wiaas__Package_Status_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Package_Status::register_package_status_taxonomy()
* @covers Wiaas_Package_Status::get_available_package_statuses()
*/
function test_register_package_status_taxonomy() {
$taxonomy = get_taxonomy('package_status');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
$package_statuses = Wiaas_Package_Status::get_available_package_statuses();
$this->assertNotEmpty($package_statuses);
$this->assertContains(Wiaas_Package_Status::AVAILABLE, $package_statuses);
}
/**
* @covers Wiaas_Package_Type::set_package_status()
* @covers Wiaas_Package_Type::get_package_status()
*/
function test_adding_package_status() {
$package = $this->create_new_package();
Wiaas_Package_Status::set_package_status($package->get_id(), Wiaas_Package_Status::AVAILABLE);
$package_status = Wiaas_Package_Status::get_package_status($package->get_id());
$this->assertNotNull($package_status);
$this->assertEquals($package_status, Wiaas_Package_Status::AVAILABLE);
}
/**
* Test package status update on simple product price update
*/
function test_package_status_update_on_simple_product_price_update() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20);
$this->add_product_category($product2, 'software');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 100
),
'managed_36' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 100,
'minimal_services_price' => 100
)
);
$commision = 50;
$cost_margin = 100;
Wiaas_Package_Pricing::set_package_prices($package, $pricing_rules, $commision, $cost_margin);
$this->assertEquals(Wiaas_Package_Status::get_package_status($package)->get_id(), Wiaas_Package_Status::AVAILABLE);
$product1->set_price(1000);
$this->assertEquals(Wiaas_Package_Status::get_package_status($package)->get_id(), Wiaas_Package_Status::MARGIN_EXCEEDED);
}
/**
* Test package status update on cost margin update
*/
function test_package_status_update_on_margin_cost_update() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20);
$this->add_product_category($product2, 'software');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 100
),
'managed_36' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 100,
'minimal_services_price' => 100
)
);
$commision = 50;
$cost_margin = 0;
Wiaas_Package_Pricing::set_package_prices($package, $pricing_rules, $commision, $cost_margin);
$this->assertEquals(Wiaas_Package_Status::get_package_status($package)->get_id(), Wiaas_Package_Status::AVAILABLE);
$cost_margin = 1;
Wiaas_Package_Pricing::set_package_prices($package, $pricing_rules, $commision, $cost_margin);
$this->assertEquals(Wiaas_Package_Status::get_package_status($package)->get_id(), Wiaas_Package_Status::MARGIN_EXCEEDED);
}
}

View File

@@ -0,0 +1,39 @@
<?php
class Wiaas_Package_Addon_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Package_Addon::register_addon_package_type()
*/
function test_addon_package_type_registered() {
$package_types = Wiaas_Package_Type::get_available_package_types();
$this->assertContains('add_on', $package_types);
}
/**
* @covers Wiaas_Package_Addon::set_package_addons()
* @covers Wiaas_Package_Addon::get_package_addons()
*/
function test_adding_package_addons() {
$package = $this->create_new_package();
$addon1 = $this->create_new_package();
$addon2 = $this->create_new_package();
$addons_ids = array(
$addon1->get_id(),
$addon2->get_id()
);
Wiaas_Package_Addon::set_package_addons($package, $addons_ids);
$added_addons = Wiaas_Package_Addon::get_package_addons($package);
$this->assertNotEmpty($added_addons);
$this->assertCount(2, $added_addons);
foreach ($added_addons as $added_addon) {
$this->assertTrue(in_array($added_addon->get_id(), $addons_ids));
}
}
}

View File

@@ -0,0 +1,100 @@
<?php
class Wiaas_Package_Option_Groups_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Package_Option_Groups::register_option_package_type()
*/
function test_option_package_type_registered() {
$package_types = Wiaas_Package_Type::get_available_package_types();
$this->assertContains('option', $package_types);
}
/**
* @covers Wiaas_Package_Option_Groups::set_package_option_groups()
* @covers Wiaas_Package_Option_Groups::get_package_option_groups()
*/
function test_adding_package_option_group() {
$package = $this->create_new_package();
$option_package1 = $this->create_new_package();
Wiaas_Package_Type::set_package_type($option_package1->get_id(), 'option');
$option_package2 = $this->create_new_package();
Wiaas_Package_Type::set_package_type($option_package2->get_id(), 'option');
$option_group1 = array(
'id' => 'option1',
'name' => 'Option 1',
'default' => $option_package1->get_id(),
'options' => array( $option_package1->get_id() )
);
$option_group2 = array(
'id' => 'option2',
'name' => 'Option 2',
'default' => $option_package2->get_id(),
'options' => array( $option_package2->get_id() )
);
Wiaas_Package_Option_Groups::set_package_option_groups($package, array(
$option_group1,
$option_group2
));
$added_option_groups = Wiaas_Package_Option_Groups::get_package_option_groups($package);
$this->assertNotEmpty($added_option_groups);
$this->assertCount(2, $added_option_groups);
foreach ($added_option_groups as $index => $added_option_group) {
$this->assertNotEmpty($added_option_group);
$this->assertArrayHasKey('id', $added_option_group);
$this->assertArrayHasKey('name', $added_option_group);
$this->assertArrayHasKey('default', $added_option_group);
$this->assertArrayHasKey('options', $added_option_group);
$this->assertEquals($added_option_group['id'], 'option' . ($index + 1));
$this->assertEquals($added_option_group['name'], 'Option ' . ($index + 1));
$this->assertCount(1, $added_option_group['options']);
$added_option = $added_option_group['options'][0];
$this->assertNotNull($added_option);
$relevant_option = null;
if ($index === 0) {
$relevant_option = $option_package1;
} else {
$relevant_option = $option_package2;
}
$this->assertEquals($added_option_group['default'], $relevant_option->get_id());
$this->assertEquals($added_option->get_id(), $relevant_option->get_id());
}
}
/**
* @covers Wiaas_Package_Option_Groups::get_group_name_for_package_option()
*/
function test_get_group_name_for_package_option() {
$package = $this->create_new_package();
$option_package = $this->create_new_package();
Wiaas_Package_Type::set_package_type($option_package->get_id(), 'option');
$option_group = array(
'id' => 'option1',
'name' => 'Option 1',
'default' => $option_package->get_id(),
'options' => array( $option_package->get_id() )
);
Wiaas_Package_Option_Groups::set_package_option_groups($package, array( $option_group ));
$option_group_name = Wiaas_Package_Option_Groups::get_group_name_for_package_option($package, $option_package);
$this->assertEquals($option_group_name, $option_group['name']);
}
}

View File

@@ -0,0 +1,35 @@
<?php
class Wiaas__Package_Type_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Package_Type::register_package_type_taxonomy()
* @covers Wiaas_Package_Type::get_available_package_types()
*/
function test_register_package_type_taxonomy() {
$taxonomy = get_taxonomy('package_type');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
$package_types = Wiaas_Package_Type::get_available_package_types();
$this->assertNotEmpty($package_types);
$this->assertContains('standard', $package_types);
}
/**
* @covers Wiaas_Package_Type::set_package_type()
* @covers Wiaas_Package_Type::get_package_type()
*/
function test_adding_package_type() {
$package = $this->create_new_package();
Wiaas_Package_Type::set_package_type($package->get_id(), 'standard');
$package_type = Wiaas_Package_Type::get_package_type($package->get_id());
$this->assertNotNull($package_type);
$this->assertEquals($package_type, 'standard');
}
}

View File

@@ -0,0 +1,162 @@
<?php
class Wiaas_Package_CL_Pricing_Test extends Wiaas_Unit_Test_Case {
var $shop_owner_id, $customer_id, $package_id, $cl_extras;
function setUp() {
parent::setUp();
$this->shop_owner_id = wp_insert_term(
'Shop owner organization',
Wiaas_User_Organization::TAXONOMY_NAME)['term_id'];
$this->customer_id = wp_insert_term(
'Customer Organization',
Wiaas_User_Organization::TAXONOMY_NAME)['term_id'];
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $this->create_new_product()));
$this->package_id = $package->get_id();
$this->cl_extras = array(
'purchase_default' => array(
'fixed' => 10,
'recurrent' => 10,
'services' => 10,
'visible' => true
),
'purchase_24_default' => array(
'fixed' => 10,
'recurrent' => 10,
'services' => 10,
'visible' => true
),
'managed_36_default' => array(
'fixed' => 10,
'recurrent' => 10,
'services' => 10,
'visible' => true
)
);
}
/**
* @covers Wiaas_Package_CL_Pricing::set_extras()
*/
function test_packages_extras_set() {
Wiaas_Package_CL_Pricing::set_extras(
$this->shop_owner_id,
$this->package_id,
$this->cl_extras);
// validate data saved
$cl_extras = get_term_meta(
$this->shop_owner_id,
'_wiaas_cm_extras_' . $this->package_id,
true);
$this->_validate_default_cl_extras($cl_extras);
}
/**
* @covers Wiaas_Package_CL_Pricing::get_extras()
*/
function test_package_extras_retrieved() {
update_term_meta(
$this->shop_owner_id,
'_wiaas_cm_extras_' . $this->package_id,
$this->cl_extras);
$cl_extras = Wiaas_Package_CL_Pricing::get_extras($this->shop_owner_id, $this->package_id);
$this->_validate_default_cl_extras($cl_extras);
}
/**
* @covers Wiaas_Package_CL_Pricing::get_extras_for_customer()
*/
function test_default_extras_retrieved_for_customer() {
update_term_meta(
$this->shop_owner_id,
'_wiaas_cm_extras_' . $this->package_id,
$this->cl_extras);
$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());
foreach ($pay_types as $pay_type) {
$customer_cl_extra = Wiaas_Package_CL_Pricing::get_extras_for_customer(
$this->shop_owner_id,
$pay_type,
$this->package_id,
$this->customer_id);
$this->assertNotNull($customer_cl_extra);
$this->assertEquals(10, $customer_cl_extra['fixed']);
$this->assertEquals(10, $customer_cl_extra['recurrent']);
$this->assertEquals(10, $customer_cl_extra['services']);
}
}
/**
* @covers Wiaas_Package_CL_Pricing::get_extras_for_customer()
*/
function test_customer_specific_extras_retrieved_for_customer() {
// append customer specific extras for purchase payment type
$this->cl_extras['purchase_customer_' . $this->customer_id] = array(
'fixed' => 100,
'recurrent' => 100,
'services' => 100,
'visible' => true
);
// set prices extras
update_term_meta(
$this->shop_owner_id,
'_wiaas_cm_extras_' . $this->package_id,
$this->cl_extras);
// test that only extras are retrieved for purchase payment type
// and the rest are not retrieved
$pay_types = array_keys(Wiaas_Package_Pricing::get_available_pay_types());
foreach ($pay_types as $pay_type) {
$customer_cl_extra = Wiaas_Package_CL_Pricing::get_extras_for_customer(
$this->shop_owner_id,
$pay_type,
$this->package_id,
$this->customer_id);
if ($pay_type === 'purchase') {
$this->assertNotNull($customer_cl_extra);
$this->assertEquals(100, $customer_cl_extra['fixed']);
$this->assertEquals(100, $customer_cl_extra['recurrent']);
$this->assertEquals(100, $customer_cl_extra['services']);
} else {
$this->assertNull($customer_cl_extra);
}
}
}
// HELPERS
private function _validate_default_cl_extras($cl_extras) {
$this->assertNotEmpty($cl_extras);
$this->assertArrayHasKey('purchase_default', $cl_extras);
$this->assertArrayHasKey('purchase_24_default', $cl_extras);
$this->assertArrayHasKey('managed_36_default', $cl_extras);
foreach ($cl_extras as $cl_extra) {
$this->assertEquals(10, $cl_extra['fixed']);
$this->assertEquals(10, $cl_extra['recurrent']);
$this->assertEquals(10, $cl_extra['services']);
$this->assertTrue($cl_extra['visible']);
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
class Wiaas_Package_Pricing_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Package_Pricing::set_package_prices()
* @covers Wiaas_Package_Pricing::get_package_prices()
*/
function test_set_and_get_package_prices() {
$package = $this->create_new_package();
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 10,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 10,
'principal_amount' => 0,
'minimal_services_price' => 10
),
'managed_36' => array(
'minimal_fixed_price' => 10,
'principal_amount' => 10,
'minimal_services_price' => 10
)
);
$commision = 60;
$cost_margin = 0;
Wiaas_Package_Pricing::set_package_prices($package, $pricing_rules, $commision, $cost_margin);
$configured_prices = Wiaas_Package_Pricing::get_package_prices($package);
$this->assertCount(3, $configured_prices);
$this->assertArrayHasKey('purchase', $configured_prices);
$this->assertArrayHasKey('purchase_24', $configured_prices);
$this->assertArrayHasKey('managed_36', $configured_prices);
foreach ($configured_prices as $type => $configured_price) {
$this->assertArrayHasKey('id', $configured_price);
$this->assertArrayHasKey('payment_type', $configured_price);
$this->assertArrayHasKey('max_contract_period', $configured_price);
$this->assertArrayHasKey('package_pay_period', $configured_price);
$this->assertArrayHasKey('period_unit', $configured_price);
$this->assertArrayHasKey('services_contract_period', $configured_price);
$this->assertArrayHasKey('commision_split', $configured_price);
$this->assertArrayHasKey('minimal_fixed_price', $configured_price);
$this->assertArrayHasKey('principal_amount', $configured_price);
$this->assertArrayHasKey('minimal_services_price', $configured_price);
$this->assertEquals($configured_price['id'], $type);
$this->assertEquals($configured_price['commision_split'], $commision / 100);
$this->assertEquals($configured_price['minimal_fixed_price'], $pricing_rules[$type]['minimal_fixed_price']);
$this->assertEquals($configured_price['principal_amount'], $pricing_rules[$type]['principal_amount']);
$this->assertEquals($configured_price['minimal_services_price'], $pricing_rules[$type]['minimal_services_price']);
}
}
}

View File

@@ -0,0 +1,74 @@
<?php
class Wiaas_Product_Pricing_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Product_Pricing::set_product_price()
* @covers Wiaas_Product_Pricing::get_product_price()
*/
function test_adding_product_price() {
$product = $this->create_new_product(10, true, 2);
$configured_price = Wiaas_Product_Pricing::get_product_price($product);
$this->assertNotNull($configured_price);
$this->assertArrayHasKey('price', $configured_price);
$this->assertArrayHasKey('is_recurring', $configured_price);
$this->assertArrayHasKey('pay_period', $configured_price);
$this->assertEquals($configured_price['price'], 10);
$this->assertEquals($configured_price['is_recurring'], true);
$this->assertEquals($configured_price['pay_period'], 2);
}
/**
* @covers Wiaas_Product_Pricing::get_product_price_html()
*/
function test_get_product_fixed_price_html() {
$product = $this->create_new_product();
$original_price_html = $product->get_price_html();
$price_html = Wiaas_Product_Pricing::get_product_price_html($original_price_html, $product);
$this->assertEquals($price_html, $original_price_html);
}
/**
* @covers Wiaas_Product_Pricing::get_product_price_html()
*/
function test_get_product_recurrent_price_html() {
$product = $this->create_new_product(10, true, 1);
$original_price_html = $product->get_price_html();
$price_html = Wiaas_Product_Pricing::get_product_price_html($original_price_html, $product);
$this->assertEquals($price_html, $original_price_html . ' / month');
}
/**
* @covers Wiaas_Product_Pricing::get_product_fixed_price()
*/
function test_get_fixed_price_for_fixed_product() {
$product = $this->create_new_product();
$original_price = $product->get_price();
$fixed_price = Wiaas_Product_Pricing::get_product_fixed_price($original_price, $product);
$this->assertEquals($fixed_price, $original_price);
}
/**
* @covers Wiaas_Product_Pricing::get_product_fixed_price()
*/
function test_get_fixed_price_for_recurring_product() {
$product = $this->create_new_product(10, true, 1);
$fixed_price = Wiaas_Product_Pricing::get_product_fixed_price($product->get_price(), $product);
$this->assertEquals($fixed_price, 0);
}
}

View File

@@ -0,0 +1,388 @@
<?php
class Wiaas_Authentication_Test extends Wiaas_Unit_Test_Case {
var $user_id, $organization_id, $request_uri;
public function setUp() {
parent::setUp();
// set admin as current user
wp_set_current_user(1);
// create testing user
$this->user_id = wp_create_user('test', 'test', 'test@mail.com');
// create organization
$this->organization_id = wp_insert_term(
'test_organization',
Wiaas_User_Organization::TAXONOMY_NAME
)['term_id'];
update_user_meta($this->user_id, '_wiaas_organization_id', $this->organization_id);
# assign user to organization
wp_set_terms_for_user(
$this->user_id,
Wiaas_User_Organization::TAXONOMY_NAME,
[$this->organization_id]);
wp_set_current_user($this->user_id);
$this->request_uri = $_SERVER['REQUEST_URI'];
}
function tearDown() {
parent::tearDown();
wp_set_current_user(1);
wp_delete_user($this->user_id);
wp_delete_term(
$this->organization_id,
Wiaas_User_Organization::TAXONOMY_NAME);
delete_user_meta($this->user_id, '_wiaas_organization_id');
delete_user_meta($this->user_id, '_wiaas_current_user_admin_role');
$_SERVER['REQUEST_URI'] = $this->request_uri;
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_user_authentication_fail_when_no_selected_role() {
$this->assertFalse(
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
$this->assertTrue(
is_wp_error(
Wiaas_Authentication::authenticate_user_on_login(wp_get_current_user())
)
);
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_user_authentication_forwards_error() {
// add roles to organization
$organization_roles = array( 'supplier', 'customer' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', 'supplier');
$this->assertFalse(
Wiaas_Authentication::authenticate_current_user(false)
);
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_current_user_authentication_fail_when_organization_has_no_roles() {
$roles = array('administrator', 'supplier', 'customer', 'commercial_lead');
foreach ($roles as $role) {
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', $role);
$this->assertFalse(
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
}
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_current_user_authentication_fail_when_organization_has_different_roles() {
// add roles to organization
$organization_roles = array( 'supplier', 'customer' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$user_roles = array('administrator', 'commercial_lead');
foreach ($user_roles as $user_role) {
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', $user_role);
$this->assertFalse(
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
}
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_current_user_authentication_valid_when_organization_has_requested_role() {
// add roles to organization
$organization_roles = array( 'administrator', 'commercial_lead' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$user_roles = $organization_roles;
foreach ($user_roles as $user_role) {
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', $user_role);
$this->assertEquals(
$this->user_id,
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
}
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_current_user_authentication_invalid_when_organization_has_no_customer_role() {
// add roles to organization
$organization_roles = array( 'administrator', 'commercial_lead' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$user_roles = $organization_roles;
$_SERVER['REQUEST_URI'] = get_home_url('') . '/' . rest_get_url_prefix();
foreach ($user_roles as $user_role) {
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', $user_role);
$this->assertFalse(
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
}
}
/**
* @covers Wiaas_Authentication::authenticate_current_user()
* @group authentication
*/
function test_current_user_authentication_valid_when_organization_has_customer_role() {
// add roles to organization
$organization_roles = array( 'administrator', 'commercial_lead', 'customer' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$user_roles = $organization_roles;
$_SERVER['REQUEST_URI'] = get_home_url('') . '/' . rest_get_url_prefix();
foreach ($user_roles as $user_role) {
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', $user_role);
$this->assertEquals(
$this->user_id,
Wiaas_Authentication::authenticate_current_user($this->user_id)
);
}
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_fails_if_no_role_posted() {
$user = wp_get_current_user();
$error = Wiaas_Authentication::authenticate_user_on_login($user);
$this->assertTrue(is_wp_error($error));
$this->assertEquals('You must selected role to login!', $error->get_error_message());
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_does_nothing_if_rest_request() {
$_SERVER['REQUEST_URI'] = get_home_url('') . '/' . rest_get_url_prefix();
$user = wp_get_current_user();
$response_user = Wiaas_Authentication::authenticate_user_on_login($user);
$this->assertEquals(
$user->ID,
$response_user->ID
);
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_fails_if_customer_role_requested() {
$user = wp_get_current_user();
$_POST['role'] = 'customer';
$error = Wiaas_Authentication::authenticate_user_on_login($user);
$this->assertTrue(is_wp_error($error));
$this->assertEquals('No access!', $error->get_error_message());
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_fails_when_user_has_no_organization() {
$_POST['role'] = 'supplier';
delete_user_meta($this->user_id, '_wiaas_organization_id');
$error = Wiaas_Authentication::authenticate_user_on_login(wp_get_current_user());
$this->assertTrue(is_wp_error($error));
$this->assertEquals('Account not completed!', $error->get_error_message());
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_fails_when_organization_has_no_roles() {
$_POST['role'] = 'supplier';
$error = Wiaas_Authentication::authenticate_user_on_login(wp_get_current_user());
$this->assertTrue(is_wp_error($error));
$this->assertEquals('Your account is not authorized for requested role. Please contact us for help.', $error->get_error_message());
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_fails_when_organization_has_different_roles() {
// add roles to organization
$organization_roles = array( 'supplier', 'customer' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$_POST['role'] = 'commercial_lead';
$error = Wiaas_Authentication::authenticate_user_on_login(wp_get_current_user());
$this->assertTrue(is_wp_error($error));
$this->assertEquals('Your account is not authorized for requested role. Please contact us for help.', $error->get_error_message());
}
/**
* @covers Wiaas_Authentication::authenticate_user_on_login()
* @group authentication
*/
function test_login_authentication_valid_when_organization_has_requested_role() {
// add roles to organization
$organization_roles = array( 'administrator', 'commercial_lead' );
update_term_meta($this->organization_id, '_wiaas_organization_roles', $organization_roles);
$user_roles = $organization_roles;
foreach ($user_roles as $user_role) {
$_POST['role'] = $user_role;
$response_user = Wiaas_Authentication::authenticate_user_on_login(wp_get_current_user());
$this->assertEquals(
$this->user_id,
$response_user->ID
);
}
}
/**
* @covers Wiaas_Authentication::maybe_filter_user_roles()
* @group authentication
*/
function test_user_has_customer_role_on_rest_request() {
$_SERVER['REQUEST_URI'] = get_home_url('') . '/' . rest_get_url_prefix();
global $wpdb;
$user_roles = Wiaas_Authentication::maybe_filter_user_roles(
null, $this->user_id,
$wpdb->get_blog_prefix() . 'capabilities'
);
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$user_roles = $user_roles[0];
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$this->assertArrayHasKey('customer', $user_roles);
$this->assertTrue($user_roles['customer']);
}
/**
* @covers Wiaas_Authentication::maybe_filter_user_roles()
* @group authentication
*/
function test_user_has_no_role_if_not_selected() {
global $wpdb;
$user_roles = Wiaas_Authentication::maybe_filter_user_roles(
null, $this->user_id,
$wpdb->get_blog_prefix() . 'capabilities'
);
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$user_roles = $user_roles[0];
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$this->assertEmpty(array_keys($user_roles)[0]);
}
/**
* @covers Wiaas_Authentication::maybe_filter_user_roles()
* @group authentication
*/
function test_user_has_selected_role() {
global $wpdb;
update_user_meta($this->user_id, '_wiaas_current_user_admin_role', 'supplier');
$user_roles = Wiaas_Authentication::maybe_filter_user_roles(
null, $this->user_id,
$wpdb->get_blog_prefix() . 'capabilities'
);
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$user_roles = $user_roles[0];
$this->assertNotNull($user_roles);
$this->assertCount(1, $user_roles);
$this->assertArrayHasKey('supplier', $user_roles);
$this->assertTrue($user_roles['supplier']);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Class Wiaas_Countries_Test
*/
class Wiaas_Countries_Test extends Wiaas_Unit_Test_Case {
var $product, $package, $current_country = 'Sweden';
public function setUp() {
parent::setUp();
# set admin as current user
wp_set_current_user(1);
$this->product = $this->create_new_product();
wp_set_object_terms($this->product->get_id(), $this->current_country, 'product_country', false);
clean_object_term_cache( $this->product->get_id(), 'product_country' );
$this->package = $this->create_new_package();
wp_set_object_terms($this->package->get_id(), $this->current_country, 'product_country', false);
clean_object_term_cache( $this->package->get_id(), 'product_country' );
}
/**
* @covers Wiaas_Countries::register_product_countries_taxonomy()
*/
function test_available_countries_created() {
// test taxonomy is available
$taxonomy = get_taxonomy('product_country');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
$country_names = array_map(function($term) {
return $term->name;
}, get_terms(array( 'taxonomy' => 'product_country', 'hide_empty' => false )));
$this->assertNotEmpty($country_names);
$this->assertContains('Sweden', $country_names);
$this->assertContains('Denmark', $country_names);
$this->assertContains('Finland', $country_names);
}
/**
* @covers Wiaas_Countries::get_product_country()
*/
function test_get_product_country() {
$retrieved_country = Wiaas_Countries::get_product_country($this->product);
$this->assertNotNull($retrieved_country, 'Product has not country!');
$this->assertEquals($retrieved_country['name'], $this->current_country, 'Retrieved product country is incorrect!');
}
/**
* @covers Wiaas_Countries::get_package_country()
*/
function test_get_package_country() {
$retrieved_country = Wiaas_Countries::get_package_country($this->package);
$this->assertNotNull($retrieved_country, 'Package has not country!');
$this->assertEquals($retrieved_country['name'], $this->current_country, 'Retrieved package country is incorrect!');
}
}

View File

@@ -0,0 +1,84 @@
<?php
class Wiaas_Order_Project_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Order_Project::register_order_project_taxonomy()
*/
function test_order_project_taxonomy_created() {
$taxonomy = get_taxonomy('shop_order_project');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
}
/**
* @covers Wiaas_Order_Project::add_order_project()
*/
function test_adding_order_project() {
Wiaas_Order_Project::add_order_project('Test', true);
$added_order_project = get_term_by('name', 'Test', 'shop_order_project');
$this->assertInstanceOf(WP_Term::class, $added_order_project);
$this->assertEquals($added_order_project->name, 'Test');
$saved_available_flag = get_term_meta($added_order_project->term_id, '_wiaas_is_available', true);
$this->assertEquals('yes', $saved_available_flag);
}
/**
* @covers Wiaas_Order_Project::is_order_project_available()
*/
function test_is_order_project_available() {
Wiaas_Order_Project::add_order_project('Test', true);
$added_order_project = get_term_by('name', 'Test', 'shop_order_project');
$this->assertTrue(Wiaas_Order_Project::is_order_project_available($added_order_project));
$this->assertTrue(Wiaas_Order_Project::is_order_project_available($added_order_project->term_id));
}
/**
* @covers Wiaas_Order_Project::set_is_order_project_available()
*/
function test_set_is_order_project_available() {
Wiaas_Order_Project::add_order_project('Test', true);
$added_order_project = get_term_by('name', 'Test', 'shop_order_project');
Wiaas_Order_Project::set_is_order_project_available($added_order_project, false);
$saved_available_flag = get_term_meta($added_order_project->term_id, '_wiaas_is_available', true);
$this->assertEquals('no', $saved_available_flag);
Wiaas_Order_Project::set_is_order_project_available($added_order_project->term_id, true);
$saved_available_flag = get_term_meta($added_order_project->term_id, '_wiaas_is_available', true);
$this->assertEquals('yes', $saved_available_flag);
}
/**
* @covers Wiaas_Order_Project::get_available_order_projects()
*/
function test_get_available_order_projects() {
Wiaas_Order_Project::add_order_project('Test Available 1', true);
Wiaas_Order_Project::add_order_project('Test Available 2', true);
Wiaas_Order_Project::add_order_project('Test Available 3', true);
Wiaas_Order_Project::add_order_project('Test Not Available 1', false);
Wiaas_Order_Project::add_order_project('Test Not Available 2', false);
Wiaas_Order_Project::add_order_project('Test Not Available 3', false);
$available_projects = Wiaas_Order_Project::get_available_order_projects();
$this->assertCount(3, $available_projects);
foreach ($available_projects as $project) {
$this->assertArrayHasKey('id', $project);
$this->assertArrayHasKey('name', $project);
$this->assertContains($project['name'], array(
'Test Available 1',
'Test Available 2',
'Test Available 3'
));
}
}
}

View File

@@ -28,6 +28,8 @@ class Wiaas_Order_Test extends Wiaas_Unit_Test_Case {
Wiaas_User_Organization::TAXONOMY_NAME
)['term_id'];
update_user_meta($this->customer_id, '_wiaas_organization_id', $this->customer_organization_id);
# add customer to organization
wp_set_terms_for_user(
$this->customer_id,

View File

@@ -0,0 +1,415 @@
<?php
class Wiaas_Pricing_Test extends Wiaas_Unit_Test_Case {
private function _create_package_to_sell() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20, true, 2);
$this->add_product_category($product2, 'installation');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 0,
'minimal_services_price' => 100
),
'managed_36' => array(
'minimal_fixed_price' => 100,
'principal_amount' => 100,
'minimal_services_price' => 100
)
);
$commision = 50;
$cost_margin = 0;
Wiaas_Package_Pricing::set_package_prices($package, $pricing_rules, $commision, $cost_margin);
$customer_id = wp_create_term(
'Customer',
Wiaas_User_Organization::TAXONOMY_NAME
)['term_id'];
$commercial_lead_id = wp_create_term(
'Commercial Lead',
Wiaas_User_Organization::TAXONOMY_NAME
)['term_id'];
self::_set_package_default_extras($commercial_lead_id, $package->get_id());
$expected_prices = array(
'purchase' => array(
'fixed_extra' => 100,
'recurrent_extra' => 0,
'services_extra' => 0
),
'purchase_24' => array(
'fixed_extra' => 100,
'recurrent_extra' => 0,
'services_extra' => 100
),
'managed_36' => array(
'fixed_extra' => 100,
'recurrent_extra' => 3,
'services_extra' => 100
)
);
return array( $package, $expected_prices, $customer_id, $commercial_lead_id );
}
private function _set_package_default_extras($commercial_lead_id, $package_id) {
$cl_extras = array(
'purchase_default' => array(
'fixed' => 0,
'recurrent' => 0,
'services' => 0,
'visible' => true
),
'purchase_24_default' => array(
'fixed' => 0,
'recurrent' => 0,
'services' => 0,
'visible' => true
),
'managed_36_default' => array(
'fixed' => 0,
'recurrent' => 0,
'services' => 0,
'visible' => true
)
);
Wiaas_Package_CL_Pricing::set_extras($commercial_lead_id, $package_id, $cl_extras);
}
/**
* @covers Wiaas_Pricing::get_product_total_cost()
*/
function test_get_fixed_product_total_cost() {
$product = $this->create_new_product();
$total_cost = Wiaas_Pricing::get_product_total_cost($product);
$this->assertEquals($total_cost, $product->get_price());
}
/**
* @covers Wiaas_Pricing::get_product_total_cost()
*/
function test_get_recurring_product_total_cost() {
$product = $this->create_new_product(10, true, 2);
$total_cost = Wiaas_Pricing::get_product_total_cost($product);
$this->assertEquals($total_cost, 20);
}
/**
* @covers Wiaas_Pricing::get_package_total_cost()
*/
function test_get_package_with_fixed_products_total_cost() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20);
$this->add_product_category($product2, 'software');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$expected_total_price = 40;
$total_price = Wiaas_Pricing::get_package_total_cost($package);
$this->assertEquals($expected_total_price, $total_price);
}
/**
* @covers Wiaas_Pricing::get_package_total_cost()
*/
function test_get_package_with_recurring_products_total_cost() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20, true, 2);
$this->add_product_category($product2, 'software');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$expected_total_price = 60;
$total_price = Wiaas_Pricing::get_package_total_cost($package);
$this->assertEquals($expected_total_price, $total_price);
}
/**
* @covers Wiaas_Pricing::get_package_total_cost()
*/
function test_package_with_single_installation_product_total_cost() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(20, true, 2);
$this->add_product_category($product2, 'installation');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2));
$expected_total_price = 60;
$total_price = Wiaas_Pricing::get_package_total_cost($package);
$this->assertEquals($expected_total_price, $total_price);
}
/**
* @covers Wiaas_Pricing::get_package_total_cost()
*/
function test_package_with_multiple_installation_products_total_cost() {
$product1 = $this->create_new_product(20);
$this->add_product_category($product1, 'hardware');
$product2 = $this->create_new_product(10, true, 2);
$this->add_product_category($product2, 'installation');
$this->assertTrue(Wiaas_Product_Category::is_installation($product2));
$product3 = $this->create_new_product(20, true, 2);
$this->add_product_category($product3, 'installation');
$package = $this->create_new_package();
$this->add_products_to_package($package, array( $product1, $product2, $product3));
// price will be 20 + 20*2 , more expensive installation will be applied
$expected_total_price = 60;
$total_price = Wiaas_Pricing::get_package_total_cost($package);
$this->assertEquals($expected_total_price, $total_price);
}
/**
* @covers Wiaas_Pricing::get_standard_package_customer_prices()
*/
function test_get_standard_package_customer_price() {
list( $package, $expected_prices, $customer_id, $commercial_lead_id ) = $this->_create_package_to_sell();
$customer_prices = Wiaas_Pricing::get_standard_package_customer_prices(
$package,
$customer_id,
$commercial_lead_id);
$this->assertCount(3, $customer_prices);
foreach ($customer_prices as $customer_price) {
$this->assertArrayHasKey('id', $customer_price);
$this->assertArrayHasKey('payment_type', $customer_price);
$this->assertArrayHasKey('max_contract_period', $customer_price);
$this->assertArrayHasKey('package_pay_period', $customer_price);
$this->assertArrayHasKey('period_unit', $customer_price);
$this->assertArrayHasKey('services_contract_period', $customer_price);
$this->assertArrayHasKey('fixed_extra', $customer_price);
$this->assertArrayHasKey('recurrent_extra', $customer_price);
$this->assertArrayHasKey('services_extra', $customer_price);
$id = $customer_price['id'];
$this->assertEquals($customer_price['fixed_extra'], $expected_prices[$id]['fixed_extra']);
$this->assertEquals($customer_price['recurrent_extra'], $expected_prices[$id]['recurrent_extra']);
$this->assertEquals($customer_price['services_extra'], $expected_prices[$id]['services_extra']);
}
}
/**
* @covers Wiaas_Pricing::get_addon_package_customer_price()
*/
function test_get_addon_package_customer_price() {
list( $package, $expected_prices, $customer_id, $commercial_lead_id ) = $this->_create_package_to_sell();
$addon_product = $this->create_new_product(20);
$this->add_product_category($addon_product, 'hardware');
$addon_package = $this->create_new_package();
$this->add_products_to_package($addon_package, array($addon_product));
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 0,
'minimal_services_price' => 500
),
'managed_36' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 500,
'minimal_services_price' => 500
)
);
$commision = 50;
$cost_margin = 0;
Wiaas_Package_Pricing::set_package_prices($addon_package, $pricing_rules, $commision, $cost_margin);
self::_set_package_default_extras($commercial_lead_id, $addon_package->get_id());
Wiaas_Package_Addon::set_package_addons($package, array($addon_package->get_id()));
$expected_prices = array(
'purchase' => array(
'fixed_extra' => 500,
'recurrent_extra' => 0,
'services_extra' => 0
),
'purchase_24' => array(
'fixed_extra' => 500,
'recurrent_extra' => 0,
'services_extra' => 500
),
'managed_36' => array(
'fixed_extra' => 500,
'recurrent_extra' => 14,
'services_extra' => 500
)
);
$customer_prices = Wiaas_Pricing::get_addon_package_customer_price(
$addon_package,
$package,
$customer_id,
$commercial_lead_id);
$this->assertCount(3, $customer_prices);
foreach ($customer_prices as $customer_price) {
$this->assertArrayHasKey('id', $customer_price);
$this->assertArrayHasKey('payment_type', $customer_price);
$this->assertArrayHasKey('max_contract_period', $customer_price);
$this->assertArrayHasKey('package_pay_period', $customer_price);
$this->assertArrayHasKey('period_unit', $customer_price);
$this->assertArrayHasKey('services_contract_period', $customer_price);
$this->assertArrayHasKey('fixed_extra', $customer_price);
$this->assertArrayHasKey('recurrent_extra', $customer_price);
$this->assertArrayHasKey('services_extra', $customer_price);
$id = $customer_price['id'];
$this->assertEquals($customer_price['fixed_extra'], $expected_prices[$id]['fixed_extra']);
$this->assertEquals($customer_price['recurrent_extra'], $expected_prices[$id]['recurrent_extra']);
$this->assertEquals($customer_price['services_extra'], $expected_prices[$id]['services_extra']);
}
}
/**
* @covers Wiaas_Pricing::get_option_package_customer_price()
*/
function test_get_option_package_customer_price() {
list( $package, $customer_id, $commercial_lead_id ) = $this->_create_package_to_sell();
$option_product = $this->create_new_product(20);
$this->add_product_category($option_product, 'hardware');
$option_package = $this->create_new_package();
$this->add_products_to_package($option_package, array($option_product));
$pricing_rules = array(
'purchase' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 0,
'minimal_services_price' => 0
),
'purchase_24' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 0,
'minimal_services_price' => 500
),
'managed_36' => array(
'minimal_fixed_price' => 500,
'principal_amount' => 500,
'minimal_services_price' => 500
)
);
$commision = 50;
$cost_margin = 0;
Wiaas_Package_Pricing::set_package_prices($option_package, $pricing_rules, $commision, $cost_margin);
self::_set_package_default_extras($commercial_lead_id, $option_package->get_id());
Wiaas_Package_Option_Groups::set_package_option_groups($package, array(
'id' => 'option',
'name' => 'Option',
'default' => $option_package->get_id(),
'options' => array( $option_package->get_id() )
));
$expected_prices = array(
'purchase' => array(
'fixed_extra' => 500,
'recurrent_extra' => 0,
'services_extra' => 0
),
'purchase_24' => array(
'fixed_extra' => 500,
'recurrent_extra' => 0,
'services_extra' => 500
),
'managed_36' => array(
'fixed_extra' => 500,
'recurrent_extra' => 14,
'services_extra' => 500
)
);
$customer_prices = Wiaas_Pricing::get_option_package_customer_price(
$option_package,
$package,
$customer_id,
$commercial_lead_id);
$this->assertCount(3, $customer_prices);
foreach ($customer_prices as $customer_price) {
$this->assertArrayHasKey('id', $customer_price);
$this->assertArrayHasKey('payment_type', $customer_price);
$this->assertArrayHasKey('max_contract_period', $customer_price);
$this->assertArrayHasKey('package_pay_period', $customer_price);
$this->assertArrayHasKey('period_unit', $customer_price);
$this->assertArrayHasKey('services_contract_period', $customer_price);
$this->assertArrayHasKey('fixed_extra', $customer_price);
$this->assertArrayHasKey('recurrent_extra', $customer_price);
$this->assertArrayHasKey('services_extra', $customer_price);
$id = $customer_price['id'];
$this->assertEquals($customer_price['fixed_extra'], $expected_prices[$id]['fixed_extra']);
$this->assertEquals($customer_price['recurrent_extra'], $expected_prices[$id]['recurrent_extra']);
$this->assertEquals($customer_price['services_extra'], $expected_prices[$id]['services_extra']);
}
}
}

View File

@@ -0,0 +1,78 @@
<?php
class Wiaas_Product_Category_Test extends Wiaas_Unit_Test_Case {
/**
* @covers Wiaas_Product_Category::register_product_categories()
*/
function test_available_product_categories_created() {
$taxonomy = get_taxonomy('product_cat');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
$category_names = array_map(function($term) {
return $term->name;
}, get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => false )));
$this->assertNotEmpty($category_names);
$this->assertTrue(in_array('hardware', $category_names));
$this->assertTrue(in_array('software', $category_names));
$this->assertTrue(in_array('service', $category_names));
$this->assertTrue(in_array('installation', $category_names));
}
/**
* @covers Wiaas_Product_Category::get_category()
*/
function test_get_category() {
$product = $this->create_new_product();
$this->add_product_category($product, 'hardware');
$product_category = Wiaas_Product_Category::get_category($product);
$this->assertNotNull($product_category);
$this->assertEquals($product_category, 'hardware');
}
/**
* @covers Wiaas_Product_Category::is_service()
*/
function test_is_service_negative() {
$product = $this->create_new_product();
$this->add_product_category($product, 'hardware');
$this->assertFalse(Wiaas_Product_Category::is_service($product));
}
/**
* @covers Wiaas_Product_Category::is_service()
*/
function test_is_service_positive() {
$product = $this->create_new_product();
$this->add_product_category($product, 'service');
$this->assertTrue(Wiaas_Product_Category::is_service($product));
}
/**
* @covers Wiaas_Product_Category::is_installation()
*/
function test_is_installation_negative() {
$product = $this->create_new_product();
$this->add_product_category($product, 'hardware');
$this->assertFalse(Wiaas_Product_Category::is_installation($product));
}
/**
* @covers Wiaas_Product_Category::is_installation()
*/
function test_is_installation_positive() {
$product = $this->create_new_product();
$this->add_product_category($product, 'installation');
$this->assertTrue(Wiaas_Product_Category::is_installation($product));
}
}

View File

@@ -0,0 +1,61 @@
<?php
class Wiaas_Templates_Test extends Wiaas_Unit_Test_Case {
var $template, $product, $package, $template_category, $template_meta;
public function setUp() {
parent::setUp();
# set admin as current user
wp_set_current_user(1);
$this->template_category = wp_create_term('Test', 'template_category');
$this->template_meta = array(
'template_category_id' => $this->template_category['term_id'],
'template_category_title' => 'Test',
'quantity' => 1
);
$this->template = $this->create_new_wiaas_template();
$this->product = $this->create_new_product();
$this->package = $this->create_new_package();
$this->add_products_to_package($this->package, $this->product);
}
public function test_template_category_taxonomy_created() {
$taxonomy = get_taxonomy('template_category');
$this->assertInstanceOf(WP_Taxonomy::class, $taxonomy);
$template_category_names = array_map(function ($term) {
return $term->name;
}, get_terms(array('taxonomy' => 'template_category', 'hide_empty' => false)));
$this->assertNotEmpty($template_category_names);
$this->assertContains('Test', $template_category_names);
}
function test_adding_template_category_to_template() {
WC_Product_Template::save_template_product_meta($this->template->get_id(), 'hardware', $this->template_meta);
$test_template_category = WC_Product_Template::get_template_categories_from_meta(
$this->template->get_id(), '_template_items_hardware');
$this->assertEquals($test_template_category['template_category_id'], $this->template_meta['template_category_id']);
$this->assertEquals($test_template_category['template_category_title'], $this->template_meta['template_category_title']);
$this->assertEquals($test_template_category['quantity'], $this->template_meta['quantity']);
}
function save_bind_package_to_template() {
WC_Product_Template::bind_selected_template_to_product($this->template->get_id(), $this->package->get_id());
$value = get_post_meta($this->package->get_id(), '_select_template', true);
$this->assertNotEmpty($value);
}
}

View File

@@ -28,6 +28,8 @@ class Wiaas_User_Organization_Test extends Wiaas_Unit_Test_Case {
Wiaas_User_Organization::TAXONOMY_NAME
)['term_id'];
update_user_meta($this->user_id, '_wiaas_organization_id', $this->user_organization_id);
# create department
$this->user_department_id = wp_insert_term(
$this->user_department_name,
@@ -63,11 +65,10 @@ class Wiaas_User_Organization_Test extends Wiaas_Unit_Test_Case {
* @covers Wiaas_User_Organization::get_user_organization()
*/
function test_retrieve_user_organization() {
$organization = Wiaas_User_Organization::get_user_organization($this->user_id);
$organization_id = Wiaas_User_Organization::get_user_organization_id($this->user_id);
$this->assertNotNull($organization);
$this->assertEquals($organization->term_id, $this->user_organization_id);
$this->assertEquals($organization->name, $this->user_organization_name);
$this->assertNotNull($organization_id);
$this->assertEquals($organization_id, $this->user_organization_id);
}
/**

View File

@@ -0,0 +1,63 @@
<?php
/**
* Implements common logic for testing Wiaas API
*
* Class Wiaas_API_Unit_Test_Case
*/
class Wiaas_API_Unit_Test_Case extends Wiaas_Unit_Test_Case {
protected $server;
function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new \WP_REST_Server;
do_action( 'rest_api_init' );
}
/**
* Test that given endpoint is forbidden when accessed as guest
*
* @param WP_REST_Request $request Request to test
*/
function check_endpoint_forbidden_for_guest($request) {
wp_set_current_user(0);
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertTrue($response->is_error());
$this->assertEquals($response->get_status(), 401);
$error_data = $response->as_error();
$this->assertEquals($error_data->get_error_message(), 'Sorry, you are not allowed to do that.');
}
/**
* Handles common action during dispatching of rest request
*
* @param WP_REST_Request $request
* @param int $expected_status_code
* @param bool $is_error_expected
*
* @return mixed Result error when error is expected, result data otherwise
*/
function dispatch_endpoint_request($request, $expected_status_code = 200, $is_error_expected = false) {
$response = $this->server->dispatch( $request );
$this->assertNotNull($response);
$this->assertInstanceOf('WP_REST_Response',$response);
$this->assertEquals($response->get_status(), $expected_status_code);
if ($is_error_expected) {
$this->assertTrue($response->is_error());
return $response->as_error();
}
$this->assertFalse($response->is_error());
return $response->get_data();
}
}

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