-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpepro-ultimate-invoice.php
More file actions
2688 lines (2608 loc) · 143 KB
/
pepro-ultimate-invoice.php
File metadata and controls
2688 lines (2608 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: PeproDev Ultimate Invoice
Description: The Most Advanced Invoice Plugin you were looking for! Create customizable PDF/HTML invoices for WooCommerce, attach to Email, Inventory Report, Shipping Labels, Shipping Tracking, Single-shop feature and ...
Contributors: peprodev, amirhpcom, blackswanlab
Tags: woocommerce invoice, pdf invoice, persian
Author: Pepro Dev. Group
Developer: amirhp.com
Author URI: https://pepro.dev/
Developer URI: https://amirhp.com
Plugin URI: https://peprodev.com/pepro-woocommerce-ultimate-invoice/
Version: 2.2.6
Stable tag: 2.2.6
Tested up to: 6.9
WC tested up to: 10.4
Requires at least: 5.0
Requires PHP: 7.4
WC requires at least: 5.0
Text Domain: pepro-ultimate-invoice
Domain Path: /languages
Copyright: (c) 2025 Pepro Dev. Group, All rights reserved.
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
* @Last modified by: amirhp-com <its@amirhp.com>
* @Last modified time: 2026/03/08 23:12:03
*/
namespace peproulitmateinvoice;
use voku\CssToInlineStyles\CssToInlineStyles;
use Automattic\WooCommerce\Utilities\OrderUtil;
use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
/**
* prevent data leak
*/
defined("ABSPATH") or die("<h2>Unauthorized Access!</h2><hr><small>PeproDev Ultimate Invoice :: Developed by Pepro Dev. Group (<a href='https://pepro.dev/'>https://pepro.dev/</a>)</small>");
// Prevent activation / loading on PHP versions older than 7.4
if (version_compare(PHP_VERSION, '7.4', '<')) {
if (defined('WP_ADMIN') && \is_admin()) {
// If this request is coming from an activation attempt, deactivate the plugin immediately
if (isset($_GET['activate']) && function_exists('deactivate_plugins')) {
\deactivate_plugins(\plugin_basename(__FILE__));
unset($_GET['activate']);
}
// Show an admin notice about the PHP version requirement
\add_action('admin_notices', function () {
$msg = sprintf(\__('%s requires at least PHP version %s to function. Your site is currently running PHP version %s. Please contact your hosting provider to upgrade your PHP version.', 'pepro-ultimate-invoice'), '<strong>PeproDev Ultimate Invoice for Woocommerce</strong>', '<strong>7.4</strong>', '<strong>' . PHP_VERSION . '</strong>');
printf('<div class="notice notice-error"><p>%s</p></div>', $msg);
});
}
return;
}
/**
* if plugin was not initiated before, let's do it
*/
if (!class_exists("PeproUltimateInvoice")) {
/**
* Main class, accessible on initiation with global $PeproUltimateInvoice
*/
class PeproUltimateInvoice {
public $td = "pepro-ultimate-invoice";
public $version = "2.2.6";
public $title = "Ultimate Invoice";
public $db_slug = "pepro-ultimate-invoice";
public $plugin_dir;
public $plugin_url;
public $assets_url;
public $plugin_basename;
public $plugin_file;
public $url;
public $barcode;
public $tpl;
public $Unauthorized_Access;
protected $print;
protected $invoice;
protected $mta;
protected $db_table = null;
protected $manage_links = array();
protected $meta_links = array();
/**
* construct plugin and set initiation hook and declare constants
*
* @method __construct
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function __construct() {
add_action("after_setup_theme", function(){
// load textdomain for translations
});
$this->plugin_file = __FILE__;
$this->plugin_dir = plugin_dir_path(__FILE__);
$this->plugin_url = plugins_url("", __FILE__);
$this->assets_url = plugins_url("/assets/", __FILE__);
$this->plugin_basename = plugin_basename(__FILE__);
$this->url = admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=general");
// for those use plugin in local environment
add_action("init", function(){ load_plugin_textdomain("pepro-ultimate-invoice", false, dirname(plugin_basename(__FILE__)) . "/languages/"); }, 1);
add_action("init", function(){
$this->title = __("Ultimate Invoice", "pepro-ultimate-invoice");
}, 2);
// define constants to be accessible out of the plugin class
defined('PEPROULTIMATEINVOICE_VER') || define('PEPROULTIMATEINVOICE_VER', $this->version);
defined('PEPROULTIMATEINVOICE_DIR') || define('PEPROULTIMATEINVOICE_DIR', plugin_dir_path(__FILE__));
defined('PEPROULTIMATEINVOICE_URL') || define('PEPROULTIMATEINVOICE_URL', plugins_url("", __FILE__));
defined('PEPROULTIMATEINVOICE_ASSETS_URL') || define('PEPROULTIMATEINVOICE_ASSETS_URL', $this->assets_url);
add_action("admin_notices", array($this, "admin_notices"));
// register_deactivation_hook( __FILE__, function () { update_option("peprodev_ultimate_invoice_alert_viewed_yet", ""); });
/**
* add compatibility with High-Performance Order Storage
*/
add_action("before_woocommerce_init", function () {
if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
}
});
if ($this->_wc_activated()) {
// hook into wp init and load plugin other hooks
add_action("init", array($this, 'init_plugin'));
include_once $this->plugin_dir . 'include/vendor/autoload.php';
$this->barcode = new \Picqer\Barcode\BarcodeGeneratorJPG();
$this->barcode->useGd();
include_once $this->plugin_dir . "include/admin/class-setting.php";
include_once $this->plugin_dir . "include/admin/class-print.php";
include_once $this->plugin_dir . "include/admin/class-template.php";
include_once $this->plugin_dir . "include/admin/class-column.php";
include_once $this->plugin_dir . 'include/admin/class-jdate.php';
include_once $this->plugin_dir . 'include/admin/class-wcproduct-panel.php';
// handle template based functions
$this->tpl = new \peproulitmateinvoice\PeproUltimateInvoice_Template();
// handle print invoice functions
$this->print = new \peproulitmateinvoice\PeproUltimateInvoice_Print();
// handle metaboxes and extras for wc orders
$this->mta = new \peproulitmateinvoice\PeproUltimateInvoice_Columns();
// attach pdf to woocommerce emails automatically
if ("yes" == $this->tpl->get_attach_pdf_invoices_to_mail()) {
add_filter('woocommerce_email_attachments', array($this, "attach_pdf_to_wC_emails"), 10, 3);
}
// automatic email sending
if ("automatic" == $this->tpl->get_send_invoices_via_email() || "automatic" == $this->tpl->get_send_invoices_via_email_admin()) {
add_action("woocommerce_order_status_changed", array($this, "woocommerce_order_status_changed_action"), 10, 3);
add_action("woocommerce_new_order", array($this, "woocommerce_new_order_action"), 10, 1);
}
// initiate plugin main instance
if (is_admin()) {
(new PeproUltimateInvoice_wcPanel())->init();
}
// disable woocommerce modern admin dashboard, has to be called here!
if ("yes" == $this->tpl->get_disable_wc_dashboard()) {
add_filter('woocommerce_admin_disabled', '__return_true');
add_filter('woocommerce_marketing_menu_items', '__return_empty_array');
add_filter('woocommerce_helper_suppress_admin_notices', '__return_true');
}
add_filter("woocommerce_hidden_order_itemmeta", array($this, "hidden_order_itemmeta"));
add_filter("woocommerce_get_order_item_totals", array($this, "woocommerce_order_discount_to_display"), 10, 3);
add_filter('woocommerce_format_weight', function ($weight) {
return str_replace(array('kg', 'g', 'lbs', 'oz',), array(__('kg', "pepro-ultimate-invoice"), __('g', "pepro-ultimate-invoice"), __('lbs', "pepro-ultimate-invoice"), __('oz', "pepro-ultimate-invoice"),), $weight);
});
add_filter('woocommerce_format_dimensions', function ($weight) {
return str_replace(array('mm', 'cm', 'in', 'yd',), array(__('mm', "pepro-ultimate-invoice"), __('cm', "pepro-ultimate-invoice"), __('in', "pepro-ultimate-invoice"), __('yd', "pepro-ultimate-invoice"),), $weight);
});
if (is_blog_admin() && isset($_GET["tab"]) && sanitize_text_field($_GET["tab"]) == sanitize_text_field("pepro_ultimate_invoice")) {
add_filter('woocommerce_admin_disabled', '__return_true');
add_filter('woocommerce_marketing_menu_items', '__return_empty_array');
add_filter('woocommerce_helper_suppress_admin_notices', '__return_true');
if (!isset($_GET["section"]) || empty(sanitize_text_field($_GET["section"]))) {
wp_safe_redirect(admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=general"));
}
}
// change colors and template if invoice is pre-invoice
add_filter("puiw_get_default_dynamic_params", array($this, "puiw_get_default_dynamic_params"), 10, 2);
add_filter('query_vars', function ($vars) {
$vars[] = "tp";
$vars[] = "pclr";
$vars[] = "sclr";
$vars[] = "tclr";
return $vars;
});
}
}
public function admin_notices() {
$message = "";
$seen = get_option("peprodev_ultimate_invoice_alert_viewed_yet", "");
if (!$seen || $seen !== $this->version) {
}
if (!$this->_wc_activated()) {
$installWC = admin_url("plugin-install.php?s=woo&tab=search&type=tag");
$alerttext = sprintf(__("%s needs %s to function. Please install and activate it.", "pepro-ultimate-invoice"), "<strong>PeproDev Ultimate Invoice for Woocommerce</strong>", "<a href='$installWC' target='_blank'><strong>WooCommerce</strong></a>");
$message = "<div style='padding: 0.3rem 0.5rem;line-height: 1; margin-inline-start: -0.5rem;'><img src='{$this->assets_url}img/peprodev.svg' width='32px' /></div>";
$message .= "<div>$alerttext</div>";
$message = apply_filters("peprodevups_alert_after_active", $message);
}
// check php version be 7.4 at least or show warning and disable plugin
if (version_compare(PHP_VERSION, '7.4', '<')) {
$alerttext = sprintf(__("%s requires at least PHP version %s to function. Your site is currently running PHP version %s. Please contact your hosting provider to upgrade your PHP version.", "pepro-ultimate-invoice"), "<strong>PeproDev Ultimate Invoice for Woocommerce</strong>", "<strong>7.4</strong>", "<strong>" . PHP_VERSION . "</strong>");
$message = "<div style='padding: 0.3rem 0.5rem;line-height: 1; margin-inline-start: -0.5rem;'><img src='{$this->assets_url}img/peprodev.svg' width='32px' /></div>";
$message .= "<div>$alerttext</div>";
$message = apply_filters("peprodevups_alert_after_active", $message);
}
if (!empty($message)) printf('<div class="%1$s" style="border-color: #ffa176;"><div class="pepro_alert" style="display: flex;align-items: center;">%2$s</div></div>', esc_attr("notice notice-info is-not-dismissible"), $message);
}
public function downloads_bulk_actions_edit_product($actions) {
$actions['invoice_zip'] = __("Bulk Download PDF Invoice", "pepro-ultimate-invoice");
$actions['invoice_pos_zip'] = __("Bulk Download POS PDF Invoice", "pepro-ultimate-invoice");
$actions['invoice_inventory_bulk'] = __("Bulk Print Inventory Report", "pepro-ultimate-invoice");
$actions['invoice_slips_bulk'] = __("Bulk Print Packing Slips", "pepro-ultimate-invoice");
return $actions;
}
public function downloads_handle_bulk_action_edit_shop_order($redirect_to, $action, $post_ids) {
global $attach_download_dir, $attach_download_file;
if ($action == 'invoice_zip') {
$redirect_to = add_query_arg(array('invoice-zip' => implode(',', $post_ids)), $redirect_to);
}
if ($action == 'invoice_pos_zip') {
$redirect_to = add_query_arg(array('invoice-pos-zip' => implode(',', $post_ids)), $redirect_to);
}
if ($action == 'invoice_inventory_bulk') {
$redirect_to = add_query_arg(array('inventory-bulk' => implode(',', $post_ids)), $redirect_to);
}
if ($action == 'invoice_slips_bulk') {
$redirect_to = add_query_arg(array('slips-bulk' => implode(',', $post_ids)), $redirect_to);
}
return $redirect_to;
}
public function debugEnabled($debug_true = true, $debug_false = false) {
return apply_filters("puiw_debug_enabled", $debug_true);
}
/**
* woocommerce order placed hook to send emails
*
* @method woocommerce_new_order_action
* @param int $order_id
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function woocommerce_new_order_action($order_id) {
$order = wc_get_order($order_id);
$note = "";
if ("automatic" == $this->tpl->get_send_invoices_via_email()) {
$email = $order->get_billing_email();
$wp_mail = $this->send_formatted_email($order_id, $email, true);
if ($wp_mail) {
$note .= "<br />" . sprintf(__("Automatic Email sent to customer mail address:<br> %s", "pepro-ultimate-invoice"), $email);
} else {
$note .= "<br />" . sprintf(__("An error occured sending Automatic Email to customer mail address:<br> %s", "pepro-ultimate-invoice"), $email);
}
}
if ("automatic" == $this->tpl->get_send_invoices_via_email_admin()) {
$valid_reciever_shopmngrs = $this->tpl->get_send_invoices_via_email_shpmngrs();
if (!empty($valid_reciever_shopmngrs)) {
$wp_mail = $this->send_formatted_email($order_id, $valid_reciever_shopmngrs, true);
if ($wp_mail) {
$note .= "<br />" . sprintf(__("Automatic Email sent to following shop managers:<br> %s", "pepro-ultimate-invoice"), (count($valid_reciever_shopmngrs) > 1 ? implode(", ", $valid_reciever_shopmngrs) : $valid_reciever_shopmngrs));
} else {
$note .= "<br />" . sprintf(__("An error occured sending Automatic Email to following shop managers:<br> %s", "pepro-ultimate-invoice"), (count($valid_reciever_shopmngrs) > 1 ? implode(", ", $valid_reciever_shopmngrs) : $valid_reciever_shopmngrs));
}
} else {
$note .= "<br />" . __("No Shop Manager selected to send Automatic Email to.", "pepro-ultimate-invoice");
}
}
if (!empty($note)) {
$order->add_order_note($note);
}
}
/**
* woocommerce order status changed hook to send emails
*
* @method woocommerce_order_status_changed_action
* @param int $order_id
* @param string $old_status
* @param string $new_status
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function woocommerce_order_status_changed_action($order_id, $old_status, $new_status) {
// $order = wc_get_order( $order_id );
$old_status = "wc-$old_status";
$new_status = "wc-$new_status";
$order = wc_get_order($order_id);
$note = "";
if ("automatic" == $this->tpl->get_send_invoices_via_email()) {
$valid_order_status = $this->tpl->get_send_invoices_via_email_opt(array("wc-completed"));
if (in_array($new_status, apply_filters('puiw_valid_order_statuses_customer_auto_email', (array) $valid_order_status))) {
$email = $order->get_billing_email();
$wp_mail = $this->send_formatted_email($order_id, $email, true);
if ($wp_mail) {
$note .= "<br />" . sprintf(__("Automatic Email sent to customer mail address:<br> %s", "pepro-ultimate-invoice"), $email);
} else {
$note .= "<br />" . sprintf(__("An error occured sending Automatic Email to customer mail address:<br> %s", "pepro-ultimate-invoice"), $email);
}
}
}
if ("automatic" == $this->tpl->get_send_invoices_via_email_admin()) {
$valid_order_status = $this->tpl->get_send_invoices_via_email_opt_admin(array("wc-completed"));
if (in_array($new_status, apply_filters('puiw_valid_order_statuses_shopmngr_auto_email', (array) $valid_order_status))) {
$valid_reciever_shopmngrs = $this->tpl->get_send_invoices_via_email_shpmngrs();
if (!empty($valid_reciever_shopmngrs)) {
$wp_mail = $this->send_formatted_email($order_id, $valid_reciever_shopmngrs, true);
if ($wp_mail) {
$note .= "<br />" . sprintf(__("Automatic Email sent to following shop managers:<br> %s", "pepro-ultimate-invoice"), (count($valid_reciever_shopmngrs) > 1 ? implode(", ", $valid_reciever_shopmngrs) : $valid_reciever_shopmngrs));
} else {
$note .= "<br />" . sprintf(__("An error occured sending Automatic Email to following shop managers:<br> %s", "pepro-ultimate-invoice"), (count($valid_reciever_shopmngrs) > 1 ? implode(", ", $valid_reciever_shopmngrs) : $valid_reciever_shopmngrs));
}
} else {
$note .= "<br />" . __("No Shop Manager selected to send Automatic Email to.", "pepro-ultimate-invoice");
}
}
}
if (!empty($note)) {
$order->add_order_note($note);
}
}
/**
* send mail using pepro ultimate invoice core
*
* @method send_formatted_email
* @param int $order_id
* @param string $email
* @param boolean $attach
* @return string wp_mail status
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function send_formatted_email($order_id, $email, $attach) {
add_filter("puiw_printinvoice_return_html_minfied", "__return_false", 10, 1);
$invc = $this->print->create_html($order_id, "HTML", "", true, true);
$cssToInlineStyles = new CssToInlineStyles($invc);
$cssToInlineStyles->setCleanup(true);
$cssToInlineStyles->setUseInlineStylesBlock(true);
$invc = $cssToInlineStyles->convert();
$subject = apply_filters("puiw_email_invoice_customer_subject", sprintf($this->tpl->get_email_subject(_x("Order #%s invoice on ", "wc-setting", "pepro-ultimate-invoice") . get_bloginfo('name', 'display')), $order_id));
$PDFattachments = false;
if ($attach) {
$PDFattachments = true;
$namedir = PEPROULTIMATEINVOICE_DIR . "/pdf_temp";
$namedir = apply_filters("puiw_get_default_mail_pdf_temp_path", $namedir);
$invcPDF = $this->print->create_pdf($order_id, false, "S", false);
$attachments = array("$namedir/$invcPDF");
}
$wp_mail = wp_mail($email, $subject, $invc, array('Content-Type: text/html; charset=UTF-8', "From: {$this->tpl->get_email_from_name()} <{$this->tpl->get_email_from_address()}>"), $attachments);
if ($PDFattachments) {
unlink("$namedir/$invcPDF");
}
return $wp_mail;
}
public function pwoosms_shortcodes_list($shortcodes) {
return "<br><strong>{$this->title}</strong><br><code>{track_id}</code> = " . __("Shipping Track Serial", "pepro-ultimate-invoice") . "<br>" . PHP_EOL . $shortcodes;
}
public function sms_body_after_replace($content, $order_id, $order, $all_product_ids, $vendor_product_ids) {
$order = wc_get_order($order_id);
if ($order_id) {$track_id = $order->get_meta("_shipping_puiw_invoice_track_id", true);
}else{$track_id = get_post_meta($order_id, "_shipping_puiw_invoice_track_id", true);}
$content = str_replace("{track_id}", $track_id, $content);
return $content;
}
/**
* customized die wp function
*
* @method die
* @param string $title
* @param string $msg
* @return string html die msg
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function die($preTitle = "", $title = "ERR", $msg = "") {
$preTitle2 = "user-guest";
$preTitle2 = (get_current_user_id() > 0) ? ("user-" . get_current_user_id()) : $preTitle2;
$ext = "
@font-face { font-family: 'bodyfont'; font-style: normal; font-weight: normal; src: url('" . PEPROULTIMATEINVOICE_URL . "/assets/css/96594ad4.woff') format('woff'); }
@font-face { font-family: 'bodyfont'; font-style: normal; font-weight: bold; src: url('" . PEPROULTIMATEINVOICE_URL . "/assets/css/96594ad5.woff') format('woff'); }";
$html = '<title>' . $title . '</title><!--ERR: ' . $preTitle . ' --><style type="text/css">' . $ext .
'html { background: #f1f1f1; } body { background: #fff; color: #444; font-family: bodyfont, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
margin: 2em auto; padding: 1em 2em; max-width: 700px; -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13); width: 80%; max-height: 130px;}
h1 { border-bottom: 1px solid #dadada; clear: both; color: #666; font-size: 24px; margin: 30px 0 0 0; padding: 0; padding-bottom: 7px; } #error-page { margin-top: 50px; }
#error-page p, #error-page .wp-die-message { font-size: 14px; line-height: 1.5; margin: 25px 0 20px; }
#error-page code { font-family: Consolas, Monaco, monospace; } ul li { margin-bottom: 10px; font-size: 14px ; }
a { color: #0073aa; } a:hover, a:active { color: #00a0d2; }
a:focus { color: #124964; -webkit-box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, 0.8); outline: none; }
.button { background: #f7f7f7; border: 1px solid #ccc; color: #555; display: inline-block; text-decoration: none; font-size: 13px; line-height: 2; height: 28px; margin: 0; padding: 0 10px 1px; cursor: pointer;
-webkit-border-radius: 3px; -webkit-appearance: none; border-radius: 3px; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-box-shadow: 0 1px 0 #ccc;
box-shadow: 0 1px 0 #ccc; vertical-align: top; } .button.button-large { height: 30px; line-height: 2.15384615; padding: 0 12px 2px; } .button:hover, .button:focus { background: #fafafa; border-color: #999; color: #23282d; }
.button:focus { border-color: #5b9dd9; -webkit-box-shadow: 0 0 3px rgba(0, 115, 170, 0.8); box-shadow: 0 0 3px rgba(0, 115, 170, 0.8); outline: none; } .button:active { background: #eee; border-color: #999;
-webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); }body { font-family: bodyfont, Tahoma, Arial; } </style>
<body id="error-page ' . "$preTitle $preTitle2" . '"><div class="wp-die-message">' . $msg . '</div></body></html>';
die($html);
}
/**
* Initiate plugin with init hook
*
* @method init_plugin
* @version 1.1.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function init_plugin() {
// add compatibility with WPC Product Bundles for WooCommerce By WPClever
// Since v. 1.3.5
if (class_exists('WPCleverWoosb') && function_exists('WPCleverWoosb')) {
$WPCleverWoosb = WPCleverWoosb();
remove_action("woocommerce_before_order_itemmeta", array($WPCleverWoosb, 'woosb_before_order_item_meta'), 10);
remove_action('woocommerce_order_formatted_line_subtotal', array($WPCleverWoosb, 'woosb_order_formatted_line_subtotal'), 10, 2);
// remove_all_actions("woocommerce_before_order_itemmeta", 10);
}
if ( class_exists("\Automattic\WooCommerce\Utilities\OrderUtil") && OrderUtil::custom_orders_table_usage_is_enabled()) {
// HPOS usage is enabled.
add_filter('bulk_actions-woocommerce_page_wc-orders', array($this, 'downloads_bulk_actions_edit_product'), 20, 1);
add_filter('handle_bulk_actions-woocommerce_page_wc-orders', array($this, 'downloads_handle_bulk_action_edit_shop_order'), 10, 3);
}
else {
// Traditional CPT-based orders are in use.
add_filter('bulk_actions-edit-shop_order', array($this, 'downloads_bulk_actions_edit_product'), 20, 1);
add_filter('handle_bulk_actions-edit-shop_order', array($this, 'downloads_handle_bulk_action_edit_shop_order'), 10, 3);
}
// public methods to get receipts
if (isset($_GET["invoice"]) && !empty(trim(sanitize_text_field($_GET["invoice"])))) {
$order_id = (int) trim(sanitize_text_field($_GET["invoice"]));
if (wc_get_order($order_id)) {
die($this->print->create_html($order_id));
}
}
if (isset($_GET["invoice-pdf"]) && !empty(trim(sanitize_text_field($_GET["invoice-pdf"])))) {
$force_download = isset($_GET["download"]) && !empty(sanitize_text_field($_GET["download"])) ? true : false;
die($this->print->create_pdf((int) trim(sanitize_text_field($_GET["invoice-pdf"])), $force_download, "I", false));
}
if (isset($_GET["invoice-pos"]) && !empty(trim(sanitize_text_field($_GET["invoice-pos"])))) {
$force_download = isset($_GET["download"]) && !empty(sanitize_text_field($_GET["download"])) ? true : false;
$this->setup_thermal_invoice();
die($this->print->create_pdf((int) trim(sanitize_text_field($_GET["invoice-pos"])), $force_download, "I", false, true));
}
if (isset($_GET["invoice-slips"]) && !empty(trim(sanitize_text_field($_GET["invoice-slips"])))) {
die($this->print->create_slips((int) trim(sanitize_text_field($_GET["invoice-slips"]))));
}
if (isset($_GET["invoice-slips-pdf"]) && !empty(trim(sanitize_text_field($_GET["invoice-slips-pdf"])))) {
$force_download = isset($_GET["download"]) && !empty(sanitize_text_field($_GET["download"])) ? true : false;
die($this->print->create_slips_pdf((int) trim(sanitize_text_field($_GET["invoice-slips-pdf"])), $force_download));
}
if (isset($_GET["invoice-inventory"]) && !empty(trim(sanitize_text_field($_GET["invoice-inventory"])))) {
die($this->print->create_inventory((int) trim(sanitize_text_field($_GET["invoice-inventory"]))));
}
// admin methods for bulk actions and setting export/import
if (is_admin() && !is_ajax() && current_user_can("manage_options") && is_blog_admin()) {
#region invoice zip bulk action
if (isset($_GET["invoice-zip"]) && !empty(trim(sanitize_text_field($_GET["invoice-zip"])))) {
$pdfs = array();
$order_ids_valid = array();
$order_ids_name = array();
$order_ids = (array) explode(",", $_GET["invoice-zip"]);
$order_ids = array_map("trim", $order_ids); $i=0;
foreach ($order_ids as $order_id) {
try {
$order = wc_get_order($order_id);
if ($order) { $i++;
$order_ids_valid[] = $order_id;
$pdf_temp = $this->print->create_pdf((int)$order_id, false, "S", false);
if (file_exists(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp")) { $pdfs[] = PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp"; }
$order_ids_name[] = "FILE {$i}: {$pdf_temp}" . PHP_EOL . "MD5: " . md5_file(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp") . PHP_EOL . "SHA1: " . sha1_file(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp") . PHP_EOL;
}
} catch (\Throwable $th) {
//throw $th;
}
}
$date_now = current_time('timestamp');
$date_time = date_i18n("Y_m_d_H_i_s", $date_now);
$name_dir = PEPROULTIMATEINVOICE_DIR . "/zip_temp";
if (!file_exists($name_dir)) @mkdir($name_dir, 0777, true);
$random = wp_generate_password(8, false, false);
$name_dot_ext = "InvoicesArchive-$date_time-$random.zip";
$zip_file = "{$name_dir}/{$name_dot_ext}";
file_exists($zip_file) and unlink($zip_file);
$zip = new \ZipArchive;
if ($zip->open($zip_file, $zip::CREATE | $zip::OVERWRITE) === TRUE) {
foreach ($pdfs as $file) @$zip->addFile($file, basename($file));
$comments_lines = array(
"== WooCommerce PDF Invoices Zipped Archive File ==",
"Created by *Pepro Ultimate Invoice for WooCommerce* v{$this->version}",
"Developed by Pepro Dev. Group ( https://pepro.dev/ )",
"Read more: https://wordpress.org/plugins/pepro-ultimate-invoice/",
"Disclaimer: Pepro Dev. Group is not responsible for the content of files included in this archive." . PHP_EOL . PHP_EOL,
"Archive Created Date: " . $this->tpl->get_date("now"),
"Archive Generated on: ".str_replace(["https", "http", "://www.", "://"], "", $this->tpl->get_store_website())." ({$this->tpl->get_store_name()})",
"Site Admin Email: {$this->tpl->get_store_email()}" . PHP_EOL,
"This archive should contain following Invoice PDF files:" . PHP_EOL,
implode(PHP_EOL, $order_ids_name),
);
$zip->setArchiveComment(implode(PHP_EOL, $comments_lines));
$zip->close();
}
else {
wp_die(sprintf(__("Failed creating zip archive! (code: %s) %s", "pepro-ultimate-invoice"), $zip->status, "<br>" . $zip->getStatusString()), __("Error", "pepro-ultimate-invoice"), array("back_link" => true));
exit;
}
foreach ($pdfs as $file) { is_file($file) and unlink($file); }
header('Content-type: application/force-download');
header("Content-Disposition: attachment; filename={$name_dot_ext}");
readfile($zip_file);
unlink($zip_file);
exit;
}
#endregion
#region invoice-pos zip bulk action
if (isset($_GET["invoice-pos-zip"]) && !empty(trim(sanitize_text_field($_GET["invoice-pos-zip"])))) {
$pdfs = array();
$order_ids_valid = array();
$order_ids_name = array();
$order_ids = (array) explode(",", $_GET["invoice-pos-zip"]);
$order_ids = array_map("trim", $order_ids); $i=0;
foreach ($order_ids as $order_id) {
try {
$order = wc_get_order($order_id);
if ($order) { $i++;
$order_ids_valid[] = $order_id;
$this->setup_thermal_invoice();
$pdf_temp = $this->print->create_pdf((int)$order_id, false, "S", false, true);
if (file_exists(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp")) { $pdfs[] = PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp"; }
$order_ids_name[] = "FILE {$i}: $pdf_temp" . PHP_EOL . "MD5: " . md5_file(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp") . PHP_EOL . "SHA1: " . sha1_file(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp") . PHP_EOL;
}
} catch (\Throwable $th) {
//throw $th;
}
}
$date_now = current_time('timestamp');
$date_time = date_i18n("Y_m_d_H_i_s", $date_now);
$name_dir = PEPROULTIMATEINVOICE_DIR . "/zip_temp";
if (!file_exists($name_dir)) @mkdir($name_dir, 0777, true);
$random = wp_generate_password(8, false, false);
$name_dot_ext = "InvoicesPOSArchive-$date_time-$random.zip";
$zip_file = "{$name_dir}/{$name_dot_ext}";
file_exists($zip_file) and unlink($zip_file);
$zip = new \ZipArchive;
if ($zip->open($zip_file, $zip::CREATE | $zip::OVERWRITE) === TRUE) {
foreach ($pdfs as $file) @$zip->addFile($file, basename($file));
$comments_lines = array(
"== WooCommerce PDF Invoices Zipped Archive File ==",
"Created by *Pepro Ultimate Invoice for WooCommerce* v{$this->version}",
"Developed by Pepro Dev. Group ( https://pepro.dev/ )",
"Read more: https://wordpress.org/plugins/pepro-ultimate-invoice/",
"Disclaimer: Pepro Dev. Group is not responsible for the content of files included in this archive." . PHP_EOL . PHP_EOL,
"Archive Created Date: " . $this->tpl->get_date("now"),
"Archive Generated on: ".str_replace(["https", "http", "://www.", "://"], "", $this->tpl->get_store_website())." ({$this->tpl->get_store_name()})",
"Site Admin Email: {$this->tpl->get_store_email()}" . PHP_EOL,
"This archive should contain following Invoice PDF files:" . PHP_EOL,
implode(PHP_EOL, $order_ids_name),
);
$zip->setArchiveComment(implode(PHP_EOL, $comments_lines));
$zip->close();
}
else {
wp_die(sprintf(__("Failed creating zip archive! (code: %s) %s", "pepro-ultimate-invoice"), $zip->status, "<br>" . $zip->getStatusString()), __("Error", "pepro-ultimate-invoice"), array("back_link" => true));
exit;
}
foreach ($pdfs as $file) { is_file($file) and unlink($file); }
header('Content-type: application/force-download');
header("Content-Disposition: attachment; filename={$name_dot_ext}");
readfile($zip_file);
unlink($zip_file);
exit;
}
#endregion
#region inventory bulk action
if (isset($_GET["inventory-bulk"]) && !empty(trim(sanitize_text_field($_GET["inventory-bulk"])))) {
$orderids = (array) explode(",", $_GET["inventory-bulk"]);
$orderids = array_map("trim", $orderids);
$inventory_temp = "";
foreach ($orderids as $order_id) {
$order = wc_get_order($order_id);
if ($order) {
$inventory_temp .= "<iframe
onload=\"this.style.width='100%';this.style.height = 0; this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';this.contentWindow.document.body.getElementsByTagName('p')[0].style.display='none'; \"
frameborder='0' scrolling='no' src='" . home_url("?invoice-inventory=$order_id") . "' title='OrderID#$order_id'></iframe>";
}
}
$printBtn = "<style> .print-button {
cursor: pointer;
text-decoration: none;
background-color: #555;
padding: 1rem;
margin: auto;
-webkit-margin-end: 2px;
margin-inline-end: 2px;
color: aliceblue;
display: inline-block;
border-radius: 15px;
line-height: 0;
} @media print {
.print-button {
display: none;
}
}</style>";
$printBtn .= "<p style='text-align: center'><a class=\"print-button\" href=\"javascript:;\" onclick=\"window.print();return false;\" >" . __("Print", "pepro-ultimate-invoice") . "</a></p>";
die("<title>" . __("Bulk Inventory Report", "pepro-ultimate-invoice") . "</title>{$printBtn}{$inventory_temp}");
}
#region slips bulk action
if (isset($_GET["slips-bulk"]) && !empty(trim(sanitize_text_field($_GET["slips-bulk"])))) {
$orderids = (array) explode(",", $_GET["slips-bulk"]);
$orderids = array_map("trim", $orderids);
$inventory_temp = "";
foreach ($orderids as $order_id) {
$order = wc_get_order($order_id);
if ($order) {
$inventory_temp .= "<iframe
onload=\"this.style.width='100%';this.style.height = 0; this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';this.contentWindow.document.body.getElementsByTagName('p')[0].style.display='none'; \"
frameborder='0' scrolling='no' src='" . home_url("?invoice-slips=$order_id") . "' title='OrderID#$order_id'></iframe>";
}
}
$printBtn = "<style>
.print-button {
cursor: pointer;
text-decoration: none;
background-color: #555;
padding: 1rem;
margin: auto;
-webkit-margin-end: 2px;
margin-inline-end: 2px;
color: aliceblue;
display: inline-block;
border-radius: 15px;
line-height: 0;
}
@media print { .print-button { display: none; }
}
</style>";
$printBtn .= "<p style='text-align: center'><a class=\"print-button\" href=\"javascript:;\" onclick=\"window.print();return false;\" >" . __("Print", "pepro-ultimate-invoice") . "</a></p>";
die("<title>" . __("Bulk Packing Slip", "pepro-ultimate-invoice") . "</title>{$printBtn}{$inventory_temp}");
}
#endregion
}
if (current_user_can("manage_options") && is_admin() && isset($_GET["nonce"], $_GET["ultimate-invoice-reset"]) && wp_verify_nonce($_GET["nonce"], "pepro-ultimate-invoice")) {
wp_die("Pepro Ultimate Invoice — FORCE RESET TO DEFAULT Settings done!<br />Return count: " . $this->change_default_settings("RESET"), "Force-reset Options", array("link_text" => __("Back to Settings", "pepro-ultimate-invoice"), "link_url" => admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=migrate"), "text_direction" => "ltr"));
}
if (current_user_can("manage_options") && is_admin() && isset($_GET["nonce"], $_GET["ultimate-invoice-set"]) && wp_verify_nonce($_GET["nonce"], "pepro-ultimate-invoice")) {
wp_die("Pepro Ultimate Invoice — RESET TO DEFAULT Settings done!<br />Return count: " . $this->change_default_settings("SET"), "Reset Options", array("link_text" => __("Back to Settings", "pepro-ultimate-invoice"), "link_url" => admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=migrate"), "text_direction" => "ltr"));
}
if (current_user_can("manage_options") && is_admin() && isset($_GET["nonce"], $_GET["ultimate-invoice-clear"]) && wp_verify_nonce($_GET["nonce"], "pepro-ultimate-invoice")) {
wp_die("Pepro Ultimate Invoice — FORCE CLEAR Settings done!<br />Return count: " . $this->change_default_settings("CLEAR"), "Clear Options", array("link_text" => __("Back to Settings", "pepro-ultimate-invoice"), "link_url" => admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=migrate"), "text_direction" => "ltr"));
}
if (current_user_can("manage_options") && is_admin() && isset($_GET["nonce"], $_GET["ultimate-invoice-get"]) && wp_verify_nonce($_GET["nonce"], "pepro-ultimate-invoice")) {
$string = "<div class='log5'>" . highlight_string("<?php" . PHP_EOL . $this->change_default_settings("GET"), 1) . "</div><style>.log5{text-align: left; direction: ltr; padding: 1rem; display: block; overflow: auto;z-index: 77777777777 !important;position: relative;background: white;} .log5 code {background: transparent !important;}</style>";
wp_die($string, "Export as PHP Script", array("link_text" => __("Back to Settings", "pepro-ultimate-invoice"), "link_url" => admin_url("admin.php?page=wc-settings&tab=pepro_ultimate_invoice§ion=migrate"), "text_direction" => "ltr"));
}
if ("yes" == $this->tpl->get_allow_quick_shop()) {
add_shortcode("puiw_quick_shop", array($this, "integrate_with_shortcode"));
if ($this->_vc_activated()) {
add_action("vc_before_init", array($this, "integrate_with_vc"));
if (function_exists('vc_add_shortcode_param')) {
vc_add_shortcode_param("{$this->td}_about", array($this, 'vc_add_pepro_about'), plugins_url("/assets/js/vc.init" . $this->debugEnabled(".js", ".min.js"), __FILE__));
}
}
}
add_action("plugin_row_meta", array($this, "plugin_row_meta"), 10, 4);
add_filter("plugin_action_links", array($this, "plugin_action_links"), 10, 2);
add_action("admin_menu", array($this, "admin_menu"), 1000);
add_action("admin_init", array($this, "admin_init"));
add_action("wp_ajax_nopriv_puiw_{$this->td}", array($this, "handel_ajax_req"));
add_action("wp_ajax_puiw_{$this->td}", array($this, "handel_ajax_req"));
add_action("wp_before_admin_bar_render", array($this, "wp_before_admin_bar_render"));
add_filter("pwoosms_shortcodes_list", array($this, "pwoosms_shortcodes_list"));
add_filter("pwoosms_order_sms_body_after_replace", array($this, "sms_body_after_replace"), -1, 5);
if ("yes" == $this->tpl->get_allow_preorder_invoice()) {
add_action("woocommerce_proceed_to_checkout", array($this, "woocommerce_after_cart_contents"), 1000);
}
if ("yes" == $this->tpl->get_allow_users_use_invoices()) {
add_filter("woocommerce_my_account_my_orders_actions", array($this, 'add_view_invoice_button_orderpage'), 10, 2);
}
if ("yes" == $this->tpl->get_allow_quick_shop()) {
add_shortcode("puiw_quick_shop", array($this, 'integrate_with_shortcode'));
}
add_action('woocommerce_admin_order_data_after_shipping_address', array($this, "after_shipping_shopmngr_provided_note"), 10, 1);
add_action("woocommerce_order_details_after_order_table_items", array($this, "woocommerce_order_details_after_order_table_items"));
add_action('woocommerce_checkout_update_order_meta', array($this, "woocommerce_checkout_update_order_meta"));
add_action('woocommerce_checkout_update_user_meta', array($this, "woocommerce_checkout_update_user_meta"), 10, 2);
add_filter('woocommerce_checkout_fields', array($this, "checkout_fields_add_uin"));
add_action("woocommerce_order_details_before_order_table", array($this, "woocommerce_order_details_before_order_table"), -1000);
add_filter("wc_order_statuses", array($this, "add_wc_order_statuses"));
add_filter("woocommerce_admin_billing_fields", array($this, "woocommerce_admin_billing_fields"));
add_filter("woocommerce_admin_shipping_fields", array($this, "woocommerce_admin_shipping_fields"));
add_action("woocommerce_checkout_create_order_line_item", array($this, "prices_as_order_line_item_meta"), 20, 4);
// remove previous generated pdf files
$saved_pdfs = glob(PEPROULTIMATEINVOICE_DIR . "/pdf_temp/*.pdf");
foreach ($saved_pdfs as $pdf) {
if (is_file($pdf)) {
unlink($pdf);
}
}
// add_action( 'woocommerce_admin_order_data_after_shipping_address', array($this,'checkout_field_admin_display_uin'), 10, 1 );
// add_action( 'woocommerce_admin_order_data_after_billing_address', array($this,'checkout_field_admin_display_uin'), 10, 1 );
// add_action( 'woocommerce_admin_order_data_after_order_details', array($this,'checkout_field_admin_display_odt'), 10, 1 );
$this->add_wc_prebuy_status();
if ($this->version != get_option("puiw_last_import_version")) {
$this->change_default_settings("SET");
update_option("puiw_last_import_version", $this->version);
}
}
public function calculate_total_discount($order) {
$total_discount_from_prices = 0;
// Iterate through order items
foreach ($order->get_items() as $item) {
// Get line item prices
$regular_price = (float) $item->get_meta('_line_regular_price', true); // Regular price
$item_price = (float) $item->get_total() / (int) $item->get_quantity(); // Item price (total / quantity)
// Calculate discount for this item
if ($regular_price > $item_price) {
$quantity = (int) $item->get_quantity();
$item_discount = ($regular_price - $item_price) * $quantity;
$total_discount_from_prices += $item_discount;
}
}
// Add coupon discount if any
$coupon_discount = $order->get_total_discount(); // Built-in WooCommerce method
$total_discount = $total_discount_from_prices + $coupon_discount;
return wc_price($total_discount);
// return [
// 'price_discount' => wc_price($total_discount_from_prices),
// 'coupon_discount' => wc_price($coupon_discount),
// 'total_discount' => wc_price($total_discount),
// ];
}
/**
* @param array $args
* @param \WC_Order $order
* @return void
*/
public function modify_storage_invoice_params($args, $order) {
$args["invoice_total"] = $order->get_formatted_order_total();
$args["invoice_final_totals"] = $this->get_order_final_prices($order);
$date_time = date_i18n("Y/m/d H:i", current_time("timestamp"));
$args["thermal_copyright"] = "<p style='text-align:center; font-size: 0.8rem;font-family: Arial;'><bdi dir='ltr'>PeproDev Ultimate Invoice v{$this->version} (www.pepro.dev)<br><small>Generated at {$date_time}</small></bdi></p>";
$order_note_a = apply_filters("puiw_printslips_order_note_customer", "<strong>" . __("Note provided by Customer", "pepro-ultimate-invoice") . "</strong><br>" . $this->tpl->get_order_note($order, "a"), $this->tpl->get_order_note($order, "a"), $order, $args);
$order_note_b = apply_filters("puiw_printslips_order_note_shopmngr", "<strong>" . __("Note provided by Shop manager", "pepro-ultimate-invoice") . "</strong><br>" . $this->tpl->get_order_note($order, "b"), $this->tpl->get_order_note($order, "b"), $order, $args);
$note_customer = !empty(trim((string) $this->tpl->get_order_note($order, "a"))) ? "<tr><div><td colspan='3' style='text-align:start; padding: 0.5rem;'>".$order_note_a."</td></div></tr>" : "";
$note_shopmngr = !empty(trim((string) $this->tpl->get_order_note($order, "b"))) ? "<tr><div><td colspan='3' style='text-align:start; padding: 0.5rem;'>".$order_note_b."</td></div></tr>" : "";
$args["order_notes_new"] = $note_customer . $note_shopmngr;
return $args;
}
/**
* @param \WC_Order $order
* @return void
*/
public function get_order_final_prices($order){
ob_start();
$ttl = $order->get_order_item_totals();
foreach ( $ttl as $key => $total ) {
if ("payment_method" == $key) {
?>
<tr class="puiw_totalrow transaction_id">
<th colspan="2">کد رهگیری پرداخت:</th>
<td width="4cm" colspan="1"><?php echo $order->get_transaction_id() ;?></td>
</tr>
<?php
}
if ( $key != "order_total" ){
?>
<tr class="puiw_totalrow <?php echo $key;?>">
<th colspan="2"><?php echo esc_html( $total['label'] ); ?></th>
<td width="4cm" colspan="1"><?php echo ( "payment_method" == $key ) ? esc_html( $total['value'] ) : wp_kses_post( $total['value'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
</tr>
<?php
}
}
$html = ob_get_contents();
ob_end_clean();
return $html;
}
public function printinvoice_create_html_item_row($args, $item_id, $item, $product_id, $order) {
// Retrieve saved price or use current price
$saved_price = (float) $item->get_meta('_saved_price', true);
$current_price = (float) $item->get_meta('_line_regular_price', true);
// Determine which price to use
$price_to_use = $saved_price > 0 ? $saved_price : $current_price;
// Get the quantity
$quantity = (int) $item->get_quantity();
// Calculate net total
$net_total = $price_to_use * $quantity;
// Save net total
$args['base_price'] = wc_price($net_total);
$args['discount'] = wc_price($net_total - $item->get_total());
$args['sku'] = !empty($args["sku"]) ? "({$args["sku"]})" : "";
return $args;
}
public function setup_thermal_invoice(){
add_filter("puiw_get_default_dynamic_params", array($this, "modify_storage_invoice_params"), 999, 2);
add_filter("puiw_printinvoice_create_html_item_row_metas", array($this, "printinvoice_create_html_item_row"), 10, 5);
add_filter("puiw_printinvoice_preserve_html_tags", function($arg, $opt, $order){$arg[] = "invoice_title"; $arg[] = "invoice_final_totals"; $arg[] = "thermal_copyright"; $arg[] = "order_notes_new"; return $arg;}, 10, 3);
add_filter("puiw_printinvoice_preserve_english_numbers", function($arg, $opt, $order){$arg[] = "invoice_title"; $arg[] = "invoice_final_totals"; $arg[] = "thermal_copyright"; $arg[] = "order_notes_new"; return $arg;}, 10, 3);
add_filter("puiw_get_export_pdf_name", function($name, $order_id_formatted, $order_id, $date){ return "sales-pos--$order_id_formatted.pdf"; }, 10, 4);
add_filter("puiw_get_templates_list", function ($templates) { $templates[] = plugin_dir_path(__FILE__) . "template/default-pos-rtl/default.cfg"; return $templates; }, 10, 1);
add_filter("puiw_get_template", function($template, $default){ return plugin_dir_path(__FILE__) . "template/default-pos-rtl"; }, 10, 2);
add_filter("puiw_printinvoice_pdf_footer_new", "__return_empty_string");
}
public function plugin_row_meta($links_array, $plugin_file_name, $plugin_data, $status) {
if (strpos($plugin_file_name, basename(__FILE__))) {
$links_array[] = "<a href='mailto:support+UltimateInvoice@pepro.dev?subject=Ask for Help [Ultimate Invoice]'>" . __("Support", "pepro-ultimate-invoice") . "</a>";
}
return $links_array;
}
public function plugin_action_links($actions, $plugin_file) {
if (plugin_basename(__FILE__) == $plugin_file) {
$actions[$this->db_slug] = "<a href='$this->url'>" . __("Settings", "pepro-ultimate-invoice") . "</a>";
}
return $actions;
}
public function make_pdf_file($order_id = 0) {
$order = wc_get_order($order_id);
if (!$order_id || !$order) return false;
$pdf_temp = $this->print->create_pdf((int) $order_id, false, "S", false);
$pdf_file = PEPROULTIMATEINVOICE_DIR . "/pdf_temp/$pdf_temp";
if (file_exists($pdf_file)) return $pdf_file;
return false;
}
public function prices_as_order_line_item_meta($item, $cart_item_key, $values, $order) {
$product = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
$product = wc_get_product($product);
$item->update_meta_data('_puiw_regular', $product->get_regular_price());
$item->update_meta_data('_puiw_sale', $product->is_on_sale() ? $product->get_sale_price() : $product->get_regular_price());
$item->update_meta_data('_puiw_html', $product->get_price_html());
$item->update_meta_data('_puiw_version', $this->version);
}
public function hidden_order_itemmeta($args) {
$args[] = '_puiw_regular';
$args[] = '_puiw_sale';
$args[] = '_puiw_html';
$args[] = '_puiw_version';
return $args;
}
public function woocommerce_order_discount_to_display($total_rows, $order, $tax_display) {
$coupons_code = "yes" === $this->tpl->get_show_coupons_code_at_totals();
$coupons_description = "yes" === $this->tpl->get_show_coupons_description_at_totals();
$coupons_amount = "yes" === $this->tpl->get_show_coupons_amount_at_totals();
$coupons_discount = "yes" === $this->tpl->get_show_coupons_discount_at_totals();
$coupuns_array = array();
$coupons = $order->get_items('coupon');
foreach ($coupons as $item) {
$coupon = new \WC_Coupon($item->get_code());
if ($coupon) {
$coupon_label = _x("Coupon:", "invoice-template", "pepro-ultimate-invoice");
$coupon_display = [];
if ($coupons_code) {
$coupon_label = sprintf(_x("Coupon (%s):", "invoice-template", "pepro-ultimate-invoice"), $coupon->get_code());
}
if ($coupons_amount) {
$coupon_display[] = ("percent" == $coupon->get_discount_type() ? $coupon->get_amount() . "%" : wc_price($coupon->get_amount(), ['currency' => $order->get_currency()]));
}
if ($coupons_discount) {
$coupon_display[] = wc_price($item->get_discount(), array('currency' => $order->get_currency()));
}
if ($coupons_description) {
$coupon_display[] = $coupon->get_description();
}
$coupuns_array["puiw_coupon_" . $item->get_id()] = array(
'label' => $coupon_label,
'value' => implode("<br>", $coupon_display),
);
}
}
$i = 0;
$pos = 0;
foreach ($total_rows as $key => $value) {
$i++;
if ("discount" === $key) {
$pos = $i;
break;
}
}
$total_rows = array_merge(array_slice($total_rows, 0, $pos), $coupuns_array, array_slice($total_rows, $pos));
return $total_rows;
}
/**
* Woocommerce Admin Billing Fields
*
* @method woocommerce_admin_billing_fields
* @param array $ar
* @return array
* @version 1.0.0
* @since 1.3.7
* @license https://pepro.dev/license Pepro.dev License
*/
public function woocommerce_admin_billing_fields($ar) {
if ("yes" == $this->tpl->get_show_user_uin()) {
$default_UIN = "";
if (get_current_user_id()) {
$default_UIN = get_user_meta(get_current_user_id(), "billing_uin", true);
}
$ar['puiw_billing_uin'] = array(
'label' => __('User Unique Identification Number', "pepro-ultimate-invoice"),
'default' => $default_UIN,
'class' => 'long',
);
}
return $ar;
}
/**
* Woocommerce Admin Shipping Fields
*
* @method woocommerce_admin_shipping_fields
* @param array $ar
* @return array
* @version 1.0.0
* @since 1.3.7
* @license https://pepro.dev/license Pepro.dev License
*/
public function woocommerce_admin_shipping_fields($ar) {
$ar['puiw_invoice_shipdaterow'] = array(
"label" => "",
"name" => "",
"style" => "display:none",
"class" => "long persianDatepickerRow",
);
$ar['puiw_invoice_shipdatefa'] = array(
'label' => __('Shipped Date (Shamsi)', "pepro-ultimate-invoice"),
'class' => 'long persianDatepicker disabled',
'placeholder' => __('Select Shipped Date', "pepro-ultimate-invoice"),
'custom_attributes' => array("readonly" => "true"),
);
$ar['puiw_invoice_shipdate'] = array(
'label' => __('Shipped Date (Gregorian)', "pepro-ultimate-invoice"),
'class' => 'long persianDatepicker disabled',
'placeholder' => __('Select Shipped Date', "pepro-ultimate-invoice"),
'custom_attributes' => array("readonly" => "true"),
);
$ar['puiw_invoice_track_id'] = array(
'label' => __('Shipping Track Serial', "pepro-ultimate-invoice"),
'class' => 'long',
'placeholder' => __('Enter Shipping Track Serial', "pepro-ultimate-invoice"),
);
$ar['puiw_customer_signature'] = array(
'label' => __('Customer Signature', "pepro-ultimate-invoice"),
'class' => 'wc-select-uploader',
'style' => 'display:none',
);
return $ar;
}
/**
* print get invoices buttons on view order and order recieved pages
*
* @method woocommerce_order_details_before_order_table
* @param WC_Order $order
* @return string html buttons
* @version 1.0.0
* @since 1.0.0
* @license https://pepro.dev/license Pepro.dev License
*/
public function woocommerce_order_details_before_order_table($order) {
$allowed_statuses = $this->tpl->get_allow_users_use_invoices_criteria("");
echo "<div class='puiw_orders_invoice_btn_container'>";
if (!empty($allowed_statuses) && in_array("wc-{$order->get_status()}", (array) $allowed_statuses)) {
if ($this->print->has_access("HTML", $order)) {
echo '<a style="margin-inline-end: 1rem;-webkit-margin-end: 1rem;" href="' . home_url("?invoice=" . $order->get_order_number()) . '" class="button">' . _x('View Invoice', "order-page", "pepro-ultimate-invoice") . '</a>';
}
if ($this->print->has_access("PDF", $order)) {
echo '<a href="' . home_url("?invoice-pdf=" . $order->get_order_number()) . '" class="button">' . _x('PDF Invoice', "order-page", "pepro-ultimate-invoice") . '</a>';
}
}
echo "</div>";
}
/**
* alter invoice template and colors if pre-invoice is status of order
*
* @method puiw_get_default_dynamic_params
* @param array $opts pre data
* @param WC_Order $order
* @return array filtered data