Skip to content

Instantly share code, notes, and snippets.

@giucu91
Last active November 11, 2022 12:01
Show Gist options
  • Save giucu91/291e752350a110c59b67d84675e3257b to your computer and use it in GitHub Desktop.
Save giucu91/291e752350a110c59b67d84675e3257b to your computer and use it in GitHub Desktop.
Integrare Woo Facturare si WooCommerce SmartBill
<?php
/**
* @copyright Intelligent IT SRL 2018
*/
// Add metabox in order page
function smartbill_order_details_meta_box() {
//afisare doar daca s-a publicat / salvat postarea
if (isset($_GET['post'])){
add_meta_box(
'smartbill_woocommerce_meta_box',
'Facturare SmartBill',
'smartbill_order_details_invoice_box',
'shop_order',
'side',
'high'
);
}
}
// Show button to issue SmartBill invoice and link to invoice in metabox
function smartbill_order_details_invoice_box($post) {
$series = get_post_meta($post->ID, 'smartbill_series_name', true);
$number = get_post_meta($post->ID, 'smartbill_document_number', true);
$document_url = get_post_meta($post->ID, 'smartbill_private_link', true);
if (!empty($document_url)) {
// View invoice link instead of edit
$pattern = '/editare/';
$replacement = 'vizualizare';
$document_url = preg_replace($pattern, $replacement, $document_url, -1 );
echo '<h4>'.$series.' '.$number.'</h4>';
echo '<p>
<a class="button tips reissue" id="smartbill-woocommerce-invoice-button"
data-tip="'.__('Reemite document', 'smartbill-woocommerce').'"
href="'.smartbill_generate_url('smartbill-create', $post->ID).'" target="_blank">'.__('Reemite document', 'smartbill-woocommerce').'</a>
</p><p>
<a class="button button-primary tips" id="smartbill-woocommerce-view-document-button"
data-tip="'.__('Vizualizeaza in SmartBill', 'smartbill-woocommerce').'"
href="'.$document_url.'" target="_blank">'.__('Vizualizeaza in SmartBill', 'smartbill-woocommerce').'</a>
</p>';
} else {
// Generate invoice link
$options = get_option('smartbill_plugin_options_settings');
if (!empty($options) && is_array($options) && isset($options['document_type'])) {
$document_type = $options['document_type'];
} else {
$document_type = Smartbill_Woocommerce_Settings::SMARTBILL_DOCUMENT_TYPE_INVOICE;
}
if ($document_type == Smartbill_Woocommerce_Settings::SMARTBILL_DOCUMENT_TYPE_INVOICE){
$button_label = __('Emite factura in SmartBill', 'smartbill-woocommerce');
}
else {
$button_label = __('Emite proforma in SmartBill', 'smartbill-woocommerce');
}
echo '<p>
<a class="button tips issue" id="smartbill-woocommerce-invoice-button"
data-tip="'.$button_label.'"
href="'.smartbill_generate_url('smartbill-create', $post->ID).'" target="_blank">'.$button_label.'</a>
</p>';
}
}
function smartbill_order_details_invoice_column_button($post) {
$link = get_post_meta($post->ID, 'smartbill_private_link', true);
if (empty($link)) {
// Generate invoice
echo '<p>
<a class="button tips smartbill-woocommerce-invoice-button" data-order="'.$post->ID.'"
data-tip="'.__('Emite in SmartBill', 'smartbill-woocommerce').'"><img src="'.plugin_dir_url(__FILE__).'../assets/images/smb_head.png'.'"/></a>
</p>';
}
}
function smartbill_generate_url($arg_name, $orderId)
{
$action_url = add_query_arg($arg_name, $orderId);
$complete_url = wp_nonce_url($action_url);
return esc_url($complete_url);
}
function smartbill_woocommerce_issue_document(){
check_ajax_referer('smartbill_nonce', 'security');
$data = $_POST['data'];
$order_id = (int) $data['order_id'];
if (! is_numeric($order_id) || ($order_id <= 0)){
$return['status'] = false;
$return['message'] = __('Comanda furnizata este invalida', 'smartbill-woocommerce');
}
else {
$return = smartbill_create_document($order_id);
}
echo json_encode($return);
die();
}
function smartbill_init_plugin_actions() {
// links
if (isset($_GET['smartbill-create'])) {
smartbill_create_document($_GET['smartbill-create']);
}
}
function smartbill_create_client_details($orderId){
$order = new WC_Order($orderId);
$orderMeta = get_post_meta($orderId);
$anafClient = new ANAFAPIClient();
$smartBillClient = array();
$companyName = isset($orderMeta['_billing_company'])?$orderMeta['_billing_company'][0]:'';
// get all counties (judete)
$wc_countries = new WC_Countries();
// get info from order
$city = isset($orderMeta['_billing_city'])?$orderMeta['_billing_city'][0]:'';
$country = isset($orderMeta['_billing_country'])?$orderMeta['_billing_country'][0]:'';
$wc_counties = $wc_countries->get_states($country);
$county = '';
$county_code = isset($orderMeta['_billing_state'])?$orderMeta['_billing_state'][0]:'';
if ( isset($wc_counties[$county_code]) ) {
$county = $wc_counties[$county_code];
$county = remove_accents(html_entity_decode($county));
}
$email = isset($orderMeta['_billing_email'])?$orderMeta['_billing_email'][0]:'';
$options_helper = Facturare_Options_Helper::get_instance();
if ( 'pers-jur' == $options_helper->get_tip( $orderId ) ){
$invoiceName = $companyName;
$cui = $options_helper->get_cui( $orderId );
if ( '-' != $cui && $cui ) {
$vatCode = $cui;
$customerTaxDetails = $anafClient->getVATInfo($vatCode);
$isTaxPayer = $anafClient->isTaxPayer($customerTaxDetails);
$smartBillClient['regCom'] = $options_helper->get_nr_reg_com( $orderId );
$smartBillClient['iban'] = $options_helper->get_iban( $orderId );
$smartBillClient['bank'] = $options_helper->get_nume_banca( $orderId );
}else{
$vatCode = isset($orderMeta['smartbill_cif'])?$orderMeta['smartbill_cif'][0]:'';
$customerTaxDetails = $anafClient->getVATInfo($vatCode);
$isTaxPayer = $anafClient->isTaxPayer($customerTaxDetails);
$smartBillClient['regCom'] = isset($orderMeta['smartbill_regcom'])?$orderMeta['smartbill_regcom'][0]:'';
$smartBillClient['iban'] = isset($orderMeta['smartbill_cont_banca'])?$orderMeta['smartbill_cont_banca'][0]:'';
$smartBillClient['bank'] = isset($orderMeta['smartbill_banca'])?$orderMeta['smartbill_banca'][0]:'';
}
}
else {
$vatCode = "";
$first_name = isset($orderMeta['_billing_first_name'])?$orderMeta['_billing_first_name'][0]:'';
$last_name = isset($orderMeta['_billing_last_name'])?$orderMeta['_billing_last_name'][0]:'';
$invoiceName = $first_name . " " . $last_name;
$isTaxPayer = false;
}
//get all address lines
$address1 = isset($orderMeta['_billing_address_1'])?$orderMeta['_billing_address_1'][0]:'';
$address2 = isset($orderMeta['_billing_address_2'])?$orderMeta['_billing_address_2'][0]:'';
$street = $address1 . " " . $address2;
$smartBillClient['name']= $invoiceName;
$smartBillClient['vatCode']= $vatCode;
$smartBillClient['address']= $street;
$smartBillClient['isTaxPayer']= $isTaxPayer;
$smartBillClient['city']= $city;
$smartBillClient['county']= $county;
$smartBillClient['country']= $country;
$smartBillClient['email']= $email;
$smartBillClient['phone'] = isset($orderMeta['_billing_phone'])?$orderMeta['_billing_phone'][0]:'';
$options = get_option('smartbill_plugin_options_settings');
if (!empty($options) && is_array($options) && isset($options['save_client'])) {
$save_client = $options['save_client'];
} else {
$save_client = 0;
}
$smartBillClient['saveToDb'] = (boolean)$save_client;
return $smartBillClient;
}
function smartbill_create_document($orderId) {
try {
$order = new WC_Order($orderId);
$orderMeta = get_post_meta($orderId);
// build custom fields
$clientDetails = smartbill_create_client_details($orderId);
// get options
$loginOptions = get_option('smartbill_plugin_options');
$options = get_option('smartbill_plugin_options_settings');
$vat_rates = Smartbill_Woocommerce_Settings::get_vat_rates();
$is_vat_payable = Smartbill_Woocommerce_Settings::is_vat_payable();
$documentSettings = smartbill_get_settings_for_order($order, $is_vat_payable);
$existing_products = SmartBillUtils::getOrderProducts($order, $documentSettings);
$products = array();
$product_vat = $documentSettings['product_vat'];
if (empty ($existing_products)) throw new \Exception(__("Eroare la citirea datelor din WooCommerce.", 'smartbill-woocommerce'));
foreach($existing_products as $product){
//convert from stdClass to array
$array_product = json_decode(json_encode($product), true);
if ($is_vat_payable){
if (array_key_exists($product_vat, $vat_rates)){
$selected_vat = $vat_rates[$product_vat];
if (!isset($array_product['taxName'])){
$array_product['taxName'] = $selected_vat['name'];
}
if (!isset($array_product['taxPercentage'])){
$array_product['taxPercentage'] = $selected_vat['percentage'];
}
}
}
$products[] = $array_product;
}
$isDraft = $documentSettings['invoice_is_draft'];
$due_days = $documentSettings['due_days'];
$delivery_days = $documentSettings['delivery_days'];
$show_delivery_days = $documentSettings['show_delivery_days'];
if (empty($due_days)) {
$due_days = 0;
}
if (empty($delivery_days)) {
$delivery_days = 0;
}
$company_vat_code = $loginOptions['vat_code'];
$currency = trim(Smartbill_Woocommerce_Admin_Settings_Fields::get_billing_currency());
$smartbillInvoice = [
'companyVatCode'=> $company_vat_code,
'client' => $clientDetails,
'issueDate' => date('Y-m-d'),
'seriesName' => $documentSettings['document_series'],
'isDraft' => $isDraft ? true: false,
'mentions' => "comanda online invoice ". $orderId,
'observations' => "",
'currency' => $currency,
'products' => $products
];
if ($show_delivery_days){
$smartbillInvoice['deliveryDate'] = date('Y-m-d', time() + absint($delivery_days) * 24 * 3600);
}
//
if ($documentSettings['issue_with_due_date']){
$smartbillInvoice['dueDate'] = date('Y-m-d', time() + absint($due_days) * 24 * 3600);
}
if (isset($documentSettings['useStock'])) {
$smartbillInvoice['useStock'] = $documentSettings['useStock'];
}
// Add order fields for 'TVA la incasare' setting
if ($is_vat_payable) {
$smartbillInvoice['usePaymentTax'] = false;
if ($documentSettings['use_payment_tax']) {
$smartbillInvoice['usePaymentTax'] = true;
$smartbillInvoice['paymentBase'] = 0;
$smartbillInvoice['colectedTax'] = 0;
$smartbillInvoice['paymentTotal'] = 0;
}
}
$client = new SmartBill_Cloud_REST_Client($loginOptions['username'], $loginOptions['password']);
$client->setWoocommerceOrderId($orderId);
$wpSettings = new Smartbill_Woocommerce_Admin_Settings_Fields;
if (defined('WP_DEBUG') && WP_DEBUG){
$debugMode = $wpSettings->get_debugging_mode();
}
else {
$debugMode = false;
}
if ($debugMode) {
$client->setWoocommerceSettingsDetails(SmartBillUtils::export_settings());
$client->setWoocommerceFullDetails(SmartBillUtils::export_order($orderId));
}
$invoiceLogger = new SmartBill_Data_Logger($orderId);
$client->setDataLogger($invoiceLogger);
if ($documentSettings['document_type'] == Smartbill_Woocommerce_Settings::SMARTBILL_DOCUMENT_TYPE_INVOICE){
$serverCall = $client->createInvoiceWithDocumentAddress($smartbillInvoice, $debugMode);
}
else if ($documentSettings['document_type'] == Smartbill_Woocommerce_Settings::SMARTBILL_DOCUMENT_TYPE_ESTIMATE){
$serverCall = $client->createProformaWithDocumentAddress($smartbillInvoice, $debugMode);
}
else {
throw new \Exception(__("Tipul de document emis este invalid.", 'smartbill-woocommerce'));
}
if ($serverCall['errorText']){
$return['status'] = false;
$return['message'] = $serverCall['message'];
$return['error'] = $serverCall['errorText'];
}
else {
$return['status'] = true;
if (isset($serverCall['number']) && ($serverCall['number'])){
$return['message'] = __('Documentul a fost emis cu succes: ', 'smartbill-woocommerce'). $serverCall['message'] . $serverCall['series'] . ' ' . $serverCall['number'] .'.';
$invoiceLogger->set_data($orderId, 'smartbill_invoice_id', $serverCall['number'])
->set_data($orderId, 'smartbill_series', $serverCall['series'])
->set_data($orderId, 'smartbill_document_url', $serverCall['documentUrl'])
->set_data($orderId, 'smartbill_status', Smartbill_Woocommerce_Settings::SMARTBILL_DATABASE_INVOICE_STATUS_FINAL )
->save($orderId);
}
else {
if (isset($serverCall['series'])){
$invoiceLogger->set_data($orderId, 'smartbill_series', $serverCall['series']);
}
$invoiceLogger->set_data($orderId, 'smartbill_document_url', $serverCall['documentUrl']);
$invoiceLogger->set_data($orderId, 'smartbill_status', Smartbill_Woocommerce_Settings::SMARTBILL_DATABASE_INVOICE_STATUS_DRAFT)->save($orderId);
$return['message'] = __('Operatiunea s-a desfasurat cu succes: ', 'smartbill-woocommerce'). $serverCall['message'] ;
}
$return['number'] = $serverCall['number'];
$return['series'] = $serverCall['series'];
$return['status'] = true;
/* translators: Variables `series` and `number` are document info */
$order->add_order_note(sprintf( __('Documentul SmartBill %1$s %2$s a fost creat.', 'smartbill-woocommerce'), $return['series'], $return['number']));
}
} catch (Exception $e) {
$return['error'] = $e->getMessage();
$return['message'] = $e->getMessage();
$return['status'] = false;
}
if (!empty($serverCall['documentUrl'])) {
update_post_meta($orderId, 'smartbill_private_link', $serverCall['documentUrl']);
}
return $return;
}
function smartbill_get_settings_for_order($order, $is_vat_payable){
$loginOptions = get_option('smartbill_plugin_options');
$options = get_option('smartbill_plugin_options_settings');
$admin_settings = new Smartbill_Woocommerce_Admin_Settings_Fields();
if (!empty($options) && is_array($options) && isset($options['document_type'])) {
$document_type = $options['document_type'];
} else {
$document_type = Smartbill_Woocommerce_Settings::SMARTBILL_DOCUMENT_TYPE_INVOICE;
}
if (!empty($options) && is_array($options) && isset($options['stock'])) {
$stock = $options['stock'];
if ($stock == 'fara-gestiune'){
$stock = '';
}
} else {
$stock = '';
}
if (!empty($options) && is_array($options) && isset($options['extra_taxes'])) {
$extra_taxes = $options['extra_taxes'];
} else {
$extra_taxes = array();
}
$doc_type = 'invoice';
if ($options['document_type'] == 1) {
$doc_type = 'estimate';
}
$billing_currency = trim($admin_settings->get_billing_currency());
// generam setarile pentru produse
$documentSettings = array(
'included_vat' => $admin_settings->get_included_vat(),
'included_vat_coupons' => $admin_settings->get_included_vat_coupons(),
'use_payment_tax' => $admin_settings->get_use_payment_tax(),
'shipping_included_vat' => $admin_settings->get_shipping_included_vat(),
'um' => $admin_settings->get_um(),
'saveProductToDb' => $admin_settings->get_save_product(),
'product_vat' => $admin_settings->get_product_vat(),
'isTaxPayer' => $is_vat_payable,
'useStock' => false,
'warehouse' => $stock,
'extraTaxes' => $extra_taxes,
'include_shipping' => $admin_settings->get_include_shipping(),
'taxes' => $order->get_taxes(),
'shipping_vat' => $admin_settings->get_shipping_vat(),
//Intermediary fields for other functions
'companySettings' => array(),
'save_client' => $admin_settings->get_save_client(),
'document_series' => $admin_settings->get_document_series($doc_type),
'document_type' => $document_type,
'billing_currency' => $billing_currency,
'due_days' => $admin_settings->get_due_days(),
'delivery_days' => $admin_settings->get_delivery_days(),
'show_delivery_days' => $admin_settings->get_show_delivery_days(),
'invoice_is_draft' => $admin_settings->get_invoice_is_draft(),
'issue_with_due_date' => $admin_settings->get_issue_with_due_date(),
);
if (! empty($stock) ) {
$documentSettings['useStock'] = true;
}
if ($document_type == 1) {
unset($documentSettings['useStock']);
}
return $documentSettings;
}
function smartbill_add_invoice_column($columns) {
$columns['smartbill_woocommerce_invoice'] = "SmartBill";
return $columns;
}
function smartbill_add_invoice_column_content($column) {
global $post;
switch ($column) {
case 'smartbill_woocommerce_invoice':
$invoice_log = get_post_meta($post->ID, 'smartbill_invoice_log', true);
$document_url = get_post_meta($post->ID, 'smartbill_private_link', true);
//
$series = isset($invoice_log['smartbill_series']) ? $invoice_log['smartbill_series'] : '';
$number = isset($invoice_log['smartbill_invoice_id']) ? $invoice_log['smartbill_invoice_id'] : '';
//Modificam sa duca spre vizualizare, nu spre editare
$pattern = '/editare/';
$replacement = 'vizualizare';
$document_url = preg_replace($pattern, $replacement, $document_url, -1 );
if (!empty($series) && !empty($number) && !empty($document_url)) {
echo '<a href="'.$document_url.'" target="_blank">'.$series.' '.$number.'</a>';
}
break;
case 'wc_actions':
case 'order_actions':
smartbill_order_details_invoice_column_button($post);
break;
}
}
function smartbill_billing_fields_ro($checkout) {
$smartbill_company_details = empty($_POST) ? false : $checkout->get_value('smartbill_company_details');
$admin_settings = new Smartbill_Woocommerce_Admin_Settings_Fields();
if ($admin_settings->get_company_info() == "1"){
echo '<div id="smartbill_billing_fields_ro">
<h3 style="margin:0;padding:0;">
<span>'.__('Doriti facturare pe firma?', 'smartbill-woocommerce').'</span>
<input type="hidden" class="input-checkbox" name="smartbill_company_details" value="1" />
</h3>
<div class="smartbill_company_details">';
if ($admin_settings->get_person_info_for_company() == "1"){
woocommerce_form_field('smartbill_cnp', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('CNP', 'smartbill-woocommerce'),
'placeholder' => __('Cod Numeric Personal', 'smartbill-woocommerce'),
), $checkout->get_value('smartbill_cnp'));
}
if ($admin_settings->get_fiscal_code_for_company() == "1"){
woocommerce_form_field('smartbill_cif', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('CIF', 'smartbill-woocommerce'),
'placeholder' => __('Cod de identificare fiscala', 'smartbill-woocommerce'),
), $checkout->get_value('smartbill_cif'));
}
if ($admin_settings->get_commerce_number_for_company() == "1"){
woocommerce_form_field('smartbill_regcom', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('Nr. inregistrare Registrul Comertului', 'smartbill-woocommerce'),
'placeholder' => __('Nr. inregistrare Registrul Comertului', 'smartbill-woocommerce'),
), $checkout->get_value('smartbill_regcom'));
}
if ($admin_settings->get_iban_for_company() == "1"){
woocommerce_form_field('smartbill_cont_banca', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('Cont bancar', 'smartbill-woocommerce'),
'placeholder' => __('Cont bancar', 'smartbill-woocommerce'),
), $checkout->get_value('smartbill_cont_banca'));
}
if ($admin_settings->get_bank_for_company() == "1"){
woocommerce_form_field('smartbill_banca', array(
'type' => 'text',
'class' => array('form-row-wide'),
'label' => __('Banca', 'smartbill-woocommerce'),
'placeholder' => __('Banca', 'smartbill-woocommerce'),
), $checkout->get_value('smartbill_banca'));
}
echo '</div></div>';
}
}
function smartbill_billing_fields_ro_update_user_meta($userId) {
if ($userId && isset($_POST['smartbill_cnp'])) {
update_user_meta($userId, 'smartbill_cnp', esc_attr($_POST['smartbill_cnp']));
}
if ($userId && isset($_POST['smartbill_cif'])) {
update_user_meta($userId, 'smartbill_cif', esc_attr($_POST['smartbill_cif']));
}
if ($userId && isset($_POST['smartbill_regcom'])) {
update_user_meta($userId, 'smartbill_regcom', esc_attr($_POST['smartbill_regcom']));
}
if ($userId && isset($_POST['smartbill_cont_banca'])) {
update_user_meta($userId, 'smartbill_cont_banca', esc_attr($_POST['smartbill_cont_banca']));
}
if ($userId && isset($_POST['smartbill_banca'])) {
update_user_meta($userId, 'smartbill_banca', esc_attr($_POST['smartbill_banca']));
}
}
function smartbill_billing_fields_ro_update_order_meta($orderId) {
if (isset($_POST['smartbill_cnp'])) {
update_post_meta($orderId, 'smartbill_cnp', esc_attr($_POST['smartbill_cnp']));
}
if (isset($_POST['smartbill_cif'])) {
update_post_meta($orderId, 'smartbill_cif', esc_attr($_POST['smartbill_cif']));
}
if (isset($_POST['smartbill_regcom'])) {
update_post_meta($orderId, 'smartbill_regcom', esc_attr($_POST['smartbill_regcom']));
}
if (isset($_POST['smartbill_cont_banca'])) {
update_post_meta($orderId, 'smartbill_cont_banca', esc_attr($_POST['smartbill_cont_banca']));
}
if (isset($_POST['smartbill_banca'])) {
update_post_meta($orderId, 'smartbill_banca', esc_attr($_POST['smartbill_banca']));
}
}
function smartbill_billing_fields_ro_order_meta_keys($keys) {
$keys[__('CNP', 'smartbill-woocommerce')] = 'smartbill_cnp';
$keys[__('CIF', 'smartbill-woocommerce')] = 'smartbill_cif';
$keys[__('Nr. inregistrare Registrul Comertului', 'smartbill-woocommerce')] = 'smartbill_regcom';
$keys[__('Cont bancar', 'smartbill-woocommerce')] = 'smartbill_cont_banca';
$keys[__('Banca', 'smartbill-woocommerce')] = 'smartbill_banca';
return $keys;
}
if (
in_array(
'woocommerce/woocommerce.php',
apply_filters('active_plugins', get_option('active_plugins'))
)
) {
//Billing fields RO
add_action('woocommerce_after_order_notes', 'smartbill_billing_fields_ro');
add_action('woocommerce_checkout_update_user_meta', 'smartbill_billing_fields_ro_update_user_meta');
add_action('woocommerce_checkout_update_order_meta', 'smartbill_billing_fields_ro_update_order_meta');
add_filter('woocommerce_email_order_meta_keys', 'smartbill_billing_fields_ro_order_meta_keys');
add_filter('manage_edit-shop_order_columns', 'smartbill_add_invoice_column', 11);
add_action('manage_shop_order_posts_custom_column', 'smartbill_add_invoice_column_content', 11, 2);
add_action('add_meta_boxes', 'smartbill_order_details_meta_box');
// afisare buton de emitere factura in comenzi
add_action('init', 'smartbill_init_plugin_actions');
add_action('wp_ajax_smartbill_woocommerce_issue_document', 'smartbill_woocommerce_issue_document');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment