Plugin Directory

Changeset 2526532


Ignore:
Timestamp:
05/05/2021 09:50:42 AM (5 years ago)
Author:
phcwordpress
Message:

2021-05-05 update

Location:
drivefx-woocommerce/trunk
Files:
18 edited

Legend:

Unmodified
Added
Removed
  • drivefx-woocommerce/trunk/PHCLibrary/authentication.php

    r2456866 r2526532  
    1818    *                          ---  LOGIN ---                           *
    1919    ********************************************************************/
    20     public function PHCLogin($ch,$credentials){   
    21         $this->url = $credentials->backendUrl."/REST/UserLoginWS/userLoginCompany"; 
     20    public function PHCLogin($ch,$credentials){
     21        $this->url = $credentials->backendUrl."/REST/UserLoginWS/userLoginCompany";
    2222
    2323        // Create map with request parameters
    24         $this->params = array(  'userCode' => $credentials->userCode, 
    25                                 'password' => $credentials->password, 
     24        $this->params = array(  'userCode' => $credentials->userCode,
     25                                'password' => $credentials->password,
    2626                                'applicationType' => $credentials->appId,
    2727                                'company' => $credentials->company
     
    4646            curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    4747            curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    48             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts         
    49        
     48            curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
     49
    5050            return $ch;
    5151    }
     
    5454    *                         ---  LOGOUT ---                          *
    5555    ********************************************************************/
    56     function PHCLogout($ch, $credentials){ 
     56    function PHCLogout($ch, $credentials){
    5757        $this->url = $credentials->backendUrl."/REST/UserLoginWS/userLogout";
    5858        curl_setopt($ch, CURLOPT_URL, $this->url);
     
    6363
    6464    }
    65 
    66 
    6765}
    6866?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/bill.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Bill {
    6 
    73    public $country;
    84    public $nome;
     
    139    public $telefone;
    1410    public $codpost;
    15     public $ncont;   
     11    public $ncont;
    1612}
    17 
    18 
    19 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/customer.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Customer {
    6 
    73    public $nome;
    84    public $email;
     
    1612    public $country;
    1713    public $user_email;
    18    
    1914}
    20 
    21 
    22 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/invoice.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Invoice {
    6 
    73    public $country;
    84    public $shipping_country;
     
    139    public $billing_name;
    1410    public $billing_email;
    15     public $billing_address_1;   
    16     public $billing_city;   
    17     public $billing_phone;   
    18     public $billing_postcode;     
    19     public $billing_nif;     
     11    public $billing_address_1;
     12    public $billing_city;
     13    public $billing_phone;
     14    public $billing_postcode;
     15    public $billing_nif;
    2016}
    21 
    22 
    23 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/order.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Order {
    6 
    73    public $post_Id;
    84    public $doc_Id;
     
    139    public $obs;
    1410    public $order_received;
    15     public $nextPostId;   
    16     public $fee_name;   
    17     public $fee_value;   
     11    public $nextPostId;
     12    public $fee_name;
     13    public $fee_value;
    1814}
    19 
    20 
    21 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/settings.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Settings {
    6 
    73    public $createInvoice;
    84    public $typeOfInvoice;
     
    106    public $fieldNif;
    117    public $includeTaxonSendCost;
    12     public $createExemptCl;
     8    public $createExemptPT;
     9    public $createExemptEU;
     10    public $createExemptCO;
    1311    public $typeOfReason;
     12    public $typeOfReasonEU;
     13    public $typeOfReasonCO;
    1414    public $warehouseOrder;
    1515    public $typeOfOrder;
     
    2323    public $warehouse;
    2424    public $sendInvoice;
    25 
    2625 }
    27 
    28 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/classes/shipping.php

    r2456866 r2526532  
    1 
    21<?php
    3 
    4 
    52class Shipping {
    6 
    73    public $paisto;
    84    public $moradato;
     
    139    public $shipping_tax;
    1410    public $shipping_country;
    15     public $shipping_value;   
     11    public $shipping_value;
    1612}
    17 
    18 
    19 ?>
  • drivefx-woocommerce/trunk/PHCLibrary/customers.php

    r2456866 r2526532  
    1313        $this->logs = new Logs();
    1414        $this->auth_services = new AuthentificationService();
    15         $this->utils_services = new UtilsServices();       
     15        $this->utils_services = new UtilsServices();
    1616
    1717    }
    18    
    19     public function processCustomer($ch, $credentials, $dataPack, $tip_button) { 
     18
     19    public function processCustomer($ch, $credentials, $dataPack, $tip_button) {
    2020        ###
    21         $customer = $dataPack->customer; 
    22        
    23         $tip_button = false; 
     21        $customer = $dataPack->customer;
     22
     23        $tip_button = false;
    2424        # If Email exists
    2525        if($customer->user_email != ''){
    2626
    27             # Verify if customer already exists in software 
    28             if( $customer->email != ''){     
     27            # Verify if customer already exists in software
     28            if( $customer->email != ''){
    2929                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Cl', 'email', $customer->email);
    3030            } else {
     
    3232            }
    3333            //$this->logs->writeFileLog('Cl Checking:', $response);
    34            
     34
    3535            if (curl_error($ch)) {
    3636                $this->logs->writeFileLog('Cl Checking', $ch);
    3737            } else if(empty($response)){
    38                 $this->logs->writeFileLog('Cl Checking', 'EMPTY RESPONSE');         
     38                $this->logs->writeFileLog('Cl Checking', 'EMPTY RESPONSE');
    3939            } else {
    4040                if($tip_button == false){
     
    4343
    4444                        //Save number id of client
    45                         $customer->no = $response['result'][0]['no']; 
    46                            
     45                        $customer->no = $response['result'][0]['no'];
     46
    4747                        # Update Customer
    48                         $updatedCustomer = $this->updateCustomer($ch, $credentials, $dataPack, $response); 
     48                        $updatedCustomer = $this->updateCustomer($ch, $credentials, $dataPack, $response);
    4949
    5050                        if (curl_error($ch)) {
    5151                            $this->logs->writeFileLog('ClUpdate', $ch);
    5252                        } else if(empty($response)){
    53                             $this->logs->writeFileLog('ClUpdate', 'EMPTY RESPONSE');               
     53                            $this->logs->writeFileLog('ClUpdate', 'EMPTY RESPONSE');
    5454                        } else {
    5555                            $returnCustomer = $updatedCustomer;
    56                         }     
    57                                                            
     56                        }
     57
    5858                    # If the customer not exists
    59                     } else{               
     59                    } else{
    6060                        #Create a new customer
    6161                        $createdCustomer = $this->createCustomer($ch, $credentials, $dataPack);
     
    6666                            $this->logs->writeFileLog('NewCl', $ch);
    6767                        } else if(empty($response)){
    68                             $this->logs->writeFileLog('NewCl', 'EMPTY RESPONSE');               
     68                            $this->logs->writeFileLog('NewCl', 'EMPTY RESPONSE');
    6969                        } else {
    7070                            $returnCustomer = $createdCustomer;
    71                         }     
    72 
    73                     } 
    74                 }   
     71                        }
     72
     73                    }
     74                }
    7575            }
    7676        # If Email not exists
     
    8484                $this->logs->writeFileLog('Gen_Cl Checking', $ch);
    8585            } else if(empty($response)){
    86                 $this->logs->writeFileLog('Gen_Cl Checking', 'EMPTY RESPONSE');         
    87             } else { 
     86                $this->logs->writeFileLog('Gen_Cl Checking', 'EMPTY RESPONSE');
     87            } else {
    8888                //return (object) $response['result'][0];
    8989
     
    102102                        $this->logs->writeFileLog('gen_clNewInstance', $ch);
    103103                    } else if(empty($response)){
    104                         $this->logs->writeFileLog('gen_clNewInstance', 'EMPTY RESPONSE');             
     104                        $this->logs->writeFileLog('gen_clNewInstance', 'EMPTY RESPONSE');
    105105                    } else {
    106106                        // Generic Customer data
     
    108108                        $response['result'][0]['clivd'] = true;
    109109                        $response['result'][0]['preco'] = $customer->preco;
    110                                                                          
    111                         // Save Instance in Software PHC 
    112                         $responseGenCl = $this->utils_services->paramsSave($ch, $credentials, 'ClWS', $response);   
    113            
    114                         //$this->logs->writeFileLog('genCl Save:', $response); 
     110
     111                        // Save Instance in Software PHC
     112                        $responseGenCl = $this->utils_services->paramsSave($ch, $credentials, 'ClWS', $response);
     113
     114                        //$this->logs->writeFileLog('genCl Save:', $response);
    115115
    116116                        if (curl_error($ch)) {
    117117                            $this->logs->writeFileLog('genCl_Save', $ch);
    118118                        } else if(empty($responseGenCl)){
    119                             $this->logs->writeFileLog('genCl_Save', 'EMPTY RESPONSE');                                                   
     119                            $this->logs->writeFileLog('genCl_Save', 'EMPTY RESPONSE');
    120120                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    121121                            $this->writeFileLog('genCl_Save', $responseGenCl['messages'][0]['messageCodeLocale']);
    122122                        } else {
    123123                            //Return object
    124                             return (object) $responseGenCl['result'][0];                   
     124                            return (object) $responseGenCl['result'][0];
    125125                        }
    126                     } 
    127                 }           
    128             }
    129         } 
    130            
    131         return $returnCustomer;         
     126                    }
     127                }
     128            }
     129        }
     130
     131        return $returnCustomer;
    132132    }
    133133
     
    142142             $this->logs->writeFileLog('clNewInstance', $ch);
    143143         } else if(empty($response)){
    144              $this->logs->writeFileLog('clNewInstance', 'EMPTY RESPONSE');             
     144             $this->logs->writeFileLog('clNewInstance', 'EMPTY RESPONSE');
    145145         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    146              $this->logs->writeFileLog('clNewInstance', $response['messages'][0]['messageCodeLocale']);             
     146             $this->logs->writeFileLog('clNewInstance', $response['messages'][0]['messageCodeLocale']);
    147147         } else {
    148148            //Save number id of client
     
    176176                $response['result'][0]['preco'] = $customer->preco;
    177177            }
    178                
    179             # get country and country stamp in accordance with Phc
     178
     179            # set country in accordance with Phc
    180180            if($customer->country != ''){
    181                 $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', $customer->country);
    182             }else if($customer->country == "GB") {
    183                 $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', "UK");
     181                if($customer->country == "GB") {
     182                    $customerCountry = "UK";
     183                } else {
     184                    $customerCountry = $customer->country;
     185                }
    184186            }else{
    185                 $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', "PT");
    186             }
     187                $customerCountry = "PT";
     188            }
     189            // Get country data
     190            $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', $customerCountry);
     191
     192            //$this->logs->writeFileLog('countries', $responseCountry);
    187193
    188194            if (curl_error($ch)) {
     
    194200                $customer->nomePais = $responseCountry['result'][0]['nome'];
    195201            }
    196          
     202
    197203            if(isset($customer->paisesstamp)) {
    198204                $response['result'][0]['paisesstamp'] =  $customer->paisesstamp;
     
    201207                $response['result'][0]['pais'] =  $customer->nomePais;
    202208                $response['result'][0]['pncont'] =  $responseCountry['result'][0]['pncont'];
    203             }         
    204              # Tax free customer
    205              if ($dataPack->settings->createExemptCl){
     209            }
     210
     211             # Tax free customer outside of PT
     212             if ($dataPack->settings->createExemptPT){
    206213                if($customer->country !="PT") {
    207214                    $response['result'][0]['tabiva'] = 4;
    208215                    $response['result'][0]['codmotiseimp'] = $dataPack->settings->typeOfReason;
    209                
    210                 // GEt table of Free Tax data
    211                 $responseReason = $this->utils_services->filterItem_Query($ch, $credentials, 'Miseimp', 'codigo', $dataPack->settings->typeOfReason);
     216
     217                    // GEt table of Free Tax data
     218                    $responseReason = $this->utils_services->filterItem_Query($ch, $credentials, 'Miseimp', 'codigo', $dataPack->settings->typeOfReason);
    212219
    213220                    if(isset($customer->nomePais)) {
     
    216223                    } else {
    217224                        $this->logs->writeFileLog('responseReason:', 'Erro on receive Free Tax Reason Data');
    218                     }                   
    219                 }
    220             }   
    221              
    222             # Save Instance in Software PHC
    223             $paramsSaveResponse = $this->utils_services->paramsSave($ch, $credentials, 'ClWS', $response); 
    224  
    225             //$this->logs->writeFileLog('clSave:', $paramsSaveResponse);
     225                    }
     226                }
     227            }
     228            # Tax free customer outside of EU
     229            if ($dataPack->settings->createExemptEU){
     230                if ($responseCountry['result'][0]['ueMember'] != 1 && $customer->country !="PT"){
     231                    $response['result'][0]['tabiva'] = 4;
     232                    $response['result'][0]['codmotiseimp'] = $dataPack->settings->typeOfReasonEU;
     233
     234                    // GEt table of Free Tax data
     235                    $responseReason = $this->utils_services->filterItem_Query($ch, $credentials, 'Miseimp', 'codigo', $dataPack->settings->typeOfReasonEU);
     236
     237                    if(isset($customer->nomePais)) {
     238                        $response['result'][0]['motiseimp'] = $responseReason['result'][0]['descricao'];
     239                        $response['result'][0]['miseimpstamp'] = $responseReason['result'][0]['miseimpstamp'];
     240                    } else {
     241                        $this->logs->writeFileLog('responseReason.1:', 'Erro on receive Free Tax Reason Data');
     242                    }
     243                }
     244            }
     245
     246            # Tax free companies from EU
     247            if ($dataPack->settings->createExemptCO){
     248                // if is from UE mermber Country
     249                if ($responseCountry['result'][0]['ueMember'] == 1){
     250                    //check if it is a company or a private client (via VIES)
     251                    $checkVAT = $this->utils_services->viesCheckVAT($responseCountry['result'][0]['nomeabrv'], $customer->ncont);
     252
     253                    if ($checkVAT['valid'] == "true"){
     254                        $response['result'][0]['tabiva'] = 4;
     255                        $response['result'][0]['codmotiseimp'] = $dataPack->settings->typeOfReasonCO;
     256
     257                        // GEt table of Free Tax data
     258                        $responseReason = $this->utils_services->filterItem_Query($ch, $credentials, 'Miseimp', 'codigo', $dataPack->settings->typeOfReasonCO);
     259
     260                        if(isset($customer->nomePais)) {
     261                            $response['result'][0]['motiseimp'] = $responseReason['result'][0]['descricao'];
     262                            $response['result'][0]['miseimpstamp'] = $responseReason['result'][0]['miseimpstamp'];
     263                        } else {
     264                            $this->logs->writeFileLog('responseReason.2:', 'Erro on receive Free Tax Reason Data');
     265                        }
     266                    }
     267                }
     268            }
     269
     270            # Save Instance in Software PHC
     271            $paramsSaveResponse = $this->utils_services->paramsSave($ch, $credentials, 'ClWS', $response);
     272
     273            //$this->logs->writeFileLog('clSave:', $paramsSaveResponse);
    226274
    227275             if (curl_error($ch)) {
    228276                 $this->logs->writeFileLog('clSave', $ch);
    229277             } else if(empty($paramsSaveResponse)){
    230                  $this->logs->writeFileLog('clSave', 'EMPTY RESPONSE');               
     278                 $this->logs->writeFileLog('clSave', 'EMPTY RESPONSE');
    231279             } else {
    232                
     280
    233281                return (object) $paramsSaveResponse['result'][0];
    234282             }
    235          } 
     283         }
    236284
    237285    }
     
    241289        $customer = $dataPack->customer;
    242290
    243         $mustUpdateCl = false; 
    244        
    245         #Update customer data 
     291        $mustUpdateCl = false;
     292
     293        #Update customer data
    246294        if(isset($customer->nome) && $response['result'][0]['nome'] !== $customer->nome) {
    247295            $response['result'][0]['nome'] = $customer->nome;
    248296            $mustUpdateCl = true;
    249         } 
     297        }
    250298        if(isset($customer->morada) && $response['result'][0]['morada'] !== $customer->morada) {
    251299           $response['result'][0]['morada'] = $customer->morada;
     
    263311           $response['result'][0]['telefone'] = $customer->telefone;
    264312            $mustUpdateCl = true;
    265         }                     
     313        }
    266314        if(isset($customer->codpost) && $response['result'][0]['codpost'] !== $customer->codpost) {
    267315           $response['result'][0]['codpost'] = $customer->codpost;
     
    272320            $mustUpdateCl = true;
    273321        }
    274          //get country and country stamp 
     322         //get country and country stamp
    275323         if($customer->country != ''){
    276324            $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', $customer->country);
     
    280328            $responseCountry = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', "PT");
    281329        }
    282        
     330
    283331        //check the response
    284332        if (curl_error($ch)) {
     
    290338            $customer->nomePais = $responseCountry['result'][0]['nome'];
    291339        }
    292    
     340
    293341        //fulfill customer data
    294342        if(isset($customer->paisesstamp) && $response['result'][0]['paisesstamp'] !== $customer->paisesstamp) {
     
    300348             $mustUpdateCl = true;
    301349         }
    302        
     350
    303351        if (!$mustUpdateCl) {
    304352            return $customer;
    305353        }
    306        
     354
    307355        //Set Operation to 2 to make the Update
    308         $response['result'][0]['Operation']= 2; 
    309 
    310         # Save Instance in Software PHC 
     356        $response['result'][0]['Operation']= 2;
     357
     358        # Save Instance in Software PHC
    311359        $paramsSaveResponse = $this->utils_services->paramsSave($ch, $credentials, 'ClWS', $response);
    312            
    313         //$this->logs->writeFileLog('ClUpdate Save:', $paramsSaveResponse); 
     360
     361        //$this->logs->writeFileLog('ClUpdate Save:', $paramsSaveResponse);
    314362
    315363        if (curl_error($ch)) {
    316364            $this->logs->writeFileLog('Cl_UpdateSave', $ch);
    317365        } else if(empty($paramsSaveResponse)){
    318             $this->logs->writeFileLog('Cl_UpdateSave', 'EMPTY RESPONSE');               
     366            $this->logs->writeFileLog('Cl_UpdateSave', 'EMPTY RESPONSE');
    319367        } else {
    320368            return (object) $paramsSaveResponse['result'][0];
  • drivefx-woocommerce/trunk/PHCLibrary/invoices.php

    r2456866 r2526532  
    1 <?php 
     1<?php
    22require_once 'log.php';
    33require_once 'authentication.php';
     
    1515        $this->logs = new Logs();
    1616        $this->auth_services = new AuthentificationService();
    17         $this->utils_services = new UtilsServices();       
    18         $this->customers_services = new CustomersServices();       
     17        $this->utils_services = new UtilsServices();
     18        $this->customers_services = new CustomersServices();
    1919    }
    2020
     
    4646                $paisesstamp = $response['result'][0]['paisesstamp'];
    4747                $nomePais = $response['result'][0]['nome'];
    48             }               
     48            }
    4949            ###
    5050            $_shipping_country = $ft->shipping_country;
     
    5555
    5656            //$this->logs->writeFileLog('shippingCountry response:', $response);
    57            
     57
    5858            if (curl_error($ch)) {
    5959                $this->logs->writeFileLog('addSimpleFT3', $ch);
     
    6868
    6969            # get current customer data
    70             $newCustomer = $this->customers_services->processCustomer($ch, $credentials, $dataPack, $tip_button);   
     70            $newCustomer = $this->customers_services->processCustomer($ch, $credentials, $dataPack, $tip_button);
    7171
    7272            //$this->logs->writeFileLog('newCustomer:', $newCustomer);
     
    7575                $this->logs->writeFileLog('getCustomer', $ch);
    7676            } else if(empty($newCustomer)){
    77                 $this->logs->writeFileLog('getCustomer', 'EMPTY RESPONSE');               
     77                $this->logs->writeFileLog('getCustomer', 'EMPTY RESPONSE');
    7878            } else {
    79                 if($newCustomer->no != ''){               
     79                if($newCustomer->no != ''){
    8080                    //Inserted client in bd
    8181                    $createClientSuccess = 1;
    82                 }                   
    83             }
    84             #If client is created/obtained with success 
    85             if($createClientSuccess == 1){ 
     82                }
     83            }
     84            #If client is created/obtained with success
     85            if($createClientSuccess == 1){
    8686                //Obtain new instance of invoice
    8787                $response = $this->utils_services->paramsNewInstance($ch, $credentials, 'FtWS', $settings->typeOfInvoice);
    88                
     88
     89                //Clear the product lines
     90                $response['result'][0]['fis'] = [];
     91
    8992                //$this->logs->writeFileLog('FtWs Response', $response);
    9093
     
    9295                    $this->logs->writeFileLog('addSimpleFT11', $ch);
    9396                } else if(empty($response)){
    94                     $this->logs->writeFileLog('addSimpleFT11', 'EMPTY RESPONSE');         
     97                    $this->logs->writeFileLog('addSimpleFT11', 'EMPTY RESPONSE');
    9598                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    96                     $this->logs->writeFileLog('addSimpleFT11', $response['messages'][0]['messageCodeLocale']);         
    97                 } else {     
     99                    $this->logs->writeFileLog('addSimpleFT11', $response['messages'][0]['messageCodeLocale']);
     100                } else {
    98101                    #Save number of client in FT
    99102                    $response['result'][0]['no'] = $newCustomer->no;
     
    101104                    #actEntity
    102105                    $response = $this->utils_services->actEntity($ch, $credentials, 'FtWS', $response);
    103            
     106
    104107                    //$this->logs->writeFileLog('actEntity:', $response);
    105108
     
    107110                        $this->logs->writeFileLog('addSimpleFT13', $ch);
    108111                    } else if(empty($response)){
    109                         $this->logs->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');             
     112                        $this->logs->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');
    110113                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    111                         $this->logs->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);             
     114                        $this->logs->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);
    112115                    } else {
    113116                        ###
    114117                        $cart = $ft->cart;
    115                        
     118
    116119                        // Only If have articles to FT
    117120                        if(!empty($cart)){
    118121                            foreach ($cart as $product) {
    119122                                //product
    120                                 if($product['qtt']*$product['epv'] != 0){                       
    121                                     $fi = new stdClass(); 
    122            
     123                                if($product['qtt']*$product['epv'] != 0){
     124                                    $fi = new stdClass();
     125
    123126                                    $fi->ref =  $product['ref'];
    124127                                    $fi->design = $product['design'];
     
    143146                                    if($settings->feesName != "") {
    144147                                        $fi->ref = $settings->feesName;
    145                                     } 
     148                                    }
    146149
    147150                                    // IVA
    148151                                    if ($settings->includeTaxonSendCost == "true") {
    149152                                        $fi->ivaincl=true;
    150                                     }                                                                                 
     153                                    }
    151154                                    if ($fi->etiliquido == 0) {
    152155                                        $fi->qtt = 0;
    153156                                        $fi->ivaincl = false;
    154                                     }                                               
    155                                     $response['result'][0]['fis'][]= $fi;   
     157                                    }
     158                                    $response['result'][0]['fis'][]= $fi;
    156159                                }
    157160                            }
     
    162165                                if($settings->shippingName != "") {
    163166                                    $fi->ref = $settings->shippingName;
    164                                 } 
    165        
     167                                }
     168
    166169                                $fi->design = $ft->shipping_name;
    167170                                $fi->qtt = 1;
    168                                                              
     171
    169172                                // IVA
    170173                                if($settings->includeTaxonSendCost == "true") {
    171174                                    $fi->ivaincl=true;
    172                                 }                                                                                 
     175                                }
    173176                                if($fi->etiliquido == 0){
    174177                                    $fi->qtt = 0;
    175178                                    $fi->ivaincl = false;
    176                                 }   
    177                                 $response['result'][0]['fis'][]= $fi;   
     179                                }
     180                                $response['result'][0]['fis'][]= $fi;
    178181                            }
    179182                            //actEntity
    180183                            $response2 = $this->utils_services->actEntity($ch, $credentials, 'FtWS', $response);
    181                            
     184
    182185                            // shipping value
    183186                            foreach ($response2['result'][0]['fis'] as &$delivery) {
     
    187190                                    $delivery['etiliquido'] = $shipping->shipping_value;
    188191                                    $delivery['epv'] = $shipping->shipping_value;
    189                                 }               
    190                             }
    191        
     192                                }
     193                            }
     194
    192195                            #actEntity
    193196                            $response = $this->utils_services->actEntity($ch, $credentials, 'FtWS', $response2);
    194            
     197
    195198                            //$this->logs->writeFileLog('actEntity1:', $response);
    196199
     
    198201                                $this->logs->writeFileLog('addSimpleFT12', $ch);
    199202                            } else if(empty($response)){
    200                                 $this->logs->writeFileLog('addSimpleFT12', 'EMPTY RESPONSE');         
     203                                $this->logs->writeFileLog('addSimpleFT12', 'EMPTY RESPONSE');
    201204                            } else if(isset($response['messages'][0]['messageCodeLocale']) && $response['messages'][0]['messageCode']!='messages.Business.Stocks.InvalidRefAutoCreate'){
    202                                
    203                                 $this->logs->writeFileLog('addSimpleFT12', $response['messages'][0]['messageCodeLocale']);         
     205
     206                                $this->logs->writeFileLog('addSimpleFT12', $response['messages'][0]['messageCodeLocale']);
    204207                            } else {
    205208                                # Billing data
    206209                                $response['result'][0]['nome2'] = $ft->billing_name;
    207                                 $response['result'][0]['morada'] = $ft->billing_address_1; 
     210                                $response['result'][0]['morada'] = $ft->billing_address_1;
    208211                                $response['result'][0]['local'] = $ft->billing_city;
    209212                                $response['result'][0]['provincia'] = $ft->billing_city;
     
    215218                                $response['result'][0]['codpostto'] = $shipping->codpostto;
    216219                                $response['result'][0]['pais'] = $nomePais;
    217                                 $response['result'][0]['paisesstamp'] = $paisesstamp; 
     220                                $response['result'][0]['paisesstamp'] = $paisesstamp;
    218221                                $response['result'][0]['paisto'] = $nomePaisShipping;
    219                                 $response['result'][0]['paisesstampto'] = $paisesstampShipping;   
     222                                $response['result'][0]['paisesstampto'] = $paisesstampShipping;
    220223
    221224                                # Eliminate comercial discount
     
    235238                                            //Eliminate discount in field "desc6"
    236239                                            $response['result'][0]['fis'][$key]['desc6'] = 0;
    237                                            
     240
    238241                                            //Eliminate financial discount of client
    239                                             $response['result'][0]['efinv'] = 0; 
    240                                             $response['result'][0]['fin'] = 0; 
     242                                            $response['result'][0]['efinv'] = 0;
     243                                            $response['result'][0]['fin'] = 0;
    241244                                        }
    242245                                    }
    243246                                }
    244                            
     247
    245248                                #actEntity
    246249                                $response = $this->utils_services->actEntity($ch, $credentials, 'FtWS', $response);
    247                
     250
    248251                                //$this->logs->writeFileLog('actEntity2:', $response);
    249252
     
    251254                                    $this->logs->writeFileLog('addSimpleFT13', $ch);
    252255                                } else if(empty($response)){
    253                                     $this->logs->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');             
     256                                    $this->logs->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');
    254257                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    255                                     $this->logs->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);             
     258                                    $this->logs->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);
    256259                                } else {
    257260                                    //Save Invoice
    258261                                    $response = $this->utils_services->paramsSave($ch, $credentials, 'FtWS', $response);
    259                                                            
     262
    260263                                    //$this->logs->writeFileLog('saveFt:', $response);
    261264
     
    263266                                        $this->logs->writeFileLog('addSimpleFT14', $ch);
    264267                                    } else if(empty($response)){
    265                                         $this->logs->writeFileLog('addSimpleFT14', 'EMPTY RESPONSE');               
     268                                        $this->logs->writeFileLog('addSimpleFT14', 'EMPTY RESPONSE');
    266269                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    267                                         $this->logs->writeFileLog('addSimpleFT14', $response['messages'][0]['messageCodeLocale']);               
     270                                        $this->logs->writeFileLog('addSimpleFT14', $response['messages'][0]['messageCodeLocale']);
    268271                                    } else {
    269272                                        //Enable to sign Document
    270                                         if($response['result'][0]['draftRecord'] == 1){ 
     273                                        if($response['result'][0]['draftRecord'] == 1){
    271274                                            //Save ftstamp of invoice
    272275                                            $_SESSION['ftstamp'] = $response['result'][0]['ftstamp'];
    273                                             $_SESSION['fno'] =  $response['result'][0]['fno'];                                     
     276                                            $_SESSION['fno'] =  $response['result'][0]['fno'];
    274277
    275278                                            //Sign document
     
    286289                                                $this->logs->writeFileLog('addSimpleFT15', $ch);
    287290                                            } else if(empty($response)){
    288                                                 $this->logs->writeFileLog('addSimpleFT15', 'EMPTY RESPONSE');                   
     291                                                $this->logs->writeFileLog('addSimpleFT15', 'EMPTY RESPONSE');
    289292                                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    290                                                 $this->logs->writeFileLog('addSimpleFT15', $response['messages'][0]['messageCodeLocale']);                   
     293                                                $this->logs->writeFileLog('addSimpleFT15', $response['messages'][0]['messageCodeLocale']);
    291294                                            } else {
    292                                                 $this->logs->writeFileLog('addNewOrder17', "Signed invoice: ".$response['result'][0]['fno'] );
     295                                                $this->logs->writeFileLog('addSimpleFT16', "Invoice number: ".$response['result'][0]['fno']." was created!" );
    293296
    294297                                                return $response;
    295298                                            }
    296299                                        } else {
    297                                             return $response;                                         
    298                                         } 
     300                                            return $response;
     301                                        }
    299302                                    }
    300303                                }
    301304                            }
    302305                        }
    303                     }           
     306                    }
    304307                }
    305             }                         
     308            }
    306309        }
    307310    }
     
    310313        ###
    311314        $settings =  $dataPack->settings;
    312        
     315
    313316        if(empty($settings->typeOfInvoice) || $settings->typeOfInvoice == 0){
    314317            $this->logs->writeFileLog('addInternalDocumentInvoice', 'Empty type of invoice');
     
    316319            //Obtain new instance of FT based in Bo(bostamp)
    317320            $response = $this->utils_services->paramsNewInstanceFromReference($ch, $credentials, $response['bostamp']);
    318            
     321
    319322            //$this->logs->writeFileLog('instanceFromReference:', $response);
    320323
     
    322325                $this->logs->writeFileLog('addInternalDocumentInvoice2', $ch);
    323326            } else if(empty($response)){
    324                 $this->logs->writeFileLog('addInternalDocumentInvoice2', 'EMPTY RESPONSE');       
    325             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    326                 $this->logs->writeFileLog('addInternalDocumentInvoice2', $response['messages'][0]['messageCodeLocale']);       
     327                $this->logs->writeFileLog('addInternalDocumentInvoice2', 'EMPTY RESPONSE');
     328            } else if(isset($response['messages'][0]['messageCodeLocale']) && $response['messages'][0]['messageCode'] != "info.Business.Stocks.RefWithoutStock"){
     329                $this->logs->writeFileLog('addInternalDocumentInvoice2', $response['messages'][0]['messageCodeLocale']);
    327330            } else {
    328331                //Save id of customer
    329                 $_SESSION['numberClient'] = $response['result'][0]['no'];             
     332                $_SESSION['numberClient'] = $response['result'][0]['no'];
    330333                //Save Invoice
    331334                $response = $this->utils_services->paramsSave($ch, $credentials, 'FtWS', $response);
     
    336339                    $this->logs->writeFileLog('addInternalDocumentInvoice3', $ch);
    337340                } else if(empty($response)){
    338                     $this->logs->writeFileLog('addInternalDocumentInvoice3', 'EMPTY RESPONSE');                               
     341                    $this->logs->writeFileLog('addInternalDocumentInvoice3', 'EMPTY RESPONSE');
    339342                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    340                     $this->logs->writeFileLog('addInternalDocumentInvoice3', $response['messages'][0]['messageCodeLocale']);                               
     343                    $this->logs->writeFileLog('addInternalDocumentInvoice3', $response['messages'][0]['messageCodeLocale']);
    341344                } else {
    342345                    //Enable to sign Document
     
    346349                            ###
    347350                            $ftstamp = $response['result'][0]['ftstamp'];
    348                            
     351
    349352                            $response = $this->utils_services->paramsSignDocument($ch, $credentials, $ftstamp);
    350353
    351354                            //$this->logs->writeFileLog('signing ft: ', $response);
    352                         } 
     355                        }
    353356
    354357                        if (curl_error($ch)) {
    355358                            $this->logs->writeFileLog('addInternalDocumentInvoice4', $ch);
    356359                        } else if(empty($response)){
    357                             $this->logs->writeFileLog('addInternalDocumentInvoice4', 'EMPTY RESPONSE');                   
     360                            $this->logs->writeFileLog('addInternalDocumentInvoice4', 'EMPTY RESPONSE');
    358361                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    359                             $this->logs->writeFileLog('addInternalDocumentInvoice4', $response['messages'][0]['messageCodeLocale']);                   
     362                            $this->logs->writeFileLog('addInternalDocumentInvoice4', $response['messages'][0]['messageCodeLocale']);
    360363                        } else {
    361                             $this->logs->writeFileLog('addInternalDocumentInvoice4', "Signed invoice: ".$response['result'][0]['fno'] );
     364                            $this->logs->writeFileLog('addInternalDocumentInvoice4', "Invoice number: ".$response['result'][0]['fno']." was created!" );
    362365
    363366                            return $response;
     
    365368                    } else {
    366369                        return $response;
    367                     }     
     370                    }
    368371                }
    369372            }
  • drivefx-woocommerce/trunk/PHCLibrary/log.php

    r2456866 r2526532  
    11<?php
    2 
    3 class Logs{
     2class Logs{
    43    //Write errors in Log File
    54    function writeFileLog($text_function, $messageResponse) {
    65        $myFile = __DIR__.'/../logsErrors/logs.txt';
    76        $date = date('Y/m/d H:i:s');
    8         $message = $text_function . " " . $date . ":  " . print_r($messageResponse, true) . "\r\n";     
     7        $message = $text_function . " " . $date . ":  " . print_r($messageResponse, true) . "\r\n";
    98            if (file_exists($myFile)) {
    109                $fh = fopen($myFile, 'a');
    1110            } else {
    1211                $fh = fopen($myFile, 'w');
    13             } 
     12            }
    1413            fwrite($fh, $message);
    1514            fclose($fh);
  • drivefx-woocommerce/trunk/PHCLibrary/orders.php

    r2456866 r2526532  
    55require_once 'customers.php';
    66
    7 
    87class OrdersService {
    9    
     8
    109    private $logs;
    1110    private $auth_services;
     
    1615        $this->logs = new Logs();
    1716        $this->auth_services = new AuthentificationService();
    18         $this->utils_services = new UtilsServices();       
    19         $this->customers_services = new CustomersServices();       
     17        $this->utils_services = new UtilsServices();
     18        $this->customers_services = new CustomersServices();
    2019    }
    21    
     20
    2221    public function processOrder($credentials, $dataPack, $fieldStatus){
    2322        # Login
    24         $ch = $this->auth_services->PHCLogin($ch, $credentials);       
     23        $ch = $this->auth_services->PHCLogin($ch, $credentials);
    2524        //initial request with login data
    2625        $response = curl_exec($ch);
    2726        // send response as JSON
    28         $response = json_decode($response, true); 
    29         // get the temporary token and insert in credentials object
     27        $response = json_decode($response, true);
     28        // get the token and insert in credentials object
    3029        $credentials->token = $response['result'][0]['token'];
    3130
    3231        //$this->logs->writeFileLog('OrderLogin response:', $response);
    33        
     32
    3433        $returnOrder = null;
    3534        ###
     
    3837        $order = $dataPack->order;
    3938        $shipping = $dataPack->shipping;
    40      
     39
    4140        if (curl_error($ch)) {
    4241            $this->logs->writeFileLog('addNewOrder', $ch);
     
    4645            $this->logs->writeFileLog('addNewOrder', $response['messages'][0]['messageCodeLocale']);
    4746        } else {
    48             # obtain gama 
     47            # obtain gama
    4948            $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
    50                
     49
    5150            //$this->logs->writeFileLog('BackEnd response:', $response);
    5251
     
    7069                }else{
    7170                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', "PT");
    72                 }   
     71                }
    7372                //$this->logs->writeFileLog('billCountry response:', $response);
    7473
     
    8382                    $nomePais = $response['result'][0]['nome'];
    8483                }
    85        
    86                 # obtain shipping country 
     84
     85                # obtain shipping country
    8786                if($shipping->paisto != ''){
    8887                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', $shipping->paisto);
     
    9190                }else{
    9291                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Countries', 'nomeabrv', "PT");
    93                 }   
     92                }
    9493                //$this->logs->writeFileLog('shippingCountry response:', $response);
    95        
     94
    9695                if (curl_error($ch)) {
    9796                    $this->logs->writeFileLog('addNewOrder3', $ch);
     
    106105
    107106                # Obtain currency coin of company
    108                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);               
    109                        
     107                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);
     108
    110109                //$this->logs->writeFileLog('E1 response:', $response);
    111110
     
    116115                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    117116                    $this->logs->writeFileLog('addNewOrder4', $response['messages'][0]['messageCodeLocale']);
    118                 } else {           
     117                } else {
    119118                    //Verify if currency of shop corresponds to PHC
    120119                    if($response['result'][0]['moeda'] == $dataPack->shop->currency){
    121120                        # get current customer data
    122                         $newCustomer = $this->customers_services->processCustomer($ch, $credentials, $dataPack, $tip_button);   
     121                        $newCustomer = $this->customers_services->processCustomer($ch, $credentials, $dataPack, $tip_button);
    123122
    124123                        //$this->logs->writeFileLog('newCustomer:', $newCustomer);
     
    127126                            $this->writeFileLog('getCustomer', $ch);
    128127                        } else if(empty($newCustomer)){
    129                             $this->writeFileLog('getCustomer', 'EMPTY RESPONSE');               
     128                            $this->writeFileLog('getCustomer', 'EMPTY RESPONSE');
    130129                        } else {
    131130                            if($newCustomer->no != ''){
    132131                                //Inserted client in bd
    133132                                $createClientSuccess = 1;
    134                             }                   
    135                         }
    136                        
    137                         #If client is created/obtained with success 
    138                         if($createClientSuccess == 1){   
    139                             //If in settings of backoffice is checked option "create invoice"                       
     133                            }
     134                        }
     135
     136                        #If client is created/obtained with success
     137                        if($createClientSuccess == 1){
     138                            //If in settings of backoffice is checked option "create invoice"
    140139                            if($settings->createInvoice){
    141140                                 //See if type of order is configured
    142141                                if(!empty($settings->typeOfOrder) && $settings->typeOfOrder != 0){
    143                                    
     142
    144143                                    //Obtain stamp of internal document based in order
    145144                                    $filterItem = 'bostamp';
    146                                     $valueItem = $order->doc_Id; 
    147                                    
     145                                    $valueItem = $order->doc_Id;
     146
    148147                                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem);
    149                                    
     148
    150149                                    //$this->logs->writeFileLog('Response', $response);
    151                            
     150
    152151                                    if (curl_error($ch)) {
    153152                                        $this->logs->writeFileLog('addNewOrder12', $ch);
    154153                                    } else if(empty($response)){
    155                                         $this->logs->writeFileLog('addNewOrder12', 'EMPTY RESPONSE');                   
     154                                        $this->logs->writeFileLog('addNewOrder12', 'EMPTY RESPONSE');
    156155                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    157                                         $this->logs->writeFileLog('addNewOrder12', $response['messages'][0]['messageCodeLocale']);                   
     156                                        $this->logs->writeFileLog('addNewOrder12', $response['messages'][0]['messageCodeLocale']);
    158157                                    } else {
    159158                                        //If internal document doesn't exists
     
    161160
    162161                                            # Create Internal Document
    163                                             $getNewInternalDoc = $this->createInternalDoc($ch, $credentials, $dataPack, $fieldStatus, $newCustomer, $paisesstampShipping, $nomePaisShipping);   
     162                                            $getNewInternalDoc = $this->createInternalDoc($ch, $credentials, $dataPack, $fieldStatus, $newCustomer, $paisesstamp, $nomePais, $paisesstampShipping, $nomePaisShipping);
    164163
    165164                                            if (curl_error($ch)) {
    166165                                                $this->logs->writeFileLog('createInternalDoc', $ch);
    167166                                            } else if(empty($getNewInternalDoc)){
    168                                                 $this->logs->writeFileLog('createInternalDoc', 'EMPTY RESPONSE');               
     167                                                $this->logs->writeFileLog('createInternalDoc', 'EMPTY RESPONSE');
    169168                                            } else {
    170169                                                $returnOrder = $getNewInternalDoc;
    171                                             }                                       
     170                                            }
    172171                                        //If internal document exists in system
    173172                                        } else if($response['result'][0]['isconfiguredtosign'] == false || ($response['result'][0]['isconfiguredtosign'] == true && $response['result'][0]['draftRecord'] == 1)){
     
    175174                                            $response['result'][0]['nome2'] = $bill->nome;
    176175                                            $response['result'][0]['email'] = $bill->email;
     176                                            $response['result'][0]['pais'] = $nomePais;
     177                                            $response['result'][0]['paisesstamp'] = $paisesstamp;
    177178                                            $response['result'][0]['morada'] = $bill->morada;
    178179                                            $response['result'][0]['local'] = $bill->local;
     
    182183                                            $response['result'][0]['ncont'] = $bill->ncont;
    183184
    184                                             $response['result'][0]['paisto'] = $nomePais;
    185                                             $response['result'][0]['paisesstampto'] = $paisesstamp;
    186                    
     185                                            $response['result'][0]['paisto'] = $nomePaisShipping;
     186                                            $response['result'][0]['paisesstampto'] = $paisesstampShipping;
     187
    187188                                            if($shipping->moradato != ''){
    188189                                                $response['result'][0]['moradato'] = $shipping->moradato;
     
    198199                                            if (is_array($order->cart)){
    199200                                                foreach ($order->cart as $key => $value){
    200                                                     if($response['result'][0]['bis'][$key]['qtt'] != $value){ 
    201                                                         #Discounts 
     201                                                    if($response['result'][0]['bis'][$key]['qtt'] != $value){
     202                                                        #Discounts
    202203                                                        if (isset($order->discount) && isset($order->discount_tax_excl)){
    203204                                                            //Introduce new line to add the cart discounts
    204205                                                            $discount = array();
    205                                                            
     206
    206207                                                            $discount['bistamp'] = '';
    207208                                                            $discount['ref'] = '';
     
    211212                                                            $discount['ettdeb'] = 0 - $order->discount;
    212213                                                            $discount['ivaincl'] = true;
    213                                                        
     214
    214215                                                            array_push($response['result'][0]['bis'], $discount);
    215216                                                        }
     
    218219                                                        $response = $this->utils_services->actEntity($ch, $credentials, 'BoWS', $response);
    219220
    220                                                         $this->logs->writeFileLog('actEntity3:', $response);
     221                                                        //$this->logs->writeFileLog('actEntity3:', $response);
    221222
    222223                                                        if (curl_error($ch)) {
     
    227228                                                            $this->logs->writeFileLog('addNewOrder11', $response['messages'][0]['messageCodeLocale']);
    228229                                                        }
    229                                                        
     230
    230231                                                        //Obtain status
    231                                                         $statusOrderShop = $this->utils_services->genericFieldsList($settings->statusOfOrder);                                               
    232                                                        
     232                                                        $statusOrderShop = $this->utils_services->genericFieldsList($settings->statusOfOrder);
     233
    233234                                                        if(!empty($statusOrderShop)){
    234235                                                            $response['result'][0][$statusOrderShop] = $fieldStatus;
     
    240241                                                        $response2 = $this->utils_services->filterItem_Query($ch, $credentials, 'Cl', 'no', $newCustomer->no);
    241242
    242                                                         $this->logs->writeFileLog('custom_by_no:', $response2);
     243                                                       // $this->logs->writeFileLog('custom_by_no:', $response2);
    243244
    244245                                                        if (curl_error($ch)) {
     
    255256                                                            #Save internal document
    256257                                                            $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
    257                                                            
     258
    258259                                                            //$this->logs->writeFileLog('save2:', $response);
    259260
     
    261262                                                                $this->logs->writeFileLog('addNewOrder19', $ch);
    262263                                                            } else if(empty($response)){
    263                                                                 $this->logs->writeFileLog('addNewOrder19', 'EMPTY RESPONSE');                         
     264                                                                $this->logs->writeFileLog('addNewOrder19', 'EMPTY RESPONSE');
    264265                                                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    265                                                                 $this->logs->writeFileLog('addNewOrder19', $response['messages'][0]['messageCodeLocale']);                         
     266                                                                $this->logs->writeFileLog('addNewOrder19', $response['messages'][0]['messageCodeLocale']);
    266267                                                            } else {
    267268                                                                $response = $response['result'][0];
     
    270271                                                                return $response;
    271272                                                            }
    272                                                         }                                 
     273                                                        }
    273274                                                    }
    274275                                                }
    275                                             }             
     276                                            }
    276277                                        }
    277278                                    }
    278                                 }                               
     279                                }
    279280                            }
    280281                        } else if(($createClientSuccess == '' || $createClientSuccess == 0) && ($tip_button == true || $tip_button == 1)){
    281                            
     282
    282283                            $_REQUEST['order_id'] = $order->order_Id;
    283284                            //Verify if exists in bd
     
    287288
    288289                            $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', 'obrano', $_REQUEST['order_id']);
    289                                    
     290
    290291                            //$this->logs->writeFileLog('Response', $response);
    291292
     
    293294                                $this->logs->writeFileLog('addNewOrder20', $ch);
    294295                            } else if(empty($response)){
    295                                 $this->logs->writeFileLog('addNewOrder20', 'EMPTY RESPONSE');               
     296                                $this->logs->writeFileLog('addNewOrder20', 'EMPTY RESPONSE');
    296297                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    297                                 $this->logs->writeFileLog('addNewOrder20', $response['messages'][0]['messageCodeLocale']);               
     298                                $this->logs->writeFileLog('addNewOrder20', $response['messages'][0]['messageCodeLocale']);
    298299                            } else {
    299300                                $hasBoOrder = false;
     
    307308
    308309                                if($hasBoOrder && $response['result'][$hasBoOrderKey]['isconfiguredtosign'] == false|| ($response['result'][$hasBoOrderKey]['isconfiguredtosign'] == true &&
    309                                    $response['result'][$hasBoOrderKey]['draftRecord'] == 1)){                           
     310                                   $response['result'][$hasBoOrderKey]['draftRecord'] == 1)){
    310311                                    //Obtain status
    311312                                    $statusOrderShop = $this->utils_services->genericFieldsList($settings->statusOfOrder);
    312                                    
     313
    313314                                    //write in VO the status
    314315                                    if(!empty($statusOrderShop)){
     
    316317                                    }
    317318                                    $response['result'][$hasBoOrderKey]['Operation'] = 2;
    318        
     319
    319320                                    #Save internal document
    320321                                    $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
    321                                    
     322
    322323                                    //$this->logs->writeFileLog('save3:', $response);
    323        
     324
    324325                                    if (curl_error($ch)) {
    325326                                        $this->logs->writeFileLog('addNewOrder21', $ch);
    326327                                    } else if(empty($response)){
    327                                         $this->logs->writeFileLog('addNewOrder21', 'EMPTY RESPONSE');                 
     328                                        $this->logs->writeFileLog('addNewOrder21', 'EMPTY RESPONSE');
    328329                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    329                                         $this->logs->writeFileLog('addNewOrder21', $response['messages'][0]['messageCodeLocale']);                 
    330                                     } 
     330                                        $this->logs->writeFileLog('addNewOrder21', $response['messages'][0]['messageCodeLocale']);
     331                                    }
    331332                                }
    332333                            }
     
    334335                    } else {
    335336                        //Show message with error
    336                         $this->logs->writeFileLog('coin', 'Please configure currency in shop according to PHC application');   
     337                        $this->logs->writeFileLog('coin', 'Please configure currency in shop according to PHC application');
    337338                        unset($_SESSION['username']);
    338339
     
    344345
    345346            return $returnOrder;
    346         }                                         
     347        }
    347348    }
    348349
    349     public function createInternalDoc($ch, $credentials, $dataPack, $fieldStatus, $newCustomer, $paisesstampShipping, $nomePaisShipping){
     350    public function createInternalDoc($ch, $credentials, $dataPack, $fieldStatus, $newCustomer, $paisesstamp, $nomePais, $paisesstampShipping, $nomePaisShipping){
    350351
    351352        ###
     
    355356        $shipping = $dataPack->shipping;
    356357
    357        
     358
    358359        //Obtain new instance of Bo
    359360        $response = $this->utils_services->paramsNewInstance($ch, $credentials, 'BoWS', $settings->typeOfOrder);
    360                                    
     361
     362        //Clear the product lines
     363        $response['result'][0]['bis'] = [];
     364
    361365        //$this->logs->writeFileLog('BoWs Response', $response);
    362366
     
    364368            $this->logs->writeFileLog('addNewOrder13', $ch);
    365369        } else if(empty($response)){
    366             $this->logs->writeFileLog('addNewOrder13', 'EMPTY RESPONSE');                       
     370            $this->logs->writeFileLog('addNewOrder13', 'EMPTY RESPONSE');
    367371        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    368             $this->logs->writeFileLog('addNewOrder13', $response['messages'][0]['messageCodeLocale']);                       
     372            $this->logs->writeFileLog('addNewOrder13', $response['messages'][0]['messageCodeLocale']);
    369373        } else {
    370            
     374
    371375            //Obtain number of customer
    372376            $response['result'][0]['no'] = $newCustomer->no;
    373377            #actEntity
    374378            $response = $this->utils_services->actEntity($ch, $credentials, 'BoWS', $response);
    375            
    376             //$this->logs->writeFileLog('actEntity:', $response);
    377            
     379
     380            //$this->logs->writeFileLog('actEntity:', $response['result'][0]);
     381
    378382            if (curl_error($ch)) {
    379383                $this->logs->writeFileLog('addNewOrder13.1', $ch);
    380384            } else if(empty($response)){
    381                 $this->logs->writeFileLog('addNewOrder13.1', 'EMPTY RESPONSE');                         
     385                $this->logs->writeFileLog('addNewOrder13.1', 'EMPTY RESPONSE');
    382386            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    383                 $this->logs->writeFileLog('addNewOrder13.1', $response['messages'][0]['messageCodeLocale']);                         
    384             } else {   
    385                
     387                $this->logs->writeFileLog('addNewOrder13.1', $response['messages'][0]['messageCodeLocale']);
     388            } else {
     389
    386390                #Put the same number of order in PHC
    387391                if($response['result'][0]['isconfiguredtosign'] == true){
     
    393397                }
    394398                else {
    395                    
     399
    396400                    $response['result'][0]['obrano'] = $order->nextPostId;
    397401                }
     
    399403                #Get taxes from Phc
    400404                $responseTaxes = $this->utils_services->getTaxes($ch, $credentials);
    401                
     405
    402406                //$this->logs->writeFileLog('Get Taxes:', $responseTaxes);
    403                
     407
    404408                if (curl_error($ch)) {
    405409                    $this->logs->writeFileLog('addNewOrder13.1.1', $ch);
    406410                } else if(empty($responseTaxes)){
    407                     $this->logs->writeFileLog('addNewOrder13.1.1', 'EMPTY RESPONSE');                         
     411                    $this->logs->writeFileLog('addNewOrder13.1.1', 'EMPTY RESPONSE');
    408412                } else if(isset($responseTaxes['messages'][0]['messageCodeLocale'])){
    409                     $this->logs->writeFileLog('addNewOrder13.1.1', $responseTaxes['messages'][0]['messageCodeLocale']);                         
    410                 }
    411                
     413                    $this->logs->writeFileLog('addNewOrder13.1.1', $responseTaxes['messages'][0]['messageCodeLocale']);
     414                }
     415
    412416                #Obtain name and price of delivery
    413417                //Obtain VO with updated Bo
    414418                foreach ($order->cart as $product) {
    415419                    //product
    416                     if($product['qtt']*$product['epv'] != 0){                       
    417                         $bi = new stdClass(); 
     420                    if($product['qtt']*$product['epv'] != 0){
     421                        $bi = new stdClass();
    418422
    419423                        $bi->ref =  $product['ref'];
     
    423427                    }
    424428                }
    425                
     429
    426430                #shipping
    427431                if (isset($shipping->shipping_name)){
     
    430434                    if($settings->shippingName != "") {
    431435                        $bi->ref = $settings->shippingName;
    432                     }   
     436                    }
    433437
    434438                    $bi->design = $shipping->shipping_name;
    435                     $bi->qtt = 1; 
     439                    $bi->qtt = 1;
    436440                    $bi->edebito = $bi->ettdeb = $shipping->shipping_value;
    437                                    
     441
    438442                    if($settings->includeTaxonSendCost == "true") {
    439443                        $bi->ivaincl=true;
    440                     }                                                                               
     444                    }
    441445                    //IVA for shipping
    442446                    foreach ($responseTaxes['result'] as $tax) {
    443447                        if ($shipping->shipping_tax == $tax['taxa'] &&
    444448                            $shipping->shipping_country == $tax['regiao']) {
    445                             //get IVA   
     449                            //get IVA
    446450                            $bi->iva = $tax['taxa'];
    447451                            $bi->tabiva = $tax['codigo'];
    448                         break;                                                                 
    449                         }                                                                                       
    450                     } 
     452                        break;
     453                        }
     454                    }
    451455                    if($bi->edebito == 0){
    452456                        $bi->qtt = 0;
    453457                        $bi->ivaincl = false;
    454                     }   
    455                     $response['result'][0]['bis'][]= $bi;   
     458                    }
     459                    $response['result'][0]['bis'][]= $bi;
    456460                }
    457461                //actEntity
     
    459463
    460464                //$this->logs->writeFileLog('actEntity.0.1:', $response2);
    461                
     465
    462466                // Update shipping value
    463467                foreach ($response2['result'][0]['bis'] as &$delivery) {
    464468
    465                     if ($delivery['design'] == $shipping->shipping_name) {
     469                    if ($delivery['ref'] == $settings->shippingName) {
    466470                        //replace the price for shipping
    467471                        $delivery['edebito'] = $shipping->shipping_value;
    468472                        $delivery['ettdeb'] = $shipping->shipping_value;
    469                     }               
    470                 }
    471                
     473                    }
     474                }
     475
    472476                //actEntity
    473477                $response = $this->utils_services->actEntity($ch, $credentials, 'BoWS', $response2);
    474            
    475                //$this->logs->writeFileLog('actEntity1:', $response);
     478
     479              // $this->logs->writeFileLog('actEntity1:', $response);
    476480
    477481                if (curl_error($ch)) {
    478482                    $this->logs->writeFileLog('addNewOrder14', $ch);
    479483                } else if(empty($response)){
    480                     $this->logs->writeFileLog('addNewOrder14', 'EMPTY RESPONSE');                         
     484                    $this->logs->writeFileLog('addNewOrder14', 'EMPTY RESPONSE');
    481485                } else if(isset($response['messages'][0]['messageCodeLocale'])  && $response['messages'][0]['messageCode']!='messages.Business.Stocks.InvalidRefAutoCreate'){
    482                     $this->logs->writeFileLog('addNewOrder14', $response['messages'][0]['messageCodeLocale']);                         
     486                    $this->logs->writeFileLog('addNewOrder14', $response['messages'][0]['messageCodeLocale']);
    483487                } else {
    484488
     
    489493                             //Update list of Quantity
    490494                            if( $value['qtt']*$value['epv']!=0 && $response['result'][0]['bis'][$key]['qtt'] != $value['qtt']){
    491                                 //get quantity   
     495                                //get quantity
    492496                                $response['result'][0]['bis'][$key]['qtt'] = $value['qtt'];
    493497                            }
    494498                            //Update list of Value Item (added condition "componente != 1" to skip articles that are part of a composite product.)
    495499                            if( $value['qtt']*$value['epv']!=0 && $response['result'][0]['bis'][$key]['ettdeb'] != $value['epv'] && $response['result'][0]['bis'][$key]['componente'] != 1){
    496                                 //get quantity   
     500                                //get quantity
    497501                                $response['result'][0]['bis'][$key]['ettdeb'] = $value['epv'];
    498502                            }
    499503                        }
    500504                    }
    501            
     505
    502506                    #Eliminate comercial discount
    503507                    if (is_array($order->cart)){
     
    530534                            $response['result'][0][$statusOrderShop] = $fieldStatus;
    531535                        }
    532                        
     536
    533537                        //Find the type of shipment
    534538                        $response['result'][0]['trab1']= $order->post_title;
     
    553557
    554558                        //billing data
     559                        $response['result'][0]['pais'] = $nomePais;
     560                        $response['result'][0]['paisesstamp'] = $paisesstamp;
    555561                        $response['result'][0]['morada'] = $bill->morada;
    556562                        $response['result'][0]['local'] = $bill->local;
     
    559565                        $response['result'][0]['codpost'] = $bill->codpost;
    560566                        $response['result'][0]['ncont'] = $bill->ncont;
    561                        
     567
    562568                        #Obtain taxes
    563569                        if (is_array($order->cart)){
    564                             //get tax rate & tax rate country 
     570                            //get tax rate & tax rate country
    565571                            foreach ($order->cart as $key => $value){
    566572                                if( $value['qtt']*$value['epv']!=0){
     
    569575                                    $refProd = $value['ref'];
    570576                                    //obtain tax from Phc
    571                                     foreach ($responseTaxes['result'] as $tax) {                                                             
     577                                    foreach ($responseTaxes['result'] as $tax) {
    572578                                        if($taxRate == $tax['taxa'] && $taxCountry == $tax['regiao'] && $refProd == $response['result'][0]['ref']) {
    573579                                           $response['result'][0]['bis'][$key]['iva'] = $tax['taxa'];
     
    575581                                           if($settings->includeTaxonSendCost == "true") {
    576582                                               $response['result'][0]['bis'][$key]['ivaincl'] = true;
    577                                             }                                                                                                   
     583                                            }
    578584                                           break;
    579585                                        }
    580                                     }                             
    581                                 }
    582                             }
    583                         } 
    584                        //$this->logs->writeFileLog('Obtain taxes:', $response['result'][0]);                         
     586                                    }
     587                                }
     588                            }
     589                        }
     590                       //$this->logs->writeFileLog('Obtain taxes:', $response['result'][0]);
    585591                        ###
    586592                        $fees = $order->fees;
     
    597603                                if($settings->feesName != "") {
    598604                                    $bi->ref = $settings->feesName;
    599                                 }   
    600 
    601                                 //IVA 
     605                                }
     606
     607                                //IVA
    602608                                foreach ($responseTaxes['result'] as $tax) {
    603609                                    if ($taxRate == $tax['taxa'] && $taxCountry == $tax['regiao']) {
     
    605611                                        $bi->tabiva = $tax['codigo'];
    606612
    607                                         break;                                                                 
    608                                     }                                                                                       
    609                                 } 
    610                                 $response['result'][0]['bis'][]= $bi;                       
    611                             }                             
    612                         }                     
     613                                        break;
     614                                    }
     615                                }
     616                                $response['result'][0]['bis'][]= $bi;
     617                            }
     618                        }
    613619                        # Discounts
    614620                        if (isset($order->discount) && $order->discount > 0){
    615621                            //Introduce new line to add the cart discounts
    616622                            $discount = array();
    617                            
     623
    618624                            $discount['bistamp'] = '';
    619625                            if($settings->discountRef != "") {
     
    621627                            } else {
    622628                                $discount['ref'] = '';
    623                             }   
     629                            }
    624630                            $discount['design'] = "Desconto";
    625631                            $discount['qtt'] = 1;
     
    627633                            $discount['ettdeb'] = 0 - $order->discount;
    628634                            $discount['ivaincl'] = true;
    629                        
     635
    630636                            array_push($response['result'][0]['bis'], $discount);
    631                         } 
     637                        }
    632638                        //actEntity
    633639                        $response = $this->utils_services->actEntity($ch, $credentials, 'BoWS', $response);
     
    638644                            $this->logs->writeFileLog('addNewOrder14.1', $ch);
    639645                        } else if(empty($response)){
    640                             $this->logs->writeFileLog('addNewOrder14.1', 'EMPTY RESPONSE');                         
     646                            $this->logs->writeFileLog('addNewOrder14.1', 'EMPTY RESPONSE');
    641647                        } else if(isset($response['messages'][0]['messageCodeLocale'])  && $response['messages'][0]['messageCode']!='messages.Business.Stocks.InvalidRefAutoCreate'){
    642                             $this->logs->writeFileLog('addNewOrder14.1', $response['messages'][0]['messageCodeLocale']);                         
     648                            $this->logs->writeFileLog('addNewOrder14.1', $response['messages'][0]['messageCodeLocale']);
    643649                        } else {
    644650                            // Update discount  value
    645651                            foreach ($response['result'][0]['bis'] as &$dDiscount) {
    646    
     652
    647653                                if ($dDiscount['design'] == "Desconto") {
    648654                                    //replace the price for shipping
    649655                                    $dDiscount['edebito'] = 0 - $order->discount;
    650656                                    $dDiscount['ettdeb'] = 0 - $order->discount;
    651                                 }               
     657                                }
    652658                            }
    653659                            //Insert
     
    657663                            if($response['result'][0]['isconfiguredtosign'] == true){
    658664
    659                                 $numberOfOrder = $this->utils_services->genericFieldsList($settings->numberOfOrder);                           
     665                                $numberOfOrder = $this->utils_services->genericFieldsList($settings->numberOfOrder);
    660666
    661667                                if(!empty($numberOfOrder)){
     
    664670                            }
    665671                            else {
    666                                
     672
    667673                                $response['result'][0]['obrano'] = $order->nextPostId;
    668674                            }
     
    670676                            #Save internal document
    671677                            $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
    672                            
     678
    673679                            //$this->logs->writeFileLog('save1:', $response);
    674680
     
    676682                                $this->logs->writeFileLog('addNewOrder15', $ch);
    677683                            } else if(empty($response)){
    678                                 $this->logs->writeFileLog('addNewOrder15', 'EMPTY RESPONSE');                             
     684                                $this->logs->writeFileLog('addNewOrder15', 'EMPTY RESPONSE');
    679685                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    680686                                $this->logs->writeFileLog('addNewOrder15', $response['messages'][0]['messageCodeLocale']);
     
    683689                                $response['result'][0]['paisesstampto'] = $paisesstampShipping;
    684690
    685                                 //fulfill the second name field with customer name corresponding to the invoice                                                                 
     691                                //fulfill the second name field with customer name corresponding to the invoice
    686692                                $response['result'][0]['nome2'] = $bill->nome;;
    687693
     
    690696                                } else if ($shipping_address_1_ != ''){
    691697                                    $response['result'][0]['moradato'] = $shipping_address_1_;
    692                                 }     
     698                                }
    693699
    694700                                if($shipping->moradato != ''){
     
    706712                                #Save internal document
    707713                                $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
    708                            
     714
    709715                                // $this->logs->writeFileLog('save2:', $response);
    710716
     
    712718                                    $this->logs->writeFileLog('addNewOrder16', $ch);
    713719                                } else if(empty($response)){
    714                                     $this->logs->writeFileLog('addNewOrder16', 'EMPTY RESPONSE');                               
     720                                    $this->logs->writeFileLog('addNewOrder16', 'EMPTY RESPONSE');
    715721                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    716                                     $this->logs->writeFileLog('addNewOrder16', $response['messages'][0]['messageCodeLocale']);                               
     722                                    $this->logs->writeFileLog('addNewOrder16', $response['messages'][0]['messageCodeLocale']);
    717723                                } else {
    718                                     $response = $response['result'][0]; 
     724                                    $response = $response['result'][0];
    719725
    720726                                    if($response['isconfiguredtosign'] == true && $response['draftRecord'] == 1 && $settings->toSignOrder){
     
    727733                                            $this->logs->writeFileLog('addNewOrder17', $ch);
    728734                                        } else if(empty($response)){
    729                                             $this->logs->writeFileLog('addNewOrder17', 'EMPTY RESPONSE');                               
     735                                            $this->logs->writeFileLog('addNewOrder17', 'EMPTY RESPONSE');
    730736                                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    731                                             $this->logs->writeFileLog('addNewOrder17', $response['messages'][0]['messageCodeLocale']);                               
     737                                            $this->logs->writeFileLog('addNewOrder17', $response['messages'][0]['messageCodeLocale']);
    732738                                        } else {
    733739                                            $response = $response['result'][0];
    734                                             $this->logs->writeFileLog('addNewOrder17', "Signed order: " . $response['obrano'] );
    735                                              
     740                                            $this->logs->writeFileLog('addNewOrder17.1', "Signed order: " . $response['obrano'] );
     741
    736742                                        }
    737743                                        //return data of Bo to save FT
    738                                         return $response; 
     744                                        return $response;
    739745                                    }
    740746                                }
     
    745751            }
    746752        }
     753        $this->logs->writeFileLog('addNewOrder17.2', "Order number: ".$response['obrano']." was created!" );
     754
    747755        return $response;
    748756    }
  • drivefx-woocommerce/trunk/PHCLibrary/utils.php

    r2456866 r2526532  
    11<?php
     2DEFINE ( 'VIES_URL', 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService');
    23
    34class UtilsServices {
     
    1718    ********************************************************************/
    1819    /** Curls builder **/
    19     public function doPhcRequest($ch, $url, $params, $credentials) {   
     20    public function doPhcRequest($ch, $url, $params, $credentials) {
    2021
    2122        $tokenHeader = array( 'Authorization' => 'Engine-Auth:'.$credentials->token, 'Content-Type' => 'application/json' );
     
    2627        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    2728        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    28        
     29
    2930        $response = curl_exec($ch);
    3031
    31         $response = json_decode($response, true); 
     32        $response = json_decode($response, true);
    3233        return $response;
    3334
     
    3839    ********************************************************************/
    3940    /** Header to create Query of webservice called **/
    40     public function paramsGetBackEndInfo($ch, $credentials){     
    41         $this->url = $credentials->backendUrl."/REST/UserLoginWS/getBackEndInfo"; 
    42         //Create map with request parameters
    43         $this->params =  array ('loginInfoVO' => '{"userCode": "'.$credentials->userCode.'", 
    44                                                 "password": "'.$credentials->password.'", 
    45                                                 "company":  "'.$credentials->company.'", 
    46                                                 "language": "", 
    47                                                 "hash": "" 
     41    public function paramsGetBackEndInfo($ch, $credentials){
     42        $this->url = $credentials->backendUrl."/REST/UserLoginWS/getBackEndInfo";
     43        //Create map with request parameters
     44        $this->params =  array ('loginInfoVO' => '{"userCode": "'.$credentials->userCode.'",
     45                                                "password": "'.$credentials->password.'",
     46                                                "company":  "'.$credentials->company.'",
     47                                                "language": "",
     48                                                "hash": ""
    4849                                                }'
    49                         );   
    50         //Build Http query using params
    51         $this->query = http_build_query ($this->params);
    52 
    53         //Called webservice that make a request
    54         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    55 
    56         return $response; 
    57     }
    58    
     50                        );
     51        //Build Http query using params
     52        $this->query = http_build_query ($this->params);
     53
     54        //Called webservice that make a request
     55        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     56
     57        return $response;
     58    }
     59
    5960    /*******************************************************************
    6061    *                  ---  Get Frontend Info ---                      *
    6162    ********************************************************************/
    6263    /** Header to save information of webservice called **/
    63     public function paramsGetFrontendInfo($ch, $credentials){   
     64    public function paramsGetFrontendInfo($ch, $credentials){
    6465        $this->url = $credentials->backendUrl."/REST/ParameterWS/getFrontEndParameters";
    6566        //Create map with request parameters
    66         $this->$params =  array ('loginInfoVO' => '{"userCode": "'.$credentials->userCode.'", 
    67                                                     "password": "'.$credentials->password.'", 
    68                                                     "company":  "'.$credentials->company.'", 
    69                                                     "language": "", 
    70                                                     "hash": "" 
     67        $this->$params =  array ('loginInfoVO' => '{"userCode": "'.$credentials->userCode.'",
     68                                                    "password": "'.$credentials->password.'",
     69                                                    "company":  "'.$credentials->company.'",
     70                                                    "language": "",
     71                                                    "hash": ""
    7172                                                    }'
    72                             );         
     73                            );
    7374        //Build Http query using params
    7475        $this->$query = http_build_query ($this->$params);
     
    7778        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    7879
    79         return $response; 
    80                            
     80        return $response;
     81
    8182    }
    8283
     
    106107                                );
    107108        //Build Http query using params
    108         $this->query = http_build_query ($this->params); 
    109        
    110         //Called webservice that make a request
    111         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    112 
    113         return $response; 
     109        $this->query = http_build_query ($this->params);
     110
     111        //Called webservice that make a request
     112        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     113
     114        return $response;
    114115    }
    115116
     
    118119    ********************************************************************/
    119120    /** Query with a comparison filter **/
    120    
     121
    121122    public function filterItem_compare($ch, $credentials, $entityName, $comparison, $filterItem = null, $valueItem = null){
    122123        $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
     
    138139                                                                }]}'
    139140                                );
    140                                    
    141         //Build Http query using params
    142         $this->query = http_build_query ($this->params); 
    143        
    144         //Called webservice that make a request
    145         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    146 
    147         return $response; 
     141
     142        //Build Http query using params
     143        $this->query = http_build_query ($this->params);
     144
     145        //Called webservice that make a request
     146        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     147
     148        return $response;
    148149    }
    149150
     
    152153    ********************************************************************/
    153154    /** Query with a comparison filter **/
    154    
     155
    155156    public function doubleFilter($ch, $credentials, $entityName, $filterItem = null, $valueItem = null,$filterItem2 = null, $valueItem2 = null){
    156157        $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
     
    182183                                );
    183184        //Build Http query using params
    184         $this->query = http_build_query ($this->params); 
    185        
    186         //Called webservice that make a request
    187         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    188 
    189         return $response; 
     185        $this->query = http_build_query ($this->params);
     186
     187        //Called webservice that make a request
     188        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     189
     190        return $response;
    190191    }
    191192
     
    208209                                );
    209210        //Build Http query using params
    210         $this->query = http_build_query ($this->params); 
    211 
    212         //Called webservice that make a request
    213         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    214 
    215         return $response; 
     211        $this->query = http_build_query ($this->params);
     212
     213        //Called webservice that make a request
     214        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     215
     216        return $response;
    216217    }
    217218
     
    243244        //Build Http query using params
    244245        $this->query = http_build_query ($this->params);
    245        
    246         //Called webservice that make a request
    247         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    248 
    249         return $response; 
     246
     247        //Called webservice that make a request
     248        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     249
     250        return $response;
    250251    }
    251252
     
    268269        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    269270
    270         return $response; 
     271        return $response;
    271272    }
    272273
     
    293294        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    294295
    295         return $response; 
     296        return $response;
    296297    }
    297298
     
    300301    ********************************************************************/
    301302    //Header to create Query of webservice called
    302     public function paramsQuery4($ch, $entityName, $selectItems, $valueItem){
    303         //get credentials
    304         $credentials =  $this->configs->fetchCredentials();
    305         $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
    306     // Create map with request parameters
    307     $this->params =  array ('itemQuery' => '{"groupByItems":[],
    308                                             "lazyLoaded":false,
    309                                             "joinEntities":[],
    310                                             "orderByItems":[],
    311                                             "SelectItems":["'.$selectItems.'"],
    312                                             "entityName":"'.$entityName.'",
    313                                             "filterItems":[{
    314                                                             "comparison":0,
    315                                                             "filterItem":"ndos",
    316                                                             "valueItem":'.$valueItem.',
    317                                                             "groupItem":1,
    318                                                             "checkNull":false,
    319                                                             "skipCheckType":false,
    320                                                             "type":"Number"
    321                                                             }]}'
    322                             );
    323 
    324     // Build Http query using params
    325         $this->query = http_build_query ($this->params);
    326 
    327         //Called webservice that make a request
    328         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    329 
    330         return $response;
     303    public function paramsQuery4($ch, $credentials, $entityName, $selectItems, $valueItem){
     304        $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
     305        // Create map with request parameters
     306        $this->params =  array ('itemQuery' => '{"groupByItems":[],
     307                                                "lazyLoaded":false,
     308                                                "joinEntities":[],
     309                                                "orderByItems":[],
     310                                                "SelectItems":["'.$selectItems.'"],
     311                                                "entityName":"'.$entityName.'",
     312                                                "filterItems":[{
     313                                                                "comparison":0,
     314                                                                "filterItem":"ndos",
     315                                                                "valueItem":'.$valueItem.',
     316                                                                "groupItem":1,
     317                                                                "checkNull":false,
     318                                                                "skipCheckType":false,
     319                                                                "type":"Number"
     320                                                                }]}'
     321                                );
     322
     323        // Build Http query using params
     324        $this->query = http_build_query ($this->params);
     325
     326        //Called webservice that make a request
     327        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     328
     329        return $response;
    331330    }
    332331
     
    363362                                                                }]}'
    364363                                );
    365                                                                          
    366         // Build Http query using params
    367         $this->query = http_build_query ($this->params);
    368 
    369         //Called webservice that make a request
    370         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    371 
    372         return $response; 
     364
     365        // Build Http query using params
     366        $this->query = http_build_query ($this->params);
     367
     368        //Called webservice that make a request
     369        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     370
     371        return $response;
    373372    }
    374373
     
    382381        // Create map with request parameters
    383382        $this->params =  array ('ndos' => $ndos);
    384        
    385         // Build Http query using params
    386         $this->query = http_build_query ($this->params);
    387 
    388         //Called webservice that make a request
    389         $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    390 
    391         return $response; 
     383
     384        // Build Http query using params
     385        $this->query = http_build_query ($this->params);
     386
     387        //Called webservice that make a request
     388        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     389
     390        return $response;
    392391    }
    393392
     
    401400        // Create map with request parameters
    402401        $this->params =  array ('entity' => json_encode($response['result'][0]),
    403                                 'code' => 0, 
     402                                'code' => 0,
    404403                                'newValue' => "{}");
    405404
     
    410409        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    411410
    412         return $response; 
     411        return $response;
    413412    }
    414413
     
    440439        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    441440
    442         return $response; 
     441        return $response;
    443442    }
    444443
     
    467466        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
    468467
    469         return $response; 
    470     }
    471        
     468        return $response;
     469    }
     470
    472471    /*******************************************************************
    473472    *                           --- SAVE ---                           *
     
    478477        // Create map with request parameters
    479478        $this->params =  array ('itemVO' => json_encode($response['result'][0]),
    480                             'runWarningRules' => 'false'); 
     479                            'runWarningRules' => 'false');
    481480        // Build Http query using params
    482481        $this->query = http_build_query ($this->params);
     
    550549                                        "stamp":"'.$ftstamp.'"}],
    551550                                        "reportStamp":"'.$repstamp.'",
    552                                         "sendToType":0,"serie":0}');                                       
    553                            
    554                            
    555                            
    556         // Build Http query using params
    557         $this->query = http_build_query ($this->params);
    558        
     551                                        "sendToType":0,"serie":0}');
     552
     553
     554
     555        // Build Http query using params
     556        $this->query = http_build_query ($this->params);
     557
    559558        //Called webservice that make a request
    560559        $response=$this->doPhcRequest($ch, $this->url, $this->params, $credentials);
     
    570569
    571570        $tokenHeader = array( 'Authorization' => 'Engine-Auth:'.$credentials->token, 'Content-Type' => 'application/json' );
    572        
     571
    573572        $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
    574573        // Create map with request parameters
     
    589588        // Build Http query using params
    590589        $this->query = http_build_query ($this->params);
    591    
     590
    592591        //Called webservice that make a request
    593592        curl_setopt($ch, CURLOPT_URL, $this->url);
     
    598597        curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
    599598        $response = curl_exec($ch);
    600    
     599
    601600        $response = json_decode($response, true);
    602    
     601
    603602        return $response;
    604603    }
     
    648647
    649648        $tokenHeader = array( 'Authorization' => 'Engine-Auth:'.$credentials->token, 'Content-Type' => 'application/json' );
    650        
     649
    651650        $this->url = $credentials->backendUrl."/REST/SearchWS/QueryAsEntities";
    652651        // Create map with request parameters
     
    661660                                                    "groupItem": 0
    662661                                                }],
    663                                                 "limit": 1, 
     662                                                "limit": 1,
    664663                                                "offset": 0,
    665664                                                "orderByItems": [
     
    674673        // Build Http query using params
    675674        $this->query = http_build_query ($this->params);
    676    
     675
    677676        //Called webservice that make a request
    678677        curl_setopt($ch, CURLOPT_URL, $this->url);
     
    683682        curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
    684683        $response = curl_exec($ch);
    685    
     684
    686685        $response = json_decode($response, true);
    687    
     686
     687        return $response;
     688    }
     689
     690    /*******************************************************************
     691    *             ---  Get Recent Internal Document ---                *
     692    ********************************************************************/
     693    function viesCheckVAT($countryCode, $vatNumber, $timeout = 30) {
     694        $response = array ();
     695        $pattern = '/<(%s).*?>([\s\S]*)<\/\1/';
     696        $keys = array (
     697                'countryCode',
     698                'vatNumber',
     699                'requestDate',
     700                'valid',
     701                'name',
     702                'address'
     703        );
     704
     705        $content = "<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
     706            <s11:Body>
     707            <tns1:checkVat xmlns:tns1='urn:ec.europa.eu:taxud:vies:services:checkVat:types'>
     708            <tns1:countryCode>%s</tns1:countryCode>
     709            <tns1:vatNumber>%s</tns1:vatNumber>
     710            </tns1:checkVat>
     711            </s11:Body>
     712            </s11:Envelope>";
     713
     714        $opts = array (
     715                'http' => array (
     716                        'method' => 'POST',
     717                        'header' => "Content-Type: text/xml; charset=utf-8; SOAPAction: checkVatService",
     718                        'content' => sprintf ( $content, $countryCode, $vatNumber ),
     719                        'timeout' => $timeout
     720                )
     721        );
     722
     723        $ctx = stream_context_create ( $opts );
     724        $result = file_get_contents ( VIES_URL, false, $ctx );
     725
     726        if (preg_match ( sprintf ( $pattern, 'checkVatResponse' ), $result, $matches )) {
     727            foreach ( $keys as $key )
     728                preg_match ( sprintf ( $pattern, $key ), $matches [2], $value ) && $response [$key] = $value [2];
     729        }
    688730        return $response;
    689731    }
  • drivefx-woocommerce/trunk/class.DriveFxWoocommerce.php

    r2456862 r2526532  
    2727            'backend' => array(
    2828                'username'          => array('label' => 'Username',                                   'type' => 'text',          'required' => true,  'descr' => 'This username allows the backend to accept data sent from this plugin.', 'notice' => 'This can not be empty! Please enter your username...'),
    29                 'password'          => array('label' => 'Password',                                   'type' => 'password',      'required' => true,  'descr' => 'This password allows the backend to accept data sent from this plugin.', 'notice' => 'This can not be empty! Please enter your password...'),     
     29                'password'          => array('label' => 'Password',                                   'type' => 'password',      'required' => true,  'descr' => 'This password allows the backend to accept data sent from this plugin.', 'notice' => 'This can not be empty! Please enter your password...'),
    3030                'url'               => array('label' => 'Backend URL',                                'type' => 'url',           'required' => true,  'descr' => 'The URL of your PHC GO application.<br>Something like, e.g. https://sisXX.phcgo.net/XPTO/html', 'notice' => 'No backend URL! Please define your backend URL...'),
    3131                'dbname'            => array('label' => 'Database Name',                              'type' => 'text',          'required' => false, 'descr' => 'Enter the name of the PHC GO where you want save your information.<br>You can leave this empty if you only work with one company.', 'notice' => ''),
     
    3737                'fieldNif'          => array('label' => 'NIF Field in Woocommerce',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the nif field of woocommerce', 'notice' => ''),
    3838                'includeTaxonSendCost'          => array('label' => 'Tax included in products Cost?', 'type' => 'select',        'required' => false, 'checkboxDescription' => 'Does the products cost has tax already included in price?', 'notice' => ''),
    39                 'createExemptCl'    => array('label' => 'Create tax-exempt customers?',               'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Create tax-free customers (for foreigners)', 'notice' => ''),
     39                'createExemptPT'    => array('label' => 'From outside PT',                            'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Save customers from outside Portugal as tax-exempt', 'notice' => ''),
    4040                'typeOfReason'      => array('label' => 'Select tax exempt reason',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the reason for the tax exemption', 'notice' => ''),
     41                'createExemptEU'    => array('label' => 'From outside EU',                            'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Save customers from outside EU as tax-exempt', 'notice' => ''),
     42                'typeOfReasonEU'    => array('label' => 'Select tax exempt reason',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the reason for the tax exemption', 'notice' => ''),
     43                'createExemptCO'    => array('label' => 'From EU',                                    'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Save customers companies from EU as tax-exempt', 'notice' => ''),
     44                'typeOfReasonCO'    => array('label' => 'Select tax exempt reason',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the reason for the tax exemption', 'notice' => ''),
    4145                'warehouseOrder'    => array('label' => 'Order Warehouse',                            'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose from warehouse do you want import products', 'notice' => ''),
    4246                'typeOfOrder'       => array('label' => 'Type of Order',                              'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the type of order', 'notice' => ''),
     
    5862        public static function self() {
    5963            if (self::$instance) return $instance;
    60            
     64
    6165            return new DriveFxWoocommerce();
    6266        }
     
    6468        private function __construct () {
    6569            $this->logs = new Logs();
    66             $this->auth_services = new AuthentificationService();   
    67             $this->syncro_services = new SyncroService();   
    68             $this->utils_services = new UtilsServices();   
    69             $this->orders_services = new OrdersService();   
    70             $this->invoices_services = new InvoicesServices(); 
     70            $this->auth_services = new AuthentificationService();
     71            $this->syncro_services = new SyncroService();
     72            $this->utils_services = new UtilsServices();
     73            $this->orders_services = new OrdersService();
     74            $this->invoices_services = new InvoicesServices();
    7175
    7276            // call init
     
    7579            // store default BACKEND fields settings
    7680            add_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME, array('backend' => $this->options['backend']));
    77            
    78         }
    79        
     81
     82        }
     83
    8084        //Initializes WordPress hooks
    8185        private function init() {
     
    9296            // handler to show notices in admin panel
    9397            add_action('admin_menu', array($this, 'render_notices'));
    94        
     98
    9599            //Obtain status of order in online shop
    96100            add_action( 'woocommerce_order_status_pending',  array($this, 'statusPending'));
     
    102106            add_action( 'woocommerce_order_status_failed',  array($this, 'statusFailed'));
    103107
    104             // HOOKS WOOCOMMERCE - ORDER Status 
     108            // HOOKS WOOCOMMERCE - ORDER Status
    105109            add_action( 'woocommerce_order_status_pending',  array($this, 'addNewOrder'));
    106110            add_action( 'woocommerce_order_status_on-hold',  array($this, 'addNewOrder'));
    107111            add_action( 'woocommerce_order_status_processing',  array($this, 'addNewOrder'));
    108            
     112
    109113            add_action( 'woocommerce_order_status_completed',  array($this, 'completedOrder'),2);
    110114            add_action( 'woocommerce_order_status_cancelled',  array($this, 'cancelOrder'));
     
    116120
    117121            // handler for form submission
    118             add_action('admin_post_woocommerce_fx', array($this, 'woocommerce_fx')); 
     122            add_action('admin_post_woocommerce_fx', array($this, 'woocommerce_fx'));
    119123
    120124            //Verify if exists token in mysql db
    121125            global $wpdb;
    122             $table_name = $wpdb->prefix."postmeta"; 
     126            $table_name = $wpdb->prefix."postmeta";
    123127
    124128            //If exists GET['fxtoken'], so popup is open to obtain key
     
    126130                return;
    127131            $accessToken = filter_var($_GET['accessToken'], FILTER_SANITIZE_STRING);
    128            
     132
    129133            if($accessToken != ''){
    130134                $accessToken = str_replace(' ', '+', $accessToken);
     
    133137                $query = "SELECT * FROM %s WHERE meta_key = %s";
    134138                $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, '_token')));
    135                  
     139
    136140                //Verify if token already exists
    137141                if($resultDB->meta_id != ''){
    138142                    //Delete value in database mysql
    139                     delete_post_meta($resultDB->post_id, '_token'); 
    140                    
     143                    delete_post_meta($resultDB->post_id, '_token');
     144
    141145                    //Obtain next post_id of order in MySQL
    142146                    $query = "SELECT MAX(post_id)+1 as nextPostId FROM %s";
    143147                    $token = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    144                    
     148
    145149                    //add to table postmeta a key of order and stamp of internal document
    146                     add_post_meta($token->nextPostId, '_token', $accessToken);     
     150                    add_post_meta($token->nextPostId, '_token', $accessToken);
    147151                } else {
    148152                    //Obtain next post_id of order in MySQL
     
    173177
    174178        }
    175        
     179
    176180        //Obtain info of plugins and save information
    177181        public function init_plugin() {
     
    194198        }
    195199
    196         public function register_scripts() { 
     200        public function register_scripts() {
    197201            ?> <script>
    198202            var pathPlugin = "<?php echo plugins_url('/' , __FILE__ ); ?>";
    199203            </script> <?php
    200            
     204
    201205            // register scripts that will be used later on
    202206            wp_register_script(DRIVEFXWOOCOMMERCE_PLUGIN_NAME, plugins_url('/js/'.DRIVEFXWOOCOMMERCE_PLUGIN_NAME.'.js' , __FILE__ ));
    203207            wp_register_script('datatable_min', plugins_url('/js/datatable_min.js' , __FILE__ ));
    204            
     208
    205209            // register css that will be used later on
    206210            wp_register_style('style_datatable_jquery', plugins_url('/css/style_datatable_jquery.css' , __FILE__ ));
     
    211215        public function render_settings() {
    212216            include(DRIVEFXWOOCOMMERCE_PLUGIN_DIR.'drivefx-woocommerce-settings.php');
    213            
     217
    214218            // inject our JS script
    215219            wp_enqueue_script(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    216220            wp_enqueue_script('datatable_min');
    217            
     221
    218222            //inject our css of datatable
    219223            wp_enqueue_style('style_datatable_jquery');
    220224            wp_enqueue_style('datatable_css');
    221            
     225
    222226            // inject data (settings) and default messages to JS
    223227            wp_localize_script(DRIVEFXWOOCOMMERCE_PLUGIN_NAME, 'settings', $settings);
    224            
     228
    225229            // inject also the server-side script that will handle the form submission
    226230            wp_localize_script(DRIVEFXWOOCOMMERCE_PLUGIN_NAME, 'url', admin_url('admin-post.php'));
     
    247251            if ($_GET["page"] !=  "drivefx-woocommerce")
    248252                return;
    249            
     253
    250254            $notices = array();
    251255            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     
    284288                <p><strong><?php echo $message ?></strong></p>
    285289            </div><?php
    286         }   
     290        }
    287291
    288292        //Verify if backend configurations are configured
     
    295299                    $notices[$opts['label']] = $opts['notice'];
    296300                    $verifyWarning = true;
    297                 }     
     301                }
    298302            }
    299303
     
    309313        //Called from "external files"
    310314        public function woocommerce_fx() {
    311            
     315
    312316            $method = sanitize_text_field( $_POST['method'] );
    313        
     317
    314318            if(is_array($_POST['refs'])){
    315                 $refs = filter_var_array($_POST['refs'], FILTER_SANITIZE_STRING); 
     319                $refs = filter_var_array($_POST['refs'], FILTER_SANITIZE_STRING);
    316320            } else {
    317321                $refs = '';
     
    319323
    320324            if(isset($_POST['selectItems'])){
    321                 $selectItems = filter_var($_POST['selectItems'], FILTER_SANITIZE_STRING); 
     325                $selectItems = filter_var($_POST['selectItems'], FILTER_SANITIZE_STRING);
    322326            } else {
    323327                $selectItems = '';
     
    325329
    326330            if(isset($_POST['typeOfOrder'])){
    327                 $typeOfOrder = filter_var($_POST['typeOfOrder'], FILTER_SANITIZE_STRING); 
     331                $typeOfOrder = filter_var($_POST['typeOfOrder'], FILTER_SANITIZE_STRING);
    328332            } else {
    329333                $typeOfOrder = '';
     
    331335
    332336            if(isset($_POST['nameTypeOfOrder'])){
    333                 $nameTypeOfOrder = filter_var($_POST['nameTypeOfOrder'], FILTER_SANITIZE_STRING); 
     337                $nameTypeOfOrder = filter_var($_POST['nameTypeOfOrder'], FILTER_SANITIZE_STRING);
    334338            } else {
    335339                $nameTypeOfOrder = '';
     
    337341
    338342            if(isset($_POST['manageStock'])){
    339                 $manageStock = filter_var($_POST['manageStock'], FILTER_SANITIZE_STRING); 
     343                $manageStock = filter_var($_POST['manageStock'], FILTER_SANITIZE_STRING);
    340344            } else {
    341345                $manageStock = '';
     
    343347
    344348            if(isset($_POST['warehouse'])){
    345                 $warehouse = filter_var($_POST['warehouse'], FILTER_SANITIZE_STRING); 
     349                $warehouse = filter_var($_POST['warehouse'], FILTER_SANITIZE_STRING);
    346350            } else {
    347351                $warehouse = '';
    348352            }
    349            
     353
    350354            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    351355
    352356                // get Credentials
    353                 $credentials = $this->syncro_services->fetchCredentials();                   
     357                $credentials = $this->syncro_services->fetchCredentials();
    354358                //Obtain configuration to make login
    355                 $ch = $this->auth_services->PHCLogin($ch, $credentials);       
     359                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    356360                //initial request with login data
    357                 $response = curl_exec($ch);     
     361                $response = curl_exec($ch);
    358362                // send response as JSON
    359                 $response = json_decode($response, true); 
     363                $response = json_decode($response, true);
    360364                // get the temporary token and insert in credentials object
    361                 $credentials->token = $response['result'][0]['token']; 
    362        
     365                $credentials->token = $response['result'][0]['token'];
     366
    363367                //$this->logs->writeFileLog('Login response:', $response);
    364        
     368
    365369            if (curl_error($ch)) {
    366370                $this->logs->writeFileLog('setCommunicationFxWooCommerce', $ch);
     
    377381                //Save data of login to show in backend.php the other fields (type of invoice and type of order)
    378382                $_SESSION['username'] = $response['result'][0]['username'];
    379                
     383
    380384                    //Obtain gama of PHC
    381385                    $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
    382        
     386
    383387                    //$this->logs->writeFileLog('BackEnd response:', $response);
    384388
     
    392396                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    393397                }
    394                
     398
    395399                //Obtain parameter of manage stock
    396                 $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);   
     400                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);
    397401
    398402                //$this->logs->writeFileLog('FrontEnd response:', $response);
    399                
     403
    400404                if (curl_error($ch)) {
    401405                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
     
    405409                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    406410                } else {
    407                     foreach ($response['result'] as $key => $value){ 
     411                    foreach ($response['result'] as $key => $value){
    408412                        if($response['result'][$key]['descricao'] === 'AllowStocks'){
    409413                            $_SESSION['manageStockParameter'] = $response['result'][$key]['valor'];
     
    428432                    }
    429433                    break;
     434                case 'updatePricesProducts':
     435                    //Update only prices of products
     436                    return $this->updatePricesProducts($refs);
     437                    break;
    430438                case 'updateAllFieldsProducts':
    431439                    //Update all fields of products
    432440                    return $this->updateAllFieldsProducts($refs);
    433                     break; 
     441                    break;
    434442                case 'statusOfOrder':
    435443                    if($_SESSION['gamaDRIVEFX'] >= 9) {
     
    452460                case 'updateTypeOfOrder':
    453461                    if($_SESSION['gamaDRIVEFX'] >= 9) {
    454                         //Update type of order dropdownlist 
     462                        //Update type of order dropdownlist
    455463                        $this->updateTypeOfOrders();
    456464                    }
     
    538546            ));
    539547            return apply_filters( 'woocommerce_get_settings_' . $this->id, $settings );
    540         }           
    541            
    542         //Lock System       
     548        }
     549
     550        //Lock System
    543551        public function lockStart() {
    544552            $this->logs->writeFileLog('lockStart', "Entrei" );
     
    546554
    547555            $maxAttempt=10;
    548            
     556
    549557            for($attempt=0;$attempt<$maxAttempt;$attempt++){
    550558                $lockFilePath =  __DIR__.'/logsErrors/tim.lock';
    551559                $date = new DateTime();
    552560                $time =  $date->getTimestamp();
    553                    
     561
    554562                if (!file_exists($lockFilePath)){
    555563                    @file_put_contents($lockFilePath, $time);
     
    558566                        continue;
    559567                    }
    560                    
     568
    561569                    $this->logs->writeFileLog('lockStart', "Sai" );
    562            
    563                     return true; 
    564        
    565                 }
    566            
     570
     571                    return true;
     572
     573                }
     574
    567575                $contents = file_get_contents($lockFilePath);
    568576
    569577                $lockedtime = (int)$contents;
    570                
     578
    571579                if($time-$lockedtime>10){
    572                    
     580
    573581                    unlink($lockFilePath);
    574582                    @file_put_contents($lockFilePath, $time);
     
    580588                    return true;
    581589                }else{
    582                    
     590
    583591                    sleep(1);
    584592                    continue;
    585593                }
    586                
    587            
     594
     595
    588596            }
    589597            $this->logs->writeFileLog('lockStart', "Sair");
    590598            return true;
    591599
    592        
     600
    593601        }
    594602
     
    600608            return true;
    601609        }
    602            
     610
    603611
    604612        /** Order Status **/
     
    606614        public function statusPending() {
    607615            $this->fieldStatus = "Pending";
    608        
     616
    609617        }
    610618        //Change order status
     
    634642
    635643
    636         //Communicate with FX backend and obtain type of invoice document and type of order 
     644        //Communicate with FX backend and obtain type of invoice document and type of order
    637645        public function setCommunicationFx() {
    638646            session_start();
    639        
     647
    640648            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    641649            // get Credentials
    642             $credentials = $this->syncro_services->fetchCredentials();     
     650            $credentials = $this->syncro_services->fetchCredentials();
    643651            //Obtain configuration to make login
    644             $ch = $this->auth_services->PHCLogin($ch, $credentials);       
     652            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    645653            //initial request with login data
    646654            $response = curl_exec($ch);
    647655            // send response as JSON
    648             $response = json_decode($response, true); 
     656            $response = json_decode($response, true);
    649657            // get the temporary token and insert in credentials object
    650658            $credentials->token = $response['result'][0]['token'];
     
    666674                //Save data of login to show in backend.php the other fields (type of invoice and type of order)
    667675                $_SESSION['username'] = $response['result'][0]['username'];
    668                
     676
    669677                //Choose Nif Field
    670678                $selected_dropdown = '';
    671679                $_SESSION['fieldNif'] = '';
    672                
    673                
     680
     681
    674682                $_SESSION['includeTaxonSendCost']="<option value='true'";
    675683                if($settings['backend']['includeTaxonSendCost'] == 'true')
     
    680688                        $_SESSION['includeTaxonSendCost'].=" selected ";
    681689                $_SESSION['includeTaxonSendCost'].=">No</option>";
    682                        
    683                            
    684                            
     690
     691
     692
    685693                if($settings['backend']['fieldNif'] == "company"){
    686694                  $_SESSION['fieldNif'] .= "<option value='company' selected >Company</option><br>";
     
    702710                  $_SESSION['fieldNif'] .= "<option value='address_2'>Address 2</option><br>";
    703711                  $_SESSION['fieldNif'] .= "<option value='state'  >State</option><br>";
    704                    $_SESSION['fieldNif'] .= "<option value='nif' selected >Billing Nif (Plugin)</option><br>"; 
     712                   $_SESSION['fieldNif'] .= "<option value='nif' selected >Billing Nif (Plugin)</option><br>";
    705713                }
    706714
    707715                //Obtain gama of PHC
    708716                $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
    709                
     717
    710718                //$this->logs->writeFileLog('BackEnd response:', $response);
    711719
     
    719727                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    720728                }
    721                
     729
    722730                //Obtain parameter of manage stock
    723                 $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);   
     731                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);
    724732
    725733                //$this->logs->writeFileLog('FrontEnd response:', $response);
     
    732740                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    733741                } else {
    734                     foreach ($response['result'] as $key => $value){ 
     742                    foreach ($response['result'] as $key => $value){
    735743                        if($response['result'][$key]['descricao'] === 'AllowStocks'){
    736744                            $_SESSION['manageStockParameter'] = $response['result'][$key]['valor'];
     
    740748
    741749                //Obtain type invoices
    742                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Td', 'inactivo', 0);   
    743                        
     750                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Td', 'inactivo', 0);
     751
    744752                //$this->logs->writeFileLog('TypeInvoice response:', $response);
    745753
     
    755763                    //Create options of dropdownlist invoices
    756764                    $i = 0;
    757                     $typeInvoice = array(); 
     765                    $typeInvoice = array();
    758766                    $_SESSION['typeOfInvoice'] = '';
    759                    
     767
    760768                    foreach ($response['result'] as $key => $value){
    761769                        if($value['tiposaft'] == 'FT' || $value['tiposaft'] == 'FS' || $value['tiposaft'] == 'FR'){
     
    765773                                $selected_dropdown = '';
    766774                            }
    767                            
    768                             $_SESSION['typeOfInvoice'] .= "<option value=" . $value['ndoc'] . " " . $selected_dropdown . ">" . $value['nmdoc'] ."</option><br>";         
     775
     776                            $_SESSION['typeOfInvoice'] .= "<option value=" . $value['ndoc'] . " " . $selected_dropdown . ">" . $value['nmdoc'] ."</option><br>";
    769777                            ++$i;
    770778                        }
    771779                    }
    772                     #Obtain tax free reason list
    773                     $response = $this->utils_services->entityName_Query($ch, $credentials, 'Miseimp'); 
    774                                        
     780                    #Obtain tax free reason list (for outside of PT)
     781                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'Miseimp');
     782
    775783                    //$this->logs->writeFileLog('Miseimp response:', $response);
    776784
     
    786794                        //Create options of dropdownlist reasons list
    787795                        $i = 0;
    788                         $typeInvoice = array(); 
     796                        $typeInvoice = array();
    789797                        $_SESSION['typeOfReason'] = '';
    790                        
    791                         foreach ($response['result'] as $key => $value){                       
     798
     799                        foreach ($response['result'] as $key => $value){
    792800                            if($settings['backend']['typeOfReason'] == $value['codigo']){
    793801                                $selected_dropdown = 'selected';
     
    795803                                $selected_dropdown = '';
    796804                            }
    797                            
    798                             $_SESSION['typeOfReason'] .= "<option value=" . $value['codigo'] . " " . $selected_dropdown . ">" . $value['descricao'] ."</option><br>";         
     805
     806                            $_SESSION['typeOfReason'] .= "<option value=" . $value['codigo'] . " " . $selected_dropdown . ">" . $value['descricao'] ."</option><br>";
    799807                            ++$i;
    800808                        }
    801809                    }
    802 
     810                    #Obtain tax free reason list (for outside of EU)
     811                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'Miseimp');
     812
     813                    //$this->logs->writeFileLog('Miseimp response:', $response);
     814
     815                    if (curl_error($ch)) {
     816                        $this->logs->writeFileLog('setCommunication3.2.1', $ch);
     817                    } else if(empty($response)){
     818                        $this->logs->writeFileLog('setCommunication3.2.1', 'EMPTY RESPONSE');
     819                        $this->messagesError("Can't connect to webservice!! There's an empty response");
     820                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
     821                        $this->logs->writeFileLog('setCommunication3.2.1', $response['messages'][0]['messageCodeLocale']);
     822                        $this->messagesError(" obtain dropdown with tax free reason list! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
     823                    } else {
     824                        //Create options of dropdownlist reasons list
     825                        $i = 0;
     826                        $typeInvoice = array();
     827                        $_SESSION['typeOfReasonEU'] = '';
     828
     829                        foreach ($response['result'] as $key => $value){
     830                            if($settings['backend']['typeOfReasonEU'] == $value['codigo']){
     831                                $selected_dropdown = 'selected';
     832                            } else {
     833                                $selected_dropdown = '';
     834                            }
     835
     836                            $_SESSION['typeOfReasonEU'] .= "<option value=" . $value['codigo'] . " " . $selected_dropdown . ">" . $value['descricao'] ."</option><br>";
     837                            ++$i;
     838                        }
     839                    }
     840                    #Obtain tax free reason list (for EU Companies)
     841                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'Miseimp');
     842
     843                    //$this->logs->writeFileLog('Miseimp response:', $response);
     844
     845                    if (curl_error($ch)) {
     846                        $this->logs->writeFileLog('setCommunication3.2.2', $ch);
     847                    } else if(empty($response)){
     848                        $this->logs->writeFileLog('setCommunication3.2.2', 'EMPTY RESPONSE');
     849                        $this->messagesError("Can't connect to webservice!! There's an empty response");
     850                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
     851                        $this->logs->writeFileLog('setCommunication3.2.2', $response['messages'][0]['messageCodeLocale']);
     852                        $this->messagesError(" obtain dropdown with tax free reason list! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
     853                    } else {
     854                        //Create options of dropdownlist reasons list
     855                        $i = 0;
     856                        $typeInvoice = array();
     857                        $_SESSION['typeOfReasonCO'] = '';
     858
     859                        foreach ($response['result'] as $key => $value){
     860                            if($settings['backend']['typeOfReasonCO'] == $value['codigo']){
     861                                $selected_dropdown = 'selected';
     862                            } else {
     863                                $selected_dropdown = '';
     864                            }
     865
     866                            $_SESSION['typeOfReasonCO'] .= "<option value=" . $value['codigo'] . " " . $selected_dropdown . ">" . $value['descricao'] ."</option><br>";
     867                            ++$i;
     868                        }
     869                    }
    803870                    #Obtain services name list
    804                     $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0', 'stns', '1');   
    805                                            
     871                    $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0', 'stns', '1');
     872
    806873                    if (curl_error($ch)) {
    807874                        $this->logs->writeFileLog('setCommunication3.2', $ch);
     
    816883                        $i = 0;
    817884                        $_SESSION['shippingName'] = '';
    818                        
    819                         foreach ($response['result'] as $key => $value){                       
     885
     886                        foreach ($response['result'] as $key => $value){
    820887                            if($settings['backend']['shippingName'] == $value['ref']){
    821888                                $selected_dropdown = 'selected';
     
    823890                                $selected_dropdown = '';
    824891                            }
    825                            
    826                             $_SESSION['shippingName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";         
     892
     893                            $_SESSION['shippingName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";
    827894                            ++$i;
    828895                        }
     
    830897                        $i = 0;
    831898                        $_SESSION['feesName'] = '';
    832                        
    833                         foreach ($response['result'] as $key => $value){                       
     899
     900                        foreach ($response['result'] as $key => $value){
    834901                            if($settings['backend']['feesName'] == $value['ref']){
    835902                                $selected_dropdown = 'selected';
     
    837904                                $selected_dropdown = '';
    838905                            }
    839                            
    840                             $_SESSION['feesName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";         
     906
     907                            $_SESSION['feesName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";
    841908                            ++$i;
    842909                        }
     
    845912                    #If gama is equal or higher of STAR
    846913                    if($_SESSION['gamaDRIVEFX'] >= 9){
    847                         //Obtain type orders   
    848                         $response = $this->utils_services->doubleFilter($ch, $credentials, 'Ts', 'bdempresas', 'CL', 'trfa', '0'); 
    849                                            
     914                        //Obtain type orders
     915                        $response = $this->utils_services->doubleFilter($ch, $credentials, 'Ts', 'bdempresas', 'CL', 'trfa', '0');
     916
    850917                        //$this->logs->writeFileLog('OrderType response:', $response);
    851918
     
    861928                            $i = 0;
    862929                            $count = count($response['result']);
    863                             $typeInvoice = array(); 
     930                            $typeInvoice = array();
    864931                            $_SESSION['typeOfOrder'] = '';
    865932                            //Create options of dropdownlist internal documents
     
    875942                                    } else if ($key == "nmdos"){
    876943                                        //Obtain type orders
    877                                         $response2 = $this->utils_services->getInternalDoc($ch, $credentials, 'Bo', 'nmdos', $value);   
     944                                        $response2 = $this->utils_services->getInternalDoc($ch, $credentials, 'Bo', 'nmdos', $value);
    878945
    879946                                       // $this->logs->writeFileLog('InternalDoc response:', $response2);
     
    894961                                            $query = "SELECT MAX(post_id)+1 as nextPostId FROM %s";
    895962                                            $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    896                                        
     963
    897964                                            if(($response2['result'][0]['obrano'] == '' || $response2['result'][0]['obrano'] <= $docid->nextPostId) && $response['result'][$i]['bdempresas'] == 'CL'){
    898965                                                $wrongTypeOrder = false;
     
    903970
    904971                                        if($wrongTypeOrder == false){
    905                                             $typeInvoice[$i]["nmdos"] = $value;     
     972                                            $typeInvoice[$i]["nmdos"] = $value;
    906973                                        }
    907974                                    }
    908975                                }
    909                    
     976
    910977                                if($typeInvoice[$i]["nmdos"] != ''){
    911                                     $_SESSION['typeOfOrder'] .= "<option id=" . $typeInvoice[$i]["nmdos"] . " value=" . $typeInvoice[$i]["ndos"] . " " . $selected_dropdown . ">" .  $typeInvoice[$i]["nmdos"] ."</option><br>";   
     978                                    $_SESSION['typeOfOrder'] .= "<option id=" . $typeInvoice[$i]["nmdos"] . " value=" . $typeInvoice[$i]["ndos"] . " " . $selected_dropdown . ">" .  $typeInvoice[$i]["nmdos"] ."</option><br>";
    912979                                }
    913980                                ++$i;
    914981                            }
    915982                        }
    916                    
     983
    917984                        //Obtain warehouses
    918                         $response = $this->utils_services->entityName_Query($ch, $credentials, 'Sa');   
     985                        $response = $this->utils_services->entityName_Query($ch, $credentials, 'Sa');
    919986
    920987                        //$this->logs->writeFileLog('Warehouses response:', $response);
     
    9531020                                        }
    9541021                                        $_SESSION['warehouse'] .= "<option id=" . $value . " value=" . $value . " " . $selected_dropdown . ">" .  $value ."</option><br>";
    955                                        
     1022
    9561023                                        if($settings['backend']['warehouseOrder'] == $value){
    9571024                                            $selected_dropdown = 'selected';
     
    9621029                            }
    9631030                        }
    964                     } 
     1031                    }
    9651032
    9661033                    //Verify if are selected type of internal document and send invoice checkbox
    9671034                    if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['createInvoice'] == 'on' && $settings['backend']['typeOfInvoice'] > 0 && isset($settings['backend']['sendInvoice'])){
    9681035                        //Obtain type invoices
    969                         $response = $this->utils_services->paramsGetReportForPrint($ch, $credentials); 
     1036                        $response = $this->utils_services->paramsGetReportForPrint($ch, $credentials);
    9701037
    9711038                        //$this->logs->writeFileLog('ReportPrint response:', $response);
     
    9961063                             if($sendEmail == false){
    9971064                                $this->logs->writeFileLog('setCommunicationFx5', 'It is not possible to send email. Please verify your configuration reports of PHC');
    998                                 $this->messagesError(": It is not possible to send email. Please verify your configuration reports of PHC because does not exists any default template");
    999                             } 
    1000                         }
    1001                     }
    1002                 }
    1003                
     1065                                //$this->messagesError(": It is not possible to send email. Please verify your configuration reports of PHC because does not exists any default template");
     1066                            }
     1067                        }
     1068                    }
     1069                }
     1070
    10041071                //Obtain currency coin of company
    1005                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
    1006                        
     1072                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);
     1073
    10071074                //$this->logs->writeFileLog('E1 response:', $response);
    10081075
     
    10221089            //Logout
    10231090            $this->auth_services->PHCLogout($ch, $credentials);
    1024            
     1091
    10251092        }
    10261093
    10271094        //Update dropdownlist of type orders
    10281095        public function updateTypeOfOrders(){
    1029            
     1096
    10301097            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    10311098            // get Credentials
    1032             $credentials = $this->syncro_services->fetchCredentials();         
     1099            $credentials = $this->syncro_services->fetchCredentials();
    10331100            //Obtain configuration to make login
    1034             $ch = $this->auth_services->PHCLogin($ch, $credentials);   
     1101            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    10351102            //initial request with login data
    1036             $response = curl_exec($ch); 
     1103            $response = curl_exec($ch);
    10371104            // send response as JSON
    1038             $response = json_decode($response, true); 
     1105            $response = json_decode($response, true);
    10391106            // get the temporary token and insert in credentials object
    10401107            $credentials->token = $response['result'][0]['token'];
    10411108
    1042             //$this->logs->writeFileLog('completedOrder Login:', $response); 
     1109            //$this->logs->writeFileLog('completedOrder Login:', $response);
    10431110
    10441111            if (curl_error($ch)) {
     
    10501117            } else {
    10511118                //Obtain type orders
    1052                  $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Ts', 'inactivo', 0);   
    1053                    
     1119                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Ts', 'inactivo', 0);
     1120
    10541121                 //$this->logs->writeFileLog('OrderType response:', $response);
    1055            
     1122
    10561123                if (curl_error($ch)) {
    10571124                    $this->logs->writeFileLog('updateTypeOfOrders2', $ch);
     
    10651132                    $i = 0;
    10661133                    $count = count($response['result']);
    1067                     $typeInvoice = array(); 
    1068                    
     1134                    $typeInvoice = array();
     1135
    10691136                    //Create options of dropdownlist internal documents
    10701137                    while ($i < $count) {
     
    10791146                            } else if ($key == "nmdos"){
    10801147                                //Obtain type orders
    1081                                 $response2 = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', 'nmdos', $value); 
     1148                                $response2 = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', 'nmdos', $value);
    10821149
    10831150                                // $this->logs->writeFileLog('Bo response:', $response2);
     
    10961163                                    $query = "SELECT MAX(post_id) as nextPostId FROM %s";
    10971164                                    $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    1098                                    
     1165
    10991166                                    if(($response2['result'][0]['obrano'] == '' || $response2['result'][0]['obrano'] <= $docid->nextPostId) && $response['result'][$i]['bdempresas'] == 'CL'){
    11001167                                        $wrongTypeOrder = false;
     
    11051172
    11061173                                if($wrongTypeOrder == false){
    1107                                     $typeInvoice[$i]["nmdos"] = $value;     
     1174                                    $typeInvoice[$i]["nmdos"] = $value;
    11081175                                }
    1109                                
    1110                             }
    1111                         }
    1112                        
     1176
     1177                            }
     1178                        }
     1179
    11131180                        if($typeInvoice[$i]["nmdos"] != ''){
    1114                             echo "<option id=" . $typeInvoice[$i]["nmdos"] . " value=" . $typeInvoice[$i]["ndos"] . " " . $selected_dropdown . ">" .  $typeInvoice[$i]["nmdos"] ."</option><br>"; 
     1181                            echo "<option id=" . $typeInvoice[$i]["nmdos"] . " value=" . $typeInvoice[$i]["ndos"] . " " . $selected_dropdown . ">" .  $typeInvoice[$i]["nmdos"] ."</option><br>";
    11151182                        }
    11161183                        ++$i;
     
    11191186            }
    11201187            //Logout
    1121             $this->auth_services->PHCLogout($ch, $credentials);     
     1188            $this->auth_services->PHCLogout($ch, $credentials);
    11221189        }
    11231190
    11241191        //Obtain value of field to PHC
    11251192        public function statusOfOrder($selectItems, $typeOfOrder){
    1126            
     1193
    11271194            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    11281195
    11291196            // get Credentials
    1130             $credentials = $this->syncro_services->fetchCredentials();     
     1197            $credentials = $this->syncro_services->fetchCredentials();
    11311198            //Obtain configuration to make login
    1132             $ch = $this->auth_services->PHCLogin($ch, $credentials); 
     1199            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    11331200            //initial request with login data
    1134             $response = curl_exec($ch); 
     1201            $response = curl_exec($ch);
    11351202            // send response as JSON
    1136             $response = json_decode($response, true); 
     1203            $response = json_decode($response, true);
    11371204            // get the temporary token and insert in credentials object
    11381205            $credentials->token = $response['result'][0]['token'];
    1139      
    1140             //$this->logs->writeFileLog('completedOrder Login:', $response); 
     1206
     1207            //$this->logs->writeFileLog('completedOrder Login:', $response);
    11411208
    11421209            if (curl_error($ch)) {
     
    11481215            } else {
    11491216                //Obtain type invoices
    1150                 $response = $this->utils_services->paramsQuery4($ch, $credentials, 'Ts', $selectItems, $typeOfOrder);   
    1151                
     1217                $response = $this->utils_services->paramsQuery4($ch, $credentials, 'Ts', $selectItems, $typeOfOrder);
     1218
    11521219                //$this->logs->writeFileLog('Type Invoices:', $response);
    11531220
     
    11641231            //Logout
    11651232            $this->auth_services->PHCLogout($ch, $credentials);
    1166            
     1233
    11671234        }
    11681235
     
    11731240
    11741241            session_start();
    1175             $credentials = $this->syncro_services->fetchCredentials(); 
     1242            $credentials = $this->syncro_services->fetchCredentials();
    11761243            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
    11771244            $prodPack = $this->syncro_services->processProducts($orderid);
     
    11871254
    11881255        }
    1189        
     1256
    11901257        //If status of order is cancelled or failed
    11911258        public function cancelOrder($order_id){
     
    11941261
    11951262            // get Credentials
    1196             $credentials = $this->syncro_services->fetchCredentials();     
     1263            $credentials = $this->syncro_services->fetchCredentials();
    11971264            //Obtain configuration to make login
    1198             $ch = $this->auth_services->PHCLogin($ch, $credentials);   
     1265            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    11991266            //initial request with login data
    1200             $response = curl_exec($ch);     
     1267            $response = curl_exec($ch);
    12011268            // send response as JSON
    1202             $response = json_decode($response, true); 
     1269            $response = json_decode($response, true);
    12031270            // get the temporary token and insert in credentials object
    12041271            $credentials->token = $response['result'][0]['token'];
    1205            
    1206             //$this->logs->writeFileLog('cancelOrder Login:', $response); 
     1272
     1273            //$this->logs->writeFileLog('cancelOrder Login:', $response);
    12071274
    12081275            if (curl_error($ch)) {
     
    12171284
    12181285                 //$this->logs->writeFileLog('cancelOrder BackEnd:', $response);
    1219                  
     1286
    12201287                if (curl_error($ch)) {
    12211288                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     
    12271294                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    12281295                }
    1229                
    1230                 if($_SESSION['gamaDRIVEFX'] >= 9) {             
     1296
     1297                if($_SESSION['gamaDRIVEFX'] >= 9) {
    12311298                    //Obtain currency coin of company
    1232                     $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
    1233                    
     1299                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);
     1300
    12341301                    //$this->logs->writeFileLog('E1 response:', $response);
    1235        
     1302
    12361303
    12371304                    if (curl_error($ch)) {
     
    12491316                            $filterItem = "bostamp";
    12501317                            $valueItem = $docid['_docid'][sizeof($docid['_docid'])-1];
    1251                          
     1318
    12521319                            //Verify if exists in bd
    1253                             $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem); 
    1254                    
    1255                             //$this->logs->writeFileLog('Bo response:', $response); 
     1320                            $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem);
     1321
     1322                            //$this->logs->writeFileLog('Bo response:', $response);
    12561323
    12571324                            if (curl_error($ch)) {
     
    12641331
    12651332                                //If is not a SAFT document we update the document
    1266                                 if(!empty($response) && $response['result'][0]['isconfiguredtosign'] == false || ($response['result'][0]['isconfiguredtosign'] == true && 
     1333                                if(!empty($response) && $response['result'][0]['isconfiguredtosign'] == false || ($response['result'][0]['isconfiguredtosign'] == true &&
    12671334                                    $response['result'][0]['draftRecord'] == 1)){
    12681335
     
    12761343                                    $response['result'][0]['Operation'] = 2;
    12771344
    1278                                     $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);   
    1279                    
    1280                                     //$this->logs->writeFileLog('BoWs Save:', $response);                                   
     1345                                    $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
     1346
     1347                                    //$this->logs->writeFileLog('BoWs Save:', $response);
    12811348
    12821349                                    if (curl_error($ch)) {
     
    12911358                        }
    12921359                    }
    1293                    
     1360
    12941361                }
    12951362                //Logout
     
    13061373
    13071374            // get Credentials
    1308             $credentials = $this->syncro_services->fetchCredentials();         
     1375            $credentials = $this->syncro_services->fetchCredentials();
    13091376            //Obtain configuration to make login
    13101377            $ch = $this->auth_services->PHCLogin($ch, $credentials);
     
    13121379            $response = curl_exec($ch);
    13131380            // send response as JSON
    1314             $response = json_decode($response, true);   
     1381            $response = json_decode($response, true);
    13151382            // get the temporary token and insert in credentials object
    1316             $credentials->token = $response['result'][0]['token'];   
     1383            $credentials->token = $response['result'][0]['token'];
    13171384
    13181385            if (curl_error($ch)) {
    13191386                $this->logs->writeFileLog('completedOrder', $ch);
    13201387            } else if(empty($response)){
    1321                 $this->logs->writeFileLog('completedOrder', 'EMPTY RESPONSE');     
     1388                $this->logs->writeFileLog('completedOrder', 'EMPTY RESPONSE');
    13221389            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1323                 $this->logs->writeFileLog('completedOrder', $response['messages'][0]['messageCodeLocale']);     
     1390                $this->logs->writeFileLog('completedOrder', $response['messages'][0]['messageCodeLocale']);
    13241391            } else {
    13251392                //Obtain information from company
    1326                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
    1327    
     1393                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);
     1394
    13281395                if (curl_error($ch)) {
    13291396                    $this->logs->writeFileLog('completedOrder2', $ch);
     
    13351402                    //Verify if currency of shop corresponds to PHC
    13361403                    if($response['result'][0]['moeda'] == get_option('woocommerce_currency')){
    1337                    
     1404
    13381405                        //If in settings of backoffice is checked option "create invoice"
    13391406                        if($settings['backend']['createInvoice'] == 'on'){
    13401407                            //Obtain stamp of internal document based in order
    13411408                            $docid = get_post_meta($order_id);
    1342                
     1409
    13431410                            $filterItem = "bostamp";
    13441411                            $valueItem = $docid['_docid'][sizeof($docid['_docid'])-1];
     
    13541421                            }
    13551422                            if(empty($valueItem)){
    1356                                 $order_received = sanitize_text_field($order_id ); 
     1423                                $order_received = sanitize_text_field($order_id );
    13571424                                $docid = get_post_meta($order_received);
    13581425                                $valueItem = $docid['_docid'][sizeof($docid['_docid'])-1];
    13591426                            }
    1360                            
     1427
    13611428                             //Obtain gama of PHC
    13621429                             $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     
    13711438                                $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    13721439                            }
    1373                            
    1374                             if($_SESSION['gamaDRIVEFX'] >= 9) {                     
     1440
     1441                            if($_SESSION['gamaDRIVEFX'] >= 9) {
    13751442                                //Verify if exists in bd
    1376                                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem); 
    1377                    
     1443                                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem);
     1444
    13781445                                if (curl_error($ch)) {
    13791446                                    $this->logs->writeFileLog('completedOrder3', $ch);
    13801447                                } else if(empty($response)){
    1381                                     $this->logs->writeFileLog('completedOrder3', 'EMPTY RESPONSE');             
     1448                                    $this->logs->writeFileLog('completedOrder3', 'EMPTY RESPONSE');
    13821449                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1383                                     $this->logs->writeFileLog('completedOrder3', $response['messages'][0]['messageCodeLocale']);             
    1384                                 } else { 
     1450                                    $this->logs->writeFileLog('completedOrder3', $response['messages'][0]['messageCodeLocale']);
     1451                                } else {
    13851452
    13861453
     
    13881455                                    $response['result'][0]['draftRecord'] == 1)){
    13891456
    1390                                         if(!empty($response['result'][0])){         
     1457                                        if(!empty($response['result'][0])){
    13911458                                            //Obtain status
    13921459                                            $statusOrderShop = $this->utils_services->genericFieldsList($settings['backend']['statusOfOrder']);
     
    13991466
    14001467                                            //Save internal document
    1401                                             $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);             
    1402                                            
     1468                                            $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);
     1469
    14031470                                            if (curl_error($ch)) {
    14041471                                                $this->logs->writeFileLog('completedOrder4', $ch);
     
    14101477                                        }
    14111478                                    }
    1412                                    
     1479
    14131480                                    $response = $response['result'][0];
    1414                                    
     1481
    14151482                                    if(!empty($response['bostamp'])){
    14161483                                        //Create Invoice only if is configurated type of invoices
     
    14251492                                }
    14261493                            } else {
    1427                                 //Add Ft 
     1494                                //Add Ft
    14281495                                $this->addSimpleFT($ch,$order_id, $credentials);
    14291496                            }
     
    14371504            $this->logs->writeFileLog('completedOrder', "Sair" . $order_id);
    14381505            $this->lockEnd();
    1439         }   
     1506        }
    14401507
    14411508        //Convert internal document to invoice
     
    14431510
    14441511            $this->logs->writeFileLog('addInternalDocumentInvoice', "Entrei addInternalDocumentInvoice ft:" . $order_id);
    1445            
     1512
    14461513            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
    14471514            $ftprodPack = $this->syncro_services->processFtProducts($orderid);
     
    14521519            $this->manageStock($ch, $credentials, $response);
    14531520            $this->sendEmail($ch, $credentials, $response);
    1454            
     1521
    14551522            $this->logs->writeFileLog('addInternalDocumentInvoice', "sai addInternalDocumentInvoice ft:" . $order_id);
    14561523        }
     
    14601527
    14611528            $this->logs->writeFileLog('addSimpleft', "Entrei simple ft:" . $orderid);
    1462            
     1529
    14631530            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
    14641531            $ftprodPack = $this->syncro_services->processFtProducts($orderid);
     
    14691536            $this->manageStock($ch, $credentials, $response);
    14701537            $this->sendEmail($ch, $credentials, $response);
    1471            
     1538
    14721539            $this->logs->writeFileLog('addSimpleft', "Sai simple ft:" . $orderid);
    14731540        }
     
    14751542        //Manage stock
    14761543        public function manageStock($ch, $credentials, $response){
    1477            
     1544
    14781545            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    1479        
     1546
    14801547            # Manage stock
    14811548            if($_SESSION['gamaDRIVEFX'] >= 9) {
    14821549                if($settings['backend']['manageStock'] == 'on'){
    1483                                    
     1550
    14841551                    $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
    14851552                    $order_received = get_option('woocommerce_checkout_order_received_endpoint');
     
    14901557                        $order = new WC_Order( $order_received );
    14911558                    }
    1492                
     1559
    14931560                    $i = 0;
    14941561                    foreach($order->get_items() as $key => $value){
     
    15021569                    $fisProducts =  $_SESSION['voProducts']['fis'];
    15031570
    1504                    
     1571
    15051572                    $i = 0;
    15061573                    $count = count($fisProducts);
    1507                     //$this->logs->writeFileLog('response:', $count);   
     1574                    //$this->logs->writeFileLog('response:', $count);
    15081575                    while ($i < $count) {
    15091576                        foreach ($fisProducts[$i] as $key => $value){
     
    15161583                                    $this->logs->writeFileLog('addSimpleFT16', $ch);
    15171584                                } else if(empty($response)){
    1518                                     $this->logs->writeFileLog('addSimpleFT16', 'EMPTY RESPONSE');                           
     1585                                    $this->logs->writeFileLog('addSimpleFT16', 'EMPTY RESPONSE');
    15191586                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1520                                     $this->logs->writeFileLog('addSimpleFT16', $response['messages'][0]['messageCodeLocale']);                           
     1587                                    $this->logs->writeFileLog('addSimpleFT16', $response['messages'][0]['messageCodeLocale']);
    15211588                                } else {
    15221589                                #If find ref, update stock
     
    15281595                                    }
    15291596                                }
    1530                             }   
     1597                            }
    15311598                        }
    15321599                        ++$i;
     
    15581625                    $this->logs->writeFileLog('addSimpleFT17', $ch);
    15591626                } else if(empty($response)){
    1560                     $this->logs->writeFileLog('addSimpleFT17', 'EMPTY RESPONSE');                       
     1627                    $this->logs->writeFileLog('addSimpleFT17', 'EMPTY RESPONSE');
    15611628                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1562                     $this->logs->writeFileLog('addSimpleFT17', $response['messages'][0]['messageCodeLocale']);                       
     1629                    $this->logs->writeFileLog('addSimpleFT17', $response['messages'][0]['messageCodeLocale']);
    15631630                } else {
    15641631                    //Verify if exists template as default
     
    15751642                        }
    15761643                        ++$i;
    1577                     }                                                           
     1644                    }
    15781645                    #If exists template as default
    1579                     if($sendEmail == true){                                     
     1646                    if($sendEmail == true){
    15801647                        //Obtain client
    15811648                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Cl', 'no', $_SESSION['numberClient']);
    15821649
    15831650                        //$this->logs->writeFileLog('custom_by_no:', $response);
    1584                        
     1651
    15851652                        if (curl_error($ch)) {
    15861653                            $this->logs->writeFileLog('addSimpleFT18', $ch);
    15871654                        } else if(empty($response)){
    1588                             $this->logs->writeFileLog('addSimpleFT18', 'EMPTY RESPONSE');                           
     1655                            $this->logs->writeFileLog('addSimpleFT18', 'EMPTY RESPONSE');
    15891656                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    15901657                            $this->logs->writeFileLog('addSimpleFT18', $response['messages'][0]['messageCodeLocale']);
     
    15951662                                //Email From
    15961663                                $infoAdmin = $this->get_settingsAdmin();
    1597                                 $emailAdmin = $infoAdmin[3]['default'];                                 
     1664                                $emailAdmin = $infoAdmin[3]['default'];
    15981665                                ###
    15991666                                $body = $settings['backend']['emailBody'];
     
    16041671                                                                    $_SESSION['ftstamp'], $_SESSION['emailClient'],
    16051672                                                                    $emailAdmin, $settings['backend']['typeOfInvoice'], '', $body);
    1606                                                                                        
     1673
    16071674                                //$this->logs->writeFileLog('paramsSendReportEmail:', $response);
    1608                                
     1675
    16091676                                if (curl_error($ch)) {
    16101677                                    $this->logs->writeFileLog('addSimpleFT19', $ch);
    16111678                                } else if(empty($response)){
    1612                                     $this->logs->writeFileLog('addSimpleFT19', 'EMPTY RESPONSE');                               
     1679                                    $this->logs->writeFileLog('addSimpleFT19', 'EMPTY RESPONSE');
    16131680                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1614                                     $this->logs->writeFileLog('addSimpleFT19', $response['messages'][0]['messageCodeLocale']);                               
     1681                                    $this->logs->writeFileLog('addSimpleFT19', $response['messages'][0]['messageCodeLocale']);
    16151682                                } else {
    16161683                                    $this->logs->writeFileLog('Info:', 'Email sended');
     
    16211688                }
    16221689            }
    1623             return $sendedEmail;                       
     1690            return $sendedEmail;
    16241691        }
    16251692
     
    16301697            $post = array(
    16311698                          'post_title'   => $nomeProduct,
    1632                           'post_status'  => "publish",                   
     1699                          'post_status'  => "publish",
    16331700                          'post_name'    => $slugNameProduct,
    16341701                          'post_type'    => "product"
    16351702                         );
    1636        
     1703
    16371704            //Create product/post:
    16381705            $new_post_id = wp_insert_post($post, $wp_error);
     
    16491716
    16501717            update_post_meta( $new_post_id, '_sku', $sku);
    1651             update_post_meta( $new_post_id, '_visibility', $visible); 
     1718            update_post_meta( $new_post_id, '_visibility', $visible);
    16521719            update_post_meta( $new_post_id, '_price', $price );
    16531720            update_post_meta( $new_post_id, '_regular_price', $price );
     
    16561723                update_post_meta( $new_post_id, '_manage_stock', $manageStock);
    16571724                update_post_meta( $new_post_id, '_stock', $stockUnitsProduct);
    1658             } 
     1725            }
    16591726
    16601727            //To return product that can't be inserted
     
    16701737
    16711738            // get Credentials
    1672             $credentials = $this->syncro_services->fetchCredentials();     
     1739            $credentials = $this->syncro_services->fetchCredentials();
    16731740            //Obtain configuration to make login
    1674             $ch = $this->auth_services->PHCLogin($ch, $credentials);   
     1741            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    16751742            //initial request with login data
    1676             $response = curl_exec($ch); 
     1743            $response = curl_exec($ch);
    16771744            // send response as JSON
    1678             $response = json_decode($response, true); 
     1745            $response = json_decode($response, true);
    16791746            // get the temporary token and insert in credentials object
    16801747            $credentials->token = $response['result'][0]['token'];
     
    16891756                $this->logs->writeFileLog('listProducts', $response['messages'][0]['messageCodeLocale']);
    16901757                unset($_SESSION['username']);
    1691             } else { 
    1692                                
     1758            } else {
     1759
    16931760                // Get condition of Tax Tab from Woocommerce -> Configuration -> Tax
    16941761                $woocommerce_calc_taxes = get_option('woocommerce_calc_taxes');
     
    17101777                        break;
    17111778                }
    1712                
     1779
    17131780                //Obtain gama of PHC
    17141781                $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     
    17251792                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    17261793                }
    1727                
     1794
    17281795                //Obtain parameter of manage stock
    17291796                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);
    17301797
    17311798                //$this->logs->writeFileLog('ListProducts FrontEnd:', $response);
    1732                
     1799
    17331800                if (curl_error($ch)) {
    17341801                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
     
    17381805                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    17391806                } else {
    1740                     foreach ($response['result'] as $key => $value){ 
     1807                    foreach ($response['result'] as $key => $value){
    17411808                        if($response['result'][$key]['descricao'] === 'AllowStocks'){
    17421809                            $_SESSION['manageStockParameter'] = $response['result'][$key]['valor'];
     
    17441811                    }
    17451812                }
    1746                
     1813
    17471814                if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
    17481815
    17491816                    // Products with VAT included in price
    1750                     if(($woocommerce_calc_taxes == "no") || ($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == "yes")) {   
     1817                    if(($woocommerce_calc_taxes == "no") || ($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == "yes")) {
    17511818
    17521819                        if ($settings['backend']['positiveStock'] == 'on'){
    17531820                            $response = $this->utils_services->paramsQuery5($ch, $credentials, 'St', '2', 'stock', '0', '0', $columnIva, '1');
    17541821                        } else {
    1755                             $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '1'); 
    1756                         }                   
    1757                        
     1822                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '1');
     1823                        }
     1824
    17581825                        //$this->logs->writeFileLog('StList response1:', $response);
    17591826
     
    17651832                            $response = $this->utils_services->paramsQuery5($ch, $credentials, 'St', '2', 'stock', '0', '0', $columnIva, '0');
    17661833                        } else {
    1767                             $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '0'); 
    1768                         }
    1769                          
    1770                         //$this->logs->writeFileLog('StList response2:', $response);       
    1771                        
     1834                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '0');
     1835                        }
     1836
     1837                        //$this->logs->writeFileLog('StList response2:', $response);
     1838
    17721839                    }
    17731840                } else {
    17741841                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'St');
    1775                 }       
    1776                
     1842                }
     1843
    17771844
    17781845                if (curl_error($ch)) {
    17791846                    $this->logs->writeFileLog('listProducts2', $ch);
    17801847                } else if(empty($response)){
    1781                     $this->logs->writeFileLog('listProducts2', 'EMPTY RESPONSE');       
     1848                    $this->logs->writeFileLog('listProducts2', 'EMPTY RESPONSE');
    17821849                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1783                     $this->logs->writeFileLog('listProducts2', $response['messages'][0]['messageCodeLocale']);       
    1784                 } else {   
     1850                    $this->logs->writeFileLog('listProducts2', $response['messages'][0]['messageCodeLocale']);
     1851                } else {
    17851852
    17861853                    foreach ($response['result'] as $key => $value){
     
    17911858                        if ($settings['backend']['filterStock'] == 'on'){
    17921859                            // Get all the stock (entries)
    1793                             $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $value['ref'], 'entrada', '1');   
    1794                                                                
     1860                            $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $value['ref'], 'entrada', '1');
     1861
    17951862                            $totalStock = array_reduce(
    17961863                                $responseFilter['result'],
     
    17991866                                },
    18001867                                0
    1801                             );     
    1802                            
     1868                            );
     1869
    18031870                            if ($settings['backend']['positiveStock'] == 'on'){
    1804                                 //Extract the customer ordrers from total stock 
     1871                                //Extract the customer ordrers from total stock
    18051872                                if ($totalStock - $value['qttcli'] > 0){
    1806                                     $arrayRef[$value['ref']] = $totalStock - $value['qttcli']; 
    1807                                 }       
     1873                                    $arrayRef[$value['ref']] = $totalStock - $value['qttcli'];
     1874                                }
    18081875                            } else {
    1809                                 $arrayRef[$value['ref']] = $totalStock - $value['qttcli']; 
    1810                             }                                               
     1876                                $arrayRef[$value['ref']] = $totalStock - $value['qttcli'];
     1877                            }
    18111878                        } else{
    18121879                            $arrayRef[$value['ref']] = $value['stock'];
    1813                         }                       
     1880                        }
    18141881                        $refArray .= '{
    18151882                                        "comparison":0,
     
    18201887                                        "skipCheckType":false,
    18211888                                        "type":"Number"
    1822                                       }';   
    1823                     }       
    1824        
    1825                     $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);                   
    1826                    
     1889                                      }';
     1890                    }
     1891
     1892                    $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);
     1893
    18271894                    //$this->logs->writeFileLog('StList response:', $response);
    18281895
     
    18301897                        $this->logs->writeFileLog('listProducts3', $ch);
    18311898                    } else if(empty($response)){
    1832                         $this->logs->writeFileLog('listProducts3', 'EMPTY RESPONSE');             
     1899                        $this->logs->writeFileLog('listProducts3', 'EMPTY RESPONSE');
    18331900                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1834                         $this->logs->writeFileLog('listProducts3', $response['messages'][0]['messageCodeLocale']);               
     1901                        $this->logs->writeFileLog('listProducts3', $response['messages'][0]['messageCodeLocale']);
    18351902                    } else {
    1836                        
     1903
    18371904                        //Create rows with information of products
    18381905                        $tableProducts = '';
    1839                         $tableProducts .= "<thead><tr><th style='text-align: left;'><input type='checkbox' onClick='toggle(this)'/> Select all</th><th style='text-align: left;'>Ref</th><th style='text-align: left;'>Product Name</th><th style='text-align: left;'>Family</th>";         
     1906                        $tableProducts .= "<thead><tr><th style='text-align: left;'><input type='checkbox' onClick='toggle(this)'/> Select all</th><th style='text-align: left;'>Ref</th><th style='text-align: left;'>Product Name</th><th style='text-align: left;'>Family</th>";
    18401907
    18411908                        if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){
     
    18441911                            $tableProducts .= "</tr></thead>";
    18451912                        }
    1846                        
     1913
    18471914                        if(is_array($response['result'])){
    18481915                            if(!empty($settings['backend']['productPriceColumn']) && $settings['backend']['productPriceColumn'] != 'epv0'){
    18491916                                foreach ($response['result'] as $key => $value) {
    18501917
    1851                                     //Create Table                                     
     1918                                    //Create Table
    18521919                                    $tableProducts .= "<tr>";
    18531920                                    if(wc_get_product_id_by_sku( $response['result'][$key]['ref'] )== ""){
     
    18611928                                    }
    18621929
    1863                                     $tableProducts .= "<td style='text-align: left;'>". $response['result'][$key]['ref'].   
     1930                                    $tableProducts .= "<td style='text-align: left;'>". $response['result'][$key]['ref'].
    18641931                                                        "</td><td style='text-align: left;'>". $response['result'][$key]['design'].
    18651932                                                        "</td><td style='text-align: left;'>". $response['result'][$key]['familia']."</td>";
    1866                                    
     1933
    18671934                                    //Only exists stocks after Star GAMA
    18681935                                    if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){
     
    18721939                                            $tableProducts .= "<td style='text-align: right;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    18731940                                        }
    1874                                     }                           
     1941                                    }
    18751942                                }
    18761943                                echo $tableProducts;
    18771944                            } else {
    18781945                                $this->logs->writeFileLog('listProducts4', 'Products: Empty productPriceColumn');
    1879                             } 
    1880                         } 
    1881                     }
    1882                 }
    1883             }   
     1946                            }
     1947                        }
     1948                    }
     1949                }
     1950            }
    18841951            //Logout
    18851952            $this->auth_services->PHCLogout($ch, $credentials);
     
    18931960                $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    18941961                // get Credentials
    1895                 $credentials = $this->syncro_services->fetchCredentials();             
     1962                $credentials = $this->syncro_services->fetchCredentials();
    18961963                // Obtain configuration to make login
    18971964                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    18981965                //initial request with login data
    1899                 $response = curl_exec($ch);     
     1966                $response = curl_exec($ch);
    19001967                // send response as JSON
    1901                 $response = json_decode($response, true); 
     1968                $response = json_decode($response, true);
    19021969                // get the temporary token and insert in credentials object
    19031970                $credentials->token = $response['result'][0]['token'];
    1904                
    1905                 //$this->logs->writeFileLog('SaveProducts Login:', $response); 
     1971
     1972                //$this->logs->writeFileLog('SaveProducts Login:', $response);
    19061973
    19071974                if (curl_error($ch)) {
     
    19141981                    $this->logs->writeFileLog('saveProducts', $response['messages'][0]['messageCodeLocale']);
    19151982                    unset($_SESSION['username']);
    1916                 } else { 
    1917                    
     1983                } else {
     1984
    19181985                    //Obtain gama of PHC
    19191986                    $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     
    19301997                        $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    19311998                    }
    1932                    
     1999
    19332000                    //Verify GAMA or value choose in warehouse dropdown
    19342001                    if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
     
    19362003                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '2', 'stock', '0');
    19372004                        } else {
    1938                             $response = $this->utils_services->entityName_Query($ch, $credentials, 'St'); 
     2005                            $response = $this->utils_services->entityName_Query($ch, $credentials, 'St');
    19392006                        }
    19402007                    } else {
    19412008                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Sa', 'armazem', $settings['backend']['warehouse']);
    19422009                    }
    1943                    
     2010
    19442011                    //$this->logs->writeFileLog('SaveProducts St ou Sa:', $response);
    19452012
     
    19472014                        $this->logs->writeFileLog('saveProducts2', $ch);
    19482015                    } else if(empty($response)){
    1949                         $this->logs->writeFileLog('saveProducts2', 'EMPTY RESPONSE');         
     2016                        $this->logs->writeFileLog('saveProducts2', 'EMPTY RESPONSE');
    19502017                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1951                         $this->logs->writeFileLog('saveProducts2', $response['messages'][0]['messageCodeLocale']);         
     2018                        $this->logs->writeFileLog('saveProducts2', $response['messages'][0]['messageCodeLocale']);
    19522019                    } else {
    19532020                        $i = 0;
     
    19642031                                            }
    19652032                                            $arrayRef[$value] = $response['result'][$i]['stock'];
    1966                                
     2033
    19672034                                            $refArray .= '{
    19682035                                                            "comparison":0,
     
    19732040                                                            "skipCheckType":false,
    19742041                                                            "type":"Number"
    1975                                                           }';                                                             
    1976                                         } 
     2042                                                          }';
     2043                                        }
    19772044                                    }
    19782045                                }
     
    19822049
    19832050                        //Obtain products from st
    1984                         $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);   
    1985                
    1986                         //$this->logs->writeFileLog('SaveList St:', $response); 
     2051                        $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);
     2052
     2053                        //$this->logs->writeFileLog('SaveList St:', $response);
    19872054
    19882055                        if (curl_error($ch)) {
    19892056                            $this->logs->writeFileLog('saveProducts3', $ch);
    19902057                        } else if(empty($response)){
    1991                             $this->logs->writeFileLog('saveProducts3', 'EMPTY RESPONSE');           
     2058                            $this->logs->writeFileLog('saveProducts3', 'EMPTY RESPONSE');
    19922059                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1993                             $this->logs->writeFileLog('saveProducts3', $response['messages'][0]['messageCodeLocale']);           
     2060                            $this->logs->writeFileLog('saveProducts3', $response['messages'][0]['messageCodeLocale']);
    19942061                        } else {
    1995                             //If exists selected products 
     2062                            //If exists selected products
    19962063                            if(is_array($refs)){
    19972064                                $i = 0;
    19982065                                $count = count($response['result']);
    1999                            
     2066
    20002067                                while ($i < $count) {
    20012068                                    foreach ($refs as $key => $value) {
     
    20032070                                            //Obtain url of image to save in shop
    20042071                                            $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    2005                                             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html'); 
     2072                                            $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    20062073                                            $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    2007                                            
     2074
    20082075                                            $thumb_url = '';
    2009                                        
    2010                                            
     2076
     2077
    20112078                                            //Add Product
    2012                                             $this->addProduct($response['result'][$i]['design'], 
    2013                                                             $response['result'][$i]['design'], 
    2014                                                             $response['result'][$i]['desctec'], 
    2015                                                             $response['result'][$i]['design'], 
    2016                                                             $arrayRef[$response['result'][$i]['ref']], 
     2079                                            $this->addProduct($response['result'][$i]['design'],
     2080                                                            $response['result'][$i]['design'],
     2081                                                            $response['result'][$i]['desctec'],
     2082                                                            $response['result'][$i]['design'],
     2083                                                            $arrayRef[$response['result'][$i]['ref']],
    20172084                                                            $response['result'][$i][$settings['backend']['productPriceColumn']],
    2018                                                             $response['result'][$i]['ref'],   
     2085                                                            $response['result'][$i]['ref'],
    20192086                                                            'yes',
    2020                                                             'visible', 
     2087                                                            'visible',
    20212088                                                            $thumb_url);
    20222089                                        }
    20232090                                    }
    20242091                                    ++$i;
    2025                                 } 
    2026                             }   
    2027                         }     
     2092                                }
     2093                            }
     2094                        }
    20282095                    }
    20292096                }
     
    20332100            } else {
    20342101                echo "empty_refs";
    2035             }   
     2102            }
    20362103        }
    20372104
     
    20412108                $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    20422109                // get Credentials
    2043                 $credentials = $this->syncro_services->fetchCredentials();         
     2110                $credentials = $this->syncro_services->fetchCredentials();
    20442111                // Obtain configuration to make login
    2045                 $ch = $this->auth_services->PHCLogin($ch, $credentials);     
     2112                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    20462113                //initial request with login data
    2047                 $response = curl_exec($ch);     
     2114                $response = curl_exec($ch);
    20482115                // send response as JSON
    2049                 $response = json_decode($response, true); 
     2116                $response = json_decode($response, true);
    20502117                // get the temporary token and insert in credentials object
    20512118                $credentials->token = $response['result'][0]['token'];
     
    20622129                    $this->logs->writeFileLog('updateStocksProducts', $response['messages'][0]['messageCodeLocale']);
    20632130                    unset($_SESSION['username']);
    2064                 } else { 
    2065                    
     2131                } else {
     2132
    20662133                     //Obtain gama of PHC
    20672134                     $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     
    20782145                        $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    20792146                    }
    2080                    
     2147
    20812148                    //Verify GAMA or value choose in warehouse dropdown
    20822149                    if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
     
    20872154                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Sa', 'armazem', $settings['backend']['warehouse']);
    20882155                    }
    2089                    
     2156
    20902157                    if (curl_error($ch)) {
    20912158                        $this->logs->writeFileLog('updateStocksProducts2', $ch);
    20922159                    } else if(empty($response)){
    2093                         $this->logs->writeFileLog('updateStocksProducts2', 'EMPTY RESPONSE');       
     2160                        $this->logs->writeFileLog('updateStocksProducts2', 'EMPTY RESPONSE');
    20942161                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2095                         $this->logs->writeFileLog('updateStocksProducts2', $response['messages'][0]['messageCodeLocale']);       
     2162                        $this->logs->writeFileLog('updateStocksProducts2', $response['messages'][0]['messageCodeLocale']);
    20962163                    } else {
    2097                        
    2098                         $count = count($response['result']);                   
     2164
     2165                        $count = count($response['result']);
    20992166                        $refArray = array();
    21002167                        $i=0;
    21012168                        while ($i < $count) {
    2102                             foreach ($response['result'][$i] as $key => $value){       
     2169                            foreach ($response['result'][$i] as $key => $value){
    21032170                                $refArray[$i]=array();
    21042171                                // filter stock - uninvoiced order
    21052172                                if ($settings['backend']['filterStock'] == 'on'){
    21062173                                    // Get all the stock (entries)
    2107                                     $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $response['result'][$i]['ref'], 'entrada', '1'); 
    2108                                                                        
     2174                                    $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $response['result'][$i]['ref'], 'entrada', '1');
     2175
    21092176                                    $totalStock = array_reduce(
    21102177                                        $responseFilter['result'],
     
    21132180                                        },
    21142181                                        0
    2115                                     );                                                 
    2116                                     //Extract the customer ordrers from total stock             
     2182                                    );
     2183                                    //Extract the customer ordrers from total stock
    21172184                                    $arrayRef[$value] = $totalStock - $response['result'][$i]['qttcli'];
    21182185
    21192186                                } else {
    21202187                                    $refArray[$i]['stock'] = $response['result'][$i]['stock'];
    2121                                 }                                                                                               
    2122                                 $refArray[$i]['sku'] = $response['result'][$i]['ref'];         
     2188                                }
     2189                                $refArray[$i]['sku'] = $response['result'][$i]['ref'];
    21232190                            }
    21242191                            ++$i;
    2125                         }                       
    2126                         //If exists selected products                   
    2127                             foreach ($refArray as $prod) {           
     2192                        }
     2193                           //If exists selected products
     2194                            foreach ($refArray as $prod) {
    21282195                                //Obtain post_id of postmeta table
    21292196                                $productID = wc_get_product_id_by_sku($prod['sku']);
    2130                                
     2197
    21312198                                //Obtain products
    21322199                                if(!empty($productID)){
    2133                                         if($settings['backend']['manageStock'] == 'on'){                                       
    2134                                             update_post_meta($productID,'_stock',$prod['stock']);   
    2135                      
     2200                                        if($settings['backend']['manageStock'] == 'on'){
     2201                                            update_post_meta($productID,'_stock',$prod['stock']);
     2202
    21362203                                            if($prod['stock'] > 0){
    21372204                                                update_post_meta( $productID, '_stock_status', 'instock');
    2138                                            
     2205
    21392206                                            } else {
    21402207                                                //update_post_meta( $productID, '_stock_status', 'outofstock');
    21412208                                            }
    2142                                         }   
     2209                                        }
    21432210                                    }
    2144                                
    2145                                
    2146                             } 
    2147                                
    2148                            
     2211
     2212
     2213                            }
     2214
     2215
    21492216                    }
    21502217                }
     
    21542221            } else {
    21552222                echo "empty_refs";
    2156             } 
    2157         }
    2158 
    2159         //Update all field of products
    2160         public function updateAllFieldsProducts($refs){
    2161             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME); 
    2162             //If exists selected products 
    2163             if(is_array($refs)){           
     2223            }
     2224        }
     2225
     2226        //Update only prices of products
     2227        public function updatePricesProducts($refs){
     2228            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     2229            //If exists selected products
     2230            if(is_array($refs)){
    21642231                // get Credentials
    2165                 $credentials = $this->syncro_services->fetchCredentials();             
     2232                $credentials = $this->syncro_services->fetchCredentials();
    21662233                // Obtain configuration to make login
    21672234                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    21682235                //initial request with login data
    2169                 $response = curl_exec($ch);     
     2236                $response = curl_exec($ch);
    21702237                // send response as JSON
    2171                 $response = json_decode($response, true); 
     2238                $response = json_decode($response, true);
    21722239                // get the temporary token and insert in credentials object
    21732240                $credentials->token = $response['result'][0]['token'];
    2174    
     2241
    21752242                //$this->logs->writeFileLog('Login response:', $response);
    2176    
     2243
     2244                if (curl_error($ch)) {
     2245                    $this->logs->writeFileLog('updatePricesProducts', $ch);
     2246                    unset($_SESSION['username']);
     2247                } else if(empty($response)){
     2248                    $this->logs->writeFileLog('updatePricesProducts', 'EMPTY RESPONSE');
     2249                    unset($_SESSION['username']);
     2250                } else if(isset($response['messages'][0]['messageCodeLocale'])){
     2251                    $this->logs->writeFileLog('updatePricesProducts', $response['messages'][0]['messageCodeLocale']);
     2252                    unset($_SESSION['username']);
     2253                } else {
     2254                    $values_touse = array();
     2255                    $i=0;
     2256
     2257                    foreach ($refs as $key => $value) {
     2258                            if($i > 0){
     2259                                                $refArray .= ",";
     2260                                            }
     2261                                    $refArray .= '{
     2262                                                    "comparison":0,
     2263                                                    "filterItem":"ref",
     2264                                                    "valueItem":"'.$value.'",
     2265                                                    "groupItem":9,
     2266                                                    "checkNull":false,
     2267                                                    "skipCheckType":false,
     2268                                                    "type":"Number"
     2269                                                  }';
     2270                        $i++;
     2271                    }
     2272
     2273                    $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);
     2274
     2275                    //$this->logs->writeFileLog('StList response:', $response);
     2276
     2277                    if (curl_error($ch)) {
     2278                        $this->logs->writeFileLog('updatePricesProducts2', $ch);
     2279                    } else if(empty($response)){
     2280                        $this->logs->writeFileLog('updatePricesProducts2', 'EMPTY RESPONSE');
     2281                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
     2282                        $this->logs->writeFileLog('updatePricesProducts2', $response['messages'][0]['messageCodeLocale']);
     2283                    } else {
     2284
     2285                        for($i=0;$i<sizeof($response['result']);$i++){
     2286                            $values_touse[$response['result'][$i]['ref']]=array();
     2287                            $values_touse[$response['result'][$i]['ref']][$settings['backend']['productPriceColumn']]=$response['result'][$i][$settings['backend']['productPriceColumn']];
     2288                        }
     2289
     2290                        //Update all prices in Woocommerce
     2291                        foreach($values_touse as $key => $values){
     2292                            $productID = wc_get_product_id_by_sku($key);
     2293                            update_post_meta( $productID, '_price', $values[$settings['backend']['productPriceColumn']] );
     2294                            update_post_meta( $productID, '_regular_price', $values[$settings['backend']['productPriceColumn']]);
     2295                        }
     2296                    }
     2297                }
     2298                //Logout
     2299                $this->auth_services->PHCLogout($ch, $credentials);
     2300            } else {
     2301                echo "empty_refs";
     2302            }
     2303        }
     2304
     2305        //Update all field of products
     2306        public function updateAllFieldsProducts($refs){
     2307            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     2308            //If exists selected products
     2309            if(is_array($refs)){
     2310                // get Credentials
     2311                $credentials = $this->syncro_services->fetchCredentials();
     2312                // Obtain configuration to make login
     2313                $ch = $this->auth_services->PHCLogin($ch, $credentials);
     2314                //initial request with login data
     2315                $response = curl_exec($ch);
     2316                // send response as JSON
     2317                $response = json_decode($response, true);
     2318                // get the temporary token and insert in credentials object
     2319                $credentials->token = $response['result'][0]['token'];
     2320
     2321                //$this->logs->writeFileLog('Login response:', $response);
     2322
    21772323                if (curl_error($ch)) {
    21782324                    $this->logs->writeFileLog('updateAllFieldsProducts', $ch);
     
    21842330                    $this->logs->writeFileLog('updateAllFieldsProducts', $response['messages'][0]['messageCodeLocale']);
    21852331                    unset($_SESSION['username']);
    2186                 } else { 
    2187                
     2332                } else {
     2333
    21882334                     //Obtain gama of PHC
    21892335                     $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     
    21912337                     //$this->logs->writeFileLog('Get Gama:', $response);
    21922338
    2193                     if (curl_error($ch)) { 
     2339                    if (curl_error($ch)) {
    21942340                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    21952341                    } else if(empty($response)){
     
    22012347                        $values_touse = array();
    22022348                        $i=0;
    2203                        
    2204                    
    2205                         foreach ($refs as $key => $value) {     
     2349
     2350
     2351                        foreach ($refs as $key => $value) {
    22062352                                if($i > 0){
    22072353                                                    $refArray .= ",";
     
    22152361                                                                "skipCheckType":false,
    22162362                                                                "type":"Number"
    2217                                                               }';                                                             
     2363                                                              }';
    22182364                            $i++;
    2219                         } 
    2220                    
    2221                         $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);   
    2222                        
     2365                        }
     2366
     2367                        $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);
     2368
    22232369                        //$this->logs->writeFileLog('StList response:', $response);
    2224                        
     2370
    22252371                        if (curl_error($ch)) {
    22262372                            $this->logs->writeFileLog('updateAllFieldsProducts2', $ch);
    22272373                        } else if(empty($response)){
    2228                             $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
     2374                            $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');
    22292375                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2230                             $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
     2376                            $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);
    22312377                        } else {
    22322378                            for($i=0;$i<sizeof($response['result']);$i++){
     
    22362382                                    $values_touse[$response['result'][$i]['ref']]['design'] = $response['result'][$i]['design'];
    22372383                            }
    2238                            
    2239                        
     2384
     2385
    22402386                            if( $settings['backend']['warehouse'] != -1 && $settings['backend']['warehouse'] != ''){
    2241                                
     2387
    22422388                                $refArray  = '{
    22432389                                                                    "comparison":0,
     
    22492395                                                                    "type":"Number"
    22502396                                                                  },';
    2251                                                                  
    2252                                      foreach ($refs as $key => $value) {     
    2253                                    
     2397
     2398                                     foreach ($refs as $key => $value) {
     2399
    22542400                                                $refArray .= '{
    22552401                                                                "comparison":0,
     
    22602406                                                                "skipCheckType":false,
    22612407                                                                "type":"Number"
    2262                                                               },';                                                             
    2263                                     } 
    2264                                    
     2408                                                              },';
     2409                                    }
     2410
    22652411                                        $refArray .='{
    22662412                                                                "comparison":0,
     
    22712417                                                                "skipCheckType":false,
    22722418                                                                "type":"Number"
    2273                                                               }'; 
    2274                                
    2275                                                          
    2276                                     $response = $this->utils_services->paramsQuery3($ch, $credentials, 'Sa', $refArray);   
    2277            
    2278                                     //$this->logs->writeFileLog('Update All Sa:', $refArray); 
     2419                                                              }';
     2420
     2421
     2422                                    $response = $this->utils_services->paramsQuery3($ch, $credentials, 'Sa', $refArray);
     2423
     2424                                    //$this->logs->writeFileLog('Update All Sa:', $refArray);
    22792425
    22802426                                    if (curl_error($ch)) {
    22812427                                        $this->logs->writeFileLog('updateAllFieldsProducts2', $ch);
    22822428                                    } else if(empty($response)){
    2283                                         $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
     2429                                        $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');
    22842430                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2285                                         $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
    2286                                     } else {             
     2431                                        $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);
     2432                                    } else {
    22872433                                            for($i=0;$i<sizeof($response['result']);$i++){
    2288                                            
     2434
    22892435                                                $values_touse[$response['result'][$i]['ref']]['stock']=$response['result'][$i]['stock'];
    2290                                             }       
     2436                                            }
    22912437                                    }
    22922438                                }else{
    22932439                                    for($i=0;$i<sizeof($response['result']);$i++){
    2294                                            
     2440
    22952441                                            $values_touse[$response['result'][$i]['ref']]['stock']=$response['result'][$i]['stock'];
    2296                                            
     2442
    22972443                                    }
    2298                                 }                               
    2299                         }
    2300                        
     2444                                }
     2445                        }
     2446
    23012447                        foreach($values_touse as $key => $values){
    23022448                                $productID = wc_get_product_id_by_sku($key);
    23032449                                update_post_meta($productID,'_stock',$values['stock']);
    2304                                
     2450
    23052451                                $my_post = array('ID'          => $productID,
    23062452                                                         'post_title'   => $values['design']
     
    23092455                                        wp_update_post( $my_post );
    23102456                                        update_post_meta( $productID, '_price', $values[$settings['backend']['productPriceColumn']] );
    2311                                         update_post_meta( $productID, '_regular_price', $values[$settings['backend']['productPriceColumn']]);   
    2312                                    
    2313                         }
    2314                    
    2315                    
    2316                     }           
     2457                                        update_post_meta( $productID, '_regular_price', $values[$settings['backend']['productPriceColumn']]);
     2458
     2459                        }
     2460
     2461
     2462                    }
    23172463                }
    23182464                //Logout
     
    23202466            } else {
    23212467                echo "empty_refs";
    2322             }   
     2468            }
    23232469        }
    23242470    }
  • drivefx-woocommerce/trunk/css/style_datatable.css

    r1487316 r2526532  
    22 * Table styles
    33 */
    4 table.dataTable {
     4 table.dataTable {
    55  width: 100%;
    66  margin: 0 auto;
     
    498498}
    499499
    500 #updateStocks, #updateAllFields {
     500#updateStocks, #updateStocks, #updatePrices, #updateAllFields {
    501501    margin-left: 10px;
    502502    cursor: pointer;
     
    554554    right: 0;
    555555}
    556 
    557 
    558 
  • drivefx-woocommerce/trunk/js/drivefx-woocommerce.js

    r2456862 r2526532  
    22
    33jQuery(document).ready(function() {
    4                
     4
    55    //Initialize plugin
    66    jQuery('#backend_url_initialize').click(function (){
    77        if(jQuery('#url').val() != ''){
    88            jQuery('#invalidBackendUrl').remove();
    9            
     9
    1010            var urlBackend = jQuery('#url').val();
    1111            urlBackend = urlBackend.replace(/html\/+$/g,"");
    1212            urlBackend = urlBackend.replace(/html+$/g,"");
    1313            urlBackend = urlBackend.replace(/\/+$/g,"");
    14            
     14
    1515            //Open popup
    16             window.open("https://sis05.drivefx.net/OAuthCallbackPHCGo/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=580,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
    17             //window.open("https://trial.phcfx.com/OauthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
    18             //window.open("http://sis.phc.pt/OauthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=580,resizable=no,toolbar=no,menubar=no,location=no,status=no");     
    19             //window.open("http://phc201412002/FX/OAuthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");     
     16            window.open("https://sis05.drivefx.net/OAuthCallbackPHCGo/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=580,resizable=no,toolbar=no,menubar=no,location=no,status=no");
    2017            return false;
    2118        } else {
     
    2421        }
    2522    });
    26    
     23
    2724    if(jQuery('#typeOfOrder').val() == 0){
    2825        jQuery('#statusOfOrder').parent('td').parent('tr').hide();
    2926    }
    30    
     27
    3128    jQuery('#updateStocks').hide();
    3229    jQuery('#saveProductInShop').hide();
    3330    jQuery('#updateStocks').hide();
     31    jQuery('#updatePrices').hide();
    3432    jQuery('#updateAllFields').hide();
    3533
     
    5149            action: 'woocommerce_fx',
    5250            method: 'statusOfOrder',
    53             selectItems: jQuery('#statusOfOrder').val(), 
    54             typeOfOrder: jQuery('#typeOfOrder').val() 
     51            selectItems: jQuery('#statusOfOrder').val(),
     52            typeOfOrder: jQuery('#typeOfOrder').val()
    5553        })
    5654        .done(function (data) {
     
    6462        })
    6563    });
    66    
     64
    6765    //Run to show list of products
    6866    jQuery('#importToShop').click(function (event){
     
    8987                });
    9088                jQuery('#updateStocks').show();
     89                jQuery('#updatePrices').show();
    9190                jQuery('#updateAllFields').show();
    9291                jQuery('#saveProductInShop').show();
     
    9897                jQuery('#loader').html('');
    9998                jQuery('#updateStocks').hide();
     99                jQuery('#updatePrices').hide();
    100100                jQuery('#updateAllFields').hide();
    101101                jQuery('#saveProductInShop').hide();
     
    116116        jQuery('#saveProductInShop').hide();
    117117        jQuery('#updateStocks').hide();
     118        jQuery('#updatePrices').hide();
    118119        jQuery('#updateAllFields').hide();
    119120
     
    129130        .done(function (data) {
    130131            jQuery('.alignleft #messageSuccess').html('');
    131            
     132
    132133            if(data.length != 0 && data != 'empty_refs'){
    133134                jQuery('.alignleft h2').before('<div id="messageSuccess"><div class="error"><p><strong>Please fill description of selected products to import them successfully: ' + data + ' </strong></p></div></div>');
    134135            }
    135            
     136
    136137            if(data != 'empty_refs'){
    137138                jQuery('.alignleft h2').before('<div id="messageSuccess"><div id="setting-error-settings_updated" class="updated settings-error"><p><strong>Import successfull</strong></p></div></div>');
    138139            }
    139            
     140
    140141            jQuery('#saveProductInShop').show();
    141142            jQuery('#updateStocks').show();
     143            jQuery('#updatePrices').show();
    142144            jQuery('#updateAllFields').show();
    143145            jQuery('#loader2').html('');
     
    161163                    });
    162164                    jQuery('#updateStocks').show();
     165                    jQuery('#updatePrices').show();
    163166                    jQuery('#updateAllFields').show();
    164167                    jQuery('#saveProductInShop').show();
     
    170173                    jQuery('#loader').html('');
    171174                    jQuery('#updateStocks').hide();
     175                    jQuery('#updatePrices').hide();
    172176                    jQuery('#updateAllFields').hide();
    173177                    jQuery('#saveProductInShop').hide();
     
    176180            })
    177181        })
    178     }); 
     182    });
    179183
    180184    //Update stocks of products presented in PHC GO
     
    189193        jQuery('#saveProductInShop').hide();
    190194        jQuery('#updateStocks').hide();
     195        jQuery('#updatePrices').hide();
    191196        jQuery('#updateAllFields').hide();
    192197
     
    202207        .done(function (data) {
    203208            jQuery('.alignleft #messageSuccess').html('');
    204            
     209
    205210            if(data != 'empty_refs'){
    206211                jQuery('.alignleft h2').before('<div id="messageSuccess"><div id="setting-error-settings_updated" class="updated settings-error"><p><strong>Update of selected products successfull</strong></p></div></div>');
    207212            }
    208            
     213
    209214            jQuery('#saveProductInShop').show();
    210215            jQuery('#updateStocks').show();
     216            jQuery('#updatePrices').show();
    211217            jQuery('#updateAllFields').show();
    212218            jQuery('#loader2').html('');
     
    230236                    });
    231237                    jQuery('#updateStocks').show();
     238                    jQuery('#updatePrices').show();
    232239                    jQuery('#updateAllFields').show();
    233240                    jQuery('#saveProductInShop').show();
     
    239246                    jQuery('#loader').html('');
    240247                    jQuery('#updateStocks').hide();
     248                    jQuery('#updatePrices').hide();
    241249                    jQuery('#updateAllFields').hide();
    242250                    jQuery('#saveProductInShop').hide();
     
    247255    });
    248256
    249     //Update all fields od products presented in PHC GO
    250     jQuery('#updateAllFields').click(function (event) {
     257    //Update prices of products presented in PHC GO
     258    jQuery('#updatePrices').click(function (event) {
    251259        //Update products
    252260        var arr = new Array();
     
    258266        jQuery('#saveProductInShop').hide();
    259267        jQuery('#updateStocks').hide();
     268        jQuery('#updatePrices').hide();
    260269        jQuery('#updateAllFields').hide();
    261270        // stop normal form submission handler
     
    264273        jQuery.post(url, {
    265274            action: 'woocommerce_fx',
    266             method: 'updateAllFieldsProducts',
     275            method: 'updatePricesProducts',
    267276            refs: arr
    268277        })
    269278        .done(function (data) {
    270279            jQuery('.alignleft #messageSuccess').html('');
    271                        
     280
    272281            if(data != 'empty_refs'){
    273282                jQuery('.alignleft h2').before('<div id="messageSuccess"><div id="setting-error-settings_updated" class="updated settings-error"><p><strong>Update of selected products successfull</strong></p></div></div>');
    274283            }
    275            
     284
    276285            jQuery('#saveProductInShop').show();
    277286            jQuery('#updateStocks').show();
     287            jQuery('#updatePrices').show();
    278288            jQuery('#updateAllFields').show();
    279289            jQuery('#loader2').html('');
     
    297307                    });
    298308                    jQuery('#updateStocks').show();
     309                    jQuery('#updatePrices').show();
    299310                    jQuery('#updateAllFields').show();
    300311                    jQuery('#saveProductInShop').show();
     
    306317                    jQuery('#loader').html('');
    307318                    jQuery('#updateStocks').hide();
     319                    jQuery('#updatePrices').hide();
     320                    jQuery('#updateAllFields').hide();
     321                    jQuery('#saveProductInShop').hide();
     322                }
     323                jQuery("#tableOfProducts_previous").after("&nbsp;&nbsp;&nbsp;&nbsp;");
     324            })
     325        })
     326    });
     327
     328    //Update all fields od products presented in PHC GO
     329    jQuery('#updateAllFields').click(function (event) {
     330        //Update products
     331        var arr = new Array();
     332        jQuery(".updateStockShop").each(function() {
     333          arr.push(jQuery(this).attr('id'));
     334        });
     335
     336        jQuery('#loader2').html('<img style="margin-top: 10px; margin-left: 20px;" src="'+pathPlugin+'images/ajax-loader.gif" title="Loading..">');
     337        jQuery('#saveProductInShop').hide();
     338        jQuery('#updateStocks').hide();
     339        jQuery('#updatePrices').hide();
     340        jQuery('#updateAllFields').hide();
     341        // stop normal form submission handler
     342        event.preventDefault();
     343        //save products in MySQL
     344        jQuery.post(url, {
     345            action: 'woocommerce_fx',
     346            method: 'updateAllFieldsProducts',
     347            refs: arr
     348        })
     349        .done(function (data) {
     350            jQuery('.alignleft #messageSuccess').html('');
     351
     352            if(data != 'empty_refs'){
     353                jQuery('.alignleft h2').before('<div id="messageSuccess"><div id="setting-error-settings_updated" class="updated settings-error"><p><strong>Update of selected products successfull</strong></p></div></div>');
     354            }
     355
     356            jQuery('#saveProductInShop').show();
     357            jQuery('#updateStocks').show();
     358            jQuery('#updatePrices').show();
     359            jQuery('#updateAllFields').show();
     360            jQuery('#loader2').html('');
     361
     362            //Refresh of list of products
     363            jQuery.post(url, {
     364                action: 'woocommerce_fx',
     365                method: 'listOfProducts'
     366            })
     367            .done(function (data) {
     368                jQuery("#tableOfProducts").html("");
     369                jQuery('#tableOfProducts').append(data);
     370                try{
     371                    jQuery('#tableOfProducts').DataTable({
     372                           "iDisplayLength": 10,
     373                           "bDestroy":true,
     374                           "aoColumnDefs": [{
     375                                'bSortable': false,
     376                                'aTargets': [ 0 ]
     377                            }]
     378                    });
     379                    jQuery('#updateStocks').show();
     380                    jQuery('#updatePrices').show();
     381                    jQuery('#updateAllFields').show();
     382                    jQuery('#saveProductInShop').show();
     383                    jQuery('#importToShop').show();
     384                    jQuery('#loader').html('');
     385                } catch(err) {
     386                    jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in PHC GO".</p></b></div>');
     387                    jQuery('#importToShop').show();
     388                    jQuery('#loader').html('');
     389                    jQuery('#updateStocks').hide();
     390                    jQuery('#updatePrices').hide();
    308391                    jQuery('#updateAllFields').hide();
    309392                    jQuery('#saveProductInShop').hide();
     
    329412    });
    330413
     414    //Update Tax-Exempt param
     415    if(jQuery('#createExemptPT')[0].checked == true){
     416        jQuery('#createExemptEU')[0].checked = false;
     417        jQuery('#createExemptEU').css('pointer-events', 'none');
     418    }
     419        jQuery('#createExemptPT').click(function (event){
     420        if(jQuery('#createExemptPT')[0].checked == true){
     421            jQuery('#createExemptEU')[0].checked = false;
     422            jQuery('#createExemptEU').css('pointer-events', 'none');
     423        } else{
     424            jQuery('#createExemptEU')[0].checked = false;
     425            jQuery('#createExemptEU').css('pointer-events', 'auto');
     426        }
     427    });
     428    if(jQuery('#createExemptEU')[0].checked == true){
     429        jQuery('#createExemptPT')[0].checked = false;
     430        jQuery('#createExemptPT').css('pointer-events', 'none');
     431    }
     432        jQuery('#createExemptEU').click(function (event){
     433        if(jQuery('#createExemptEU')[0].checked == true){
     434            jQuery('#createExemptPT')[0].checked = false;
     435            jQuery('#createExemptPT').css('pointer-events', 'none');
     436        } else{
     437            jQuery('#createExemptPT')[0].checked = false;
     438            jQuery('#createExemptPT').css('pointer-events', 'auto');
     439        }
     440    });
     441
    331442});
    332443
  • drivefx-woocommerce/trunk/settings/backend.php

    r2456862 r2526532  
    44
    55    global $wpdb;
    6    
    7     $table_name = $wpdb->prefix."postmeta"; 
     6
     7    $table_name = $wpdb->prefix."postmeta";
    88    $query = "SELECT meta_value FROM %s WHERE meta_key = %s";
    99    $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, '_token')));
     
    2121    ?><p>Provide the info bellow so that the plugin can talk to your PHC Software backend installation.<br>
    2222    <?php echo implode(', ', $required) ?> are required to be setup!</p>
    23    
    24     <div id="box"> 
     23
     24    <div id="box">
    2525      <div id="cab">
    2626      Initialize Plugin Settings
    2727    </div>
    2828    <table class="form-table">
    29       <tbody> 
     29      <tbody>
    3030        <tr>
    3131          <th scope="row">
     
    3333          </th>
    3434          <td>
    35             <?php 
    36               if(is_array($settings['backend']['url'])){ 
     35            <?php
     36              if(is_array($settings['backend']['url'])){
    3737                $settings['backend']['url'] = '';
    3838              } ?>
    3939            <input class="regular-text" id="url" type="text" name="drivefx-woocommerce[backend][url]" value="<?php echo $settings['backend']['url'] ?>">
    40            
     40
    4141              <?php if($resultDB->meta_value != ''){ ?>
    4242                <div id="backend_url_initialize" class="button button-primary" title="Autenticate plugin">
    43                   <img id="plus" src="<?php echo plugins_url('/../images/plus.png', __FILE__) ?>" title="Autenticate plugin"> 
     43                  <img id="plus" src="<?php echo plugins_url('/../images/plus.png', __FILE__) ?>" title="Autenticate plugin">
    4444                  <span id="autenticatePlugin">Re-Autenticate</span>
    4545                </div>
    46                
     46
    4747              <?php } else if($settings['backend']['url'] == '' && $resultDB->meta_value == '') { ?>
    4848
    4949              <?php } else { ?>
    5050                <div id="backend_url_initialize" class="button button-primary" title="Autenticate plugin">
    51                   <img id="plus" src="<?php echo plugins_url('/../images/plus.png', __FILE__) ?>" title="Autenticate plugin"> 
     51                  <img id="plus" src="<?php echo plugins_url('/../images/plus.png', __FILE__) ?>" title="Autenticate plugin">
    5252                  <span id="autenticatePlugin">Autenticate</span>
    5353                </div>
    5454              <?php } ?>
    55            
     55
    5656            <p class="description">The URL of your PHC application.<br>Something like, e.g. https://sisXX.phcgo.net/XPTO/</p>
    5757          </td>
     
    5959      </tbody>
    6060    </table>
    61    </div><?php 
     61   </div><?php
    6262
    6363  foreach ($this->options['backend'] as $id => $opts):
    64  
     64
    6565    $name  = sprintf(DRIVEFXWOOCOMMERCE_PLUGIN_NAME.'[backend][%s]', $id);
    6666    $value = isset($settings['backend'][$id]) ? $settings['backend'][$id] : null;
     
    7575      switch ($id) {
    7676        case 'username':
    77           ?><div id="box"> 
     77          ?><div id="box">
    7878              <div id="cab">
    7979                Backend Settings
    8080              </div>
    8181              <table class="form-table">
    82                 <tbody> 
     82                <tbody>
    8383                  <tr>
    8484                    <th scope="row">
     
    102102              <p class="description"><?php echo $opts['descr'] ?></p>
    103103              </td>
    104             </tr>   
     104            </tr>
    105105            <?php break;
    106106        case 'dbname':
     
    113113              <p class="description"><?php echo $opts['descr'] ?></p>
    114114            </td>
    115           </tr>   
     115          </tr>
    116116          <?php break;
    117117
     
    119119          ?></tbody>
    120120          </table>
    121           </div> <?php 
     121          </div> <?php
    122122          if($_SESSION['username'] != ''){ ?>
    123            
     123
    124124            <div id="box">
    125125                <div id="cab">
     
    127127                </div>
    128128                <table class="form-table">
    129                   <tbody> 
     129                  <tbody>
    130130                    <tr>
    131131                      <th scope="row">
     
    149149          <?php } break;
    150150        case 'sendInvoice':
    151           if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
    152          
     151          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     152
    153153          <tr>
    154154            <th scope="row">
     
    169169        // Text for email body
    170170        case 'emailBody':
    171           if($settings['backend']['createInvoice'] != '' && $settings['backend']['sendInvoice'] != ''){ ?> 
     171          if($settings['backend']['createInvoice'] != '' && $settings['backend']['sendInvoice'] != ''){ ?>
    172172          <tr>
    173173            <th scope="row">
     
    178178              <p class="description"><?php echo $opts['descr'] ?></p>
    179179            </td>
    180           </tr>   
     180          </tr>
    181181          <?php } break;
    182182        // Type of Invoice
    183183        case 'typeOfInvoice':
    184           if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     184          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    185185          <tr>
    186186            <th scope="row">
     
    188188            </th>
    189189            <td>
    190               <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     190              <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    191191              <?php if(!empty($_SESSION[$id])){ ?>
    192192                <option value="0">Select one...</option>
    193               <?php } 
     193              <?php }
    194194              echo $_SESSION[$id]; ?>
    195195            </td>
    196196          </tr>
    197           <?php } break;         
     197          <?php } break;
    198198        case 'toSignInvoice':
    199               if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     199              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    200200              <tr>
    201201                <th scope="row">
     
    217217
    218218        case 'fieldNif':
    219               if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     219              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    220220              <tr>
    221221                <th scope="row">
     
    223223                </th>
    224224                <td>
    225             <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     225            <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    226226            <?php echo $_SESSION[$id];?>
    227            
     227
    228228                </td>
    229229              </tr>
     
    231231
    232232        case 'includeTaxonSendCost':
    233           if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     233          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    234234          <tr>
    235235            <th scope="row">
     
    237237            </th>
    238238            <td>
    239           <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     239          <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    240240          <?php echo $_SESSION[$id];?>
    241241          </select>
     
    243243          </tr>
    244244           <?php } break;
    245       //Customer free-tax
    246         case 'createExemptCl':
     245        //Customer from outside Portugal as free-tax
     246        case 'createExemptPT':
    247247          ?></tbody>
    248248          </table>
    249           </div><?php 
     249          </div><?php
    250250          if($_SESSION['username'] != ''){ ?>
    251251            <div id="box">
    252252                <div id="cab">
    253                 Tax-exempt customers Settings
     253                Tax-Exempt Settings
    254254                </div>
    255255                <table class="form-table">
    256                   <tbody> 
     256                  <tbody>
    257257                  <tr>
    258258                      <th scope="row">
    259259                        <?php if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '') { ?>
    260                             <label for="<?php echo $id ?>">Create tax-exempt customers?</label>
     260                            <label for="<?php echo $id ?>">From outside PT</label>
    261261                        <?php } ?>
    262262                      </th>
     
    273273                    </tr>
    274274              <?php } break;
    275               //The reason for the tax exemption.
     275              //The reason for the tax exemption PT.
    276276               case 'typeOfReason':
    277                 if($_SESSION['username'] != ''  && $settings['backend']['createInvoice'] != '' && $settings['backend']['createExemptCl'] != ''){ ?>
     277                if($_SESSION['username'] != ''  && $settings['backend']['createInvoice'] != '' && $settings['backend']['createExemptPT'] != ''){ ?>
    278278                    <tr>
    279279                    <th scope="row">
     
    281281                    </th>
    282282                    <td>
    283                       <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     283                      <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    284284                      <?php if(!empty($_SESSION[$id])){ ?>
    285285                        <option value="0">Select one...</option>
    286                       <?php } 
     286                      <?php }
    287287                      echo $_SESSION[$id]; ?>
    288288                    </td>
    289289                  </tr>
    290290                  <?php } break;
    291 
    292           case 'warehouseOrder':       
     291              //Customer from outside EU as free-tax
     292              case 'createExemptEU':
     293                if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     294                  <tr>
     295                    <th scope="row">
     296                      <label for="<?php echo $id ?>">From outside EU</label>
     297                    </th>
     298                    <td>
     299                      <?php if($value == 'on'){
     300                        $checkedBox = 'checked';
     301                      } else {
     302                        $checkbox = '';
     303                      } ?>
     304                      <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     305                      <span><?php echo $opts['checkboxDescription'] ?></span>
     306                      <p class="description"><?php echo $opts['descr'] ?></p>
     307                    </td>
     308                  </tr>
     309                <?php } break;
     310                //The reason for the tax exemption EU.
     311                case 'typeOfReasonEU':
     312                if($_SESSION['username'] != ''  && $settings['backend']['createInvoice'] != '' && $settings['backend']['createExemptEU'] != ''){ ?>
     313                    <tr>
     314                    <th scope="row">
     315                      <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     316                    </th>
     317                    <td>
     318                      <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     319                      <?php if(!empty($_SESSION[$id])){ ?>
     320                        <option value="0">Select one...</option>
     321                      <?php }
     322                      echo $_SESSION[$id]; ?>
     323                    </td>
     324                  </tr>
     325                  <?php } break;
     326              //Companies from EU as free-tax
     327              case 'createExemptCO':
     328                if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     329                  <tr>
     330                    <th scope="row">
     331                      <label for="<?php echo $id ?>">From EU (Co)</label>
     332                    </th>
     333                    <td>
     334                      <?php if($value == 'on'){
     335                        $checkedBox = 'checked';
     336                      } else {
     337                        $checkbox = '';
     338                      } ?>
     339                      <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     340                      <span><?php echo $opts['checkboxDescription'] ?></span>
     341                      <p class="description"><?php echo $opts['descr'] ?></p>
     342                    </td>
     343                  </tr>
     344                <?php } break;
     345                //The reason for the tax exemption EU companies.
     346                case 'typeOfReasonCO':
     347                if($_SESSION['username'] != ''  && $settings['backend']['createInvoice'] != '' && $settings['backend']['createExemptCO'] != ''){ ?>
     348                    <tr>
     349                    <th scope="row">
     350                      <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     351                    </th>
     352                    <td>
     353                      <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     354                      <?php if(!empty($_SESSION[$id])){ ?>
     355                        <option value="0">Select one...</option>
     356                      <?php }
     357                      echo $_SESSION[$id]; ?>
     358                    </td>
     359                  </tr>
     360                  <?php } break;
     361          case 'warehouseOrder':
    293362          // Show gama >= star
    294           if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?> 
     363          if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    295364                </tbody>
    296365                </table>
    297366                </div>
    298                 <div id="box"> 
     367                <div id="box">
    299368                    <div id="cab">
    300369                      Order Settings
    301370                    </div>
    302371                    <table class="form-table">
    303                       <tbody> 
     372                      <tbody>
    304373                        <tr>
    305374                          <th scope="row">
     
    307376                          </th>
    308377                          <td>
    309                             <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     378                            <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    310379                            <?php if(!empty($_SESSION[$id])){ ?>
    311380                              <option value="1">Default Warehouse</option>
    312                             <?php } 
     381                            <?php }
    313382                            echo $_SESSION[$id]; ?>
    314383                          </td>
     
    316385                        <?php } break;
    317386          case 'typeOfOrder':
    318           if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     387          if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    319388              <tr>
    320389                <th scope="row">
     
    322391                </th>
    323392                <td>
    324                   <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     393                  <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    325394                  <?php if(!empty($_SESSION[$id])){ ?>
    326395                    <option value="0">Select one...</option>
    327                   <?php } 
     396                  <?php }
    328397                  echo $_SESSION[$id]; ?>
    329398                </td>
    330399              </tr>
    331            
    332               <?php } break;         
     400
     401              <?php } break;
    333402        case 'toSignOrder':
    334               if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     403              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    335404              <tr>
    336405                <th scope="row">
     
    351420              <?php } break;
    352421          case 'numberOfOrder':
    353             if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['toSignOrder'] != ''){ ?> 
     422            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['toSignOrder'] != ''){ ?>
    354423            <tr>
    355424              <th scope="row">
     
    357426              </th>
    358427              <td>
    359                 <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     428                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    360429                <?php $fieldsStatus = array('notSelected' => 'Select one...',
    361430                                            'nmdesc' => 'Main Description',
     
    373442                        } ?>
    374443                          <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
    375                         <?php                     
     444                        <?php
    376445                      } ?>
    377446              </td>
     
    380449              <?php } break;
    381450          case 'statusOfOrder':
    382             if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
     451            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    383452            <tr>
    384453              <th scope="row">
     
    386455              </th>
    387456              <td>
    388                 <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     457                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    389458                <?php $fieldsStatus = array('notSelected' => 'Select one...',
    390459                                            'nmdesc' => 'Main Description',
     
    402471                        } ?>
    403472                          <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
    404                         <?php                     
     473                        <?php
    405474                      } ?>
    406475              </td>
     
    409478            // Select reference for shipping
    410479            case 'shippingName':
    411               if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?> 
     480              if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    412481                    <tr>
    413482                      <th scope="row">
     
    415484                      </th>
    416485                      <td>
    417                         <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     486                        <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    418487                        <?php if(!empty($_SESSION[$id])){ ?>
    419488                          <option value="0">Select one...</option>
    420                         <?php } 
     489                        <?php }
    421490                        echo $_SESSION[$id]; ?>
    422491                      </td>
     
    425494             // Select reference for fees
    426495             case 'feesName':
    427               if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?> 
     496              if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    428497                    <tr>
    429498                      <th scope="row">
     
    431500                      </th>
    432501                      <td>
    433                         <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     502                        <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    434503                        <?php if(!empty($_SESSION[$id])){ ?>
    435504                          <option value="0">Select one...</option>
    436                         <?php } 
     505                        <?php }
    437506                        echo $_SESSION[$id]; ?>
    438507                      </td>
     
    441510            //Manage stock
    442511          case 'manageStock':
    443             if($_SESSION['username'] != ''){ ?> 
     512            if($_SESSION['username'] != ''){ ?>
    444513              </tbody>
    445514              </table>
     
    450519                </div>
    451520                <table class="form-table">
    452                   <tbody> 
     521                  <tbody>
    453522                 <?php if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){ ?>
    454523                    <tr>
     
    470539                    // Select produtcs that have a positive stock
    471540                    case 'positiveStock':
    472                       if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?> 
    473                      
     541                      if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     542
    474543                      <tr>
    475544                        <th scope="row">
     
    488557                      </tr>
    489558                      <?php } break;
    490                  // Filter stock (stock - orders)   
     559                 // Filter stock (stock - orders)
    491560                 case 'filterStock':
    492                   if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['warehouse'] == "-1"){ ?> 
    493                  
     561                  if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['warehouse'] == "-1"){ ?>
     562
    494563                  <tr>
    495564                    <th scope="row">
     
    510579          // Product price column
    511580          case 'productPriceColumn':
    512             if($_SESSION['username'] != ''){ ?> 
     581            if($_SESSION['username'] != ''){ ?>
    513582              <tr>
    514583                <th scope="row">
     
    516585                </th>
    517586                <td>
    518                   <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     587                  <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    519588                  <?php $fieldsStatus = array('epv0' => 'Select one...',
    520589                                              'epv1' => 'Retail price 1 (epv1)',
     
    529598                          } ?>
    530599                            <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
    531                           <?php                     
     600                          <?php
    532601                        } ?>
    533602                </td>
     
    535604              <?php } break;
    536605          case 'warehouse':
    537             if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?> 
     606            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    538607            <tr>
    539608              <th scope="row">
     
    541610              </th>
    542611              <td>
    543                 <select id="<?php echo $id ?>" name="<?php echo $name ?>"> 
     612                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    544613                <?php if(!empty($_SESSION[$id])){ ?>
    545614                  <option value="-1">All Warehouses</option>
    546                 <?php } 
     615                <?php }
    547616                echo $_SESSION[$id]; ?>
    548617              </td>
     
    556625            </table>
    557626            </div>
    558             <?php } break; 
     627            <?php } break;
    559628           default:
    560629            break;
    561630      }
    562631    }
    563    
    564        
    565   endforeach; 
    566  
     632
     633
     634  endforeach;
     635
    567636  if($showErrorsLogin == true && (empty($settings['backend']['username']) || empty($settings['backend']['password']) || empty($settings['backend']['url']))){
    568637    $this->messagesInformation("Incomplete configurations.<br>Please fill Username, Password and Backend URL");
    569   } 
     638  }
    570639?>
  • drivefx-woocommerce/trunk/settings/import-products.php

    r2456862 r2526532  
    2323</div>
    2424
    25 <?php if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){ ?> 
     25<?php if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){ ?>
    2626    <div id="updateStocks" class="button button-primary" title="Update stocks in your online store">
    27         <img id="plus" src="<?php echo plugins_url('/../images/update.png', __FILE__) ?>" title="Save selected product in yout online store"> Update Stocks
     27        <img id="plus" src="<?php echo plugins_url('/../images/update.png', __FILE__) ?>" title="Update all stocks of products from PHC"> Update Stocks
    2828    </div>
    2929<?php } ?>
     30
     31<div id="updatePrices" class="button button-primary" title="Update prices in your online store">
     32    <img id="plus" src="<?php echo plugins_url('/../images/update.png', __FILE__) ?>" title="Update all prices of products from PHC"> Update Prices
     33</div>
     34
    3035<div id="updateAllFields" class="button button-primary" title="Update all fields of products from PHC">
    3136    <img id="plus" src="<?php echo plugins_url('/../images/update.png', __FILE__) ?>" title="Update all fields of products in your online store"> Update all fields
  • drivefx-woocommerce/trunk/settings/syncro_gate.php

    r2465114 r2526532  
    1919    public function __construct () {
    2020        $this->logs = new Logs();
    21         $this->utils_services = new UtilsServices();   
     21        $this->utils_services = new UtilsServices();
    2222    }
    2323
     
    3333        // get token
    3434        global $wpdb;
    35         $table_name = $wpdb->prefix."postmeta"; 
     35        $table_name = $wpdb->prefix."postmeta";
    3636        $query = "SELECT meta_value FROM %s WHERE meta_key = %s";
    3737        $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, '_token')));
     
    6868        $query = "SELECT meta_key, meta_value FROM %s where post_id = %d";
    6969        $raw_order = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($order_id))));
    70        
     70
    7171        //get NIF name field from backendinfo
    7272        $nifName = '_billing_'.$settings['backend']['fieldNif'];
    7373        //get price column field from backendinfo
    7474        $preco = intval(str_replace('epv', '', $settings['backend']['productPriceColumn']));
    75      
     75
    7676        $syncroData = new stdClass();
    7777
     
    7979        *                       --- billing data  ---                      *
    8080        ********************************************************************/
    81        
     81
    8282            foreach ($raw_order as $key => $value) {
    8383                if($value->meta_key == '_billing_country'){
    8484                    $syncroData->billing_country = $value->meta_value;
    8585                }  else if($value->meta_key == '_billing_first_name') {
    86                     $syncroData->billing_first_name = $value->meta_value;       
     86                    $syncroData->billing_first_name = $value->meta_value;
    8787                } else if($value->meta_key == '_billing_last_name') {
    88                     $syncroData->billing_last_name = $value->meta_value;       
     88                    $syncroData->billing_last_name = $value->meta_value;
    8989                } else if($value->meta_key == '_billing_address_1') {
    90                     $syncroData->billing_address_1 = $value->meta_value;       
     90                    $syncroData->billing_address_1 = $value->meta_value;
    9191                } else if($value->meta_key == '_billing_city') {
    92                     $syncroData->billing_city = $value->meta_value;       
     92                    $syncroData->billing_city = $value->meta_value;
    9393                } else if($value->meta_key == '_billing_postcode') {
    94                     $syncroData->billing_postcode = $value->meta_value;       
     94                    $syncroData->billing_postcode = $value->meta_value;
    9595                } else if($value->meta_key == $nifName) {
    9696                    $syncroData->$nifName = $value->meta_value;
    9797                } else if($value->meta_key == '_billing_email') {
    98                     $syncroData->billing_email = $value->meta_value;     
     98                    $syncroData->billing_email = $value->meta_value;
    9999                } else if($value->meta_key == '_billing_phone') {
    100                     $syncroData->billing_phone = $value->meta_value;       
     100                    $syncroData->billing_phone = $value->meta_value;
    101101                } else if($value->meta_key == '_shipping_country') {
    102                     $syncroData->shipping_country = $value->meta_value;     
     102                    $syncroData->shipping_country = $value->meta_value;
    103103                } else if($value->meta_key == '_shipping_address_1') {
    104                     $syncroData->shipping_address_1 = $value->meta_value;       
     104                    $syncroData->shipping_address_1 = $value->meta_value;
    105105                } else if($value->meta_key == '_shipping_city') {
    106                     $syncroData->shipping_city = $value->meta_value;       
     106                    $syncroData->shipping_city = $value->meta_value;
    107107                } else if($value->meta_key == '_shipping_postcode') {
    108108                    $syncroData->shipping_postcode = $value->meta_value;
     
    115115        *                 --- settings backend Data  ---                   *
    116116        ********************************************************************/
    117    
     117
    118118            if(isset($settings['backend']['createInvoice'])){
    119119                $createInvoice = $settings['backend']['createInvoice'];
     
    121121                    $syncroData->createInvoice = true;
    122122                }
    123             } 
     123            }
    124124            if(isset($settings['backend']['typeOfInvoice'])) {
    125125                $syncroData->typeOfInvoice = $settings['backend']['typeOfInvoice'];
    126             } 
     126            }
    127127            if(isset($settings['backend']['toSignInvoice'])) {
    128128                $toSignInvoice = $settings['backend']['toSignInvoice'];
     
    137137                $syncroData->includeTaxonSendCost = $settings['backend']['includeTaxonSendCost'];
    138138            }
    139             if(isset($settings['backend']['createExemptCl'])) {
    140                 $createExemptCl = $settings['backend']['createExemptCl'];
    141                 if($createExemptCl == 'on'){
    142                     $syncroData->createExemptCl = true;
     139            if(isset($settings['backend']['createExemptPT'])) {
     140                $createExemptPT = $settings['backend']['createExemptPT'];
     141                if($createExemptPT == 'on'){
     142                    $syncroData->createExemptPT = true;
     143                }
     144            }
     145            if(isset($settings['backend']['createExemptEU'])) {
     146                $createExemptEU = $settings['backend']['createExemptEU'];
     147                if($createExemptEU == 'on'){
     148                    $syncroData->createExemptEU = true;
     149                }
     150            }
     151            if(isset($settings['backend']['createExemptCO'])) {
     152                $createExemptCO = $settings['backend']['createExemptCO'];
     153                if($createExemptCO == 'on'){
     154                    $syncroData->createExemptCO = true;
    143155                }
    144156            }
     
    148160            if(isset($settings['backend']['typeOfReason'])) {
    149161                $syncroData->typeOfReason = $settings['backend']['typeOfReason'];
     162            }
     163            if(isset($settings['backend']['typeOfReasonEU'])) {
     164                $syncroData->typeOfReasonEU = $settings['backend']['typeOfReasonEU'];
     165            }
     166            if(isset($settings['backend']['typeOfReasonCO'])) {
     167                $syncroData->typeOfReasonCO = $settings['backend']['typeOfReasonCO'];
    150168            }
    151169            if(isset($settings['backend']['warehouseOrder'])) {
     
    188206                $syncroData->sendInvoice = $settings['backend']['sendInvoice'];
    189207            }
    190        
     208
    191209
    192210        /*******************************************************************
    193211        *                        --- Users Data  ---                       *
    194212        ********************************************************************/
    195             #Get users data query 
     213            #Get users data query
    196214            //Obtain customer ID to obtain email in Woocommerce Users
    197215            global $wpdb;
     
    199217            //Obtain next post_id of order in MySQL
    200218            $query = "SELECT user_email FROM %s WHERE id = %d";
    201             $docid = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($syncroData->customer_user))));           
     219            $docid = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($syncroData->customer_user))));
    202220            $syncroData->user_email  = $docid[0]->user_email;
    203221
    204222            #Get POST Id for current order
    205             global $wpdb;                                                   
     223            global $wpdb;
    206224            $table_name = $wpdb->prefix."postmeta";
    207225            //Obtain post_id of order in MySQL
     
    213231            if($syncroData->post_ID == ''){
    214232                $post_ID = sanitize_text_field($order_id);
    215             }   
    216                                                
     233            }
     234
    217235                //Obtain doc ID based in order
    218236                $docid = get_post_meta($syncroData->post_ID);
    219237
    220                 $syncroData->docId = $docid['_docid'][0]; 
     238                $syncroData->docId = $docid['_docid'][0];
    221239                $syncroData->orderId = sanitize_text_field($order_id);
    222240
     
    232250
    233251            #nextPostId
    234             global $wpdb;   
     252            global $wpdb;
    235253            $table_name = $wpdb->prefix."postmeta";
    236254            //Obtain next post_id of order in MySQL
    237255            $query = "SELECT MAX(post_id) as nextPostId FROM %s";
    238             $packDocId = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name))); 
     256            $packDocId = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    239257
    240258            //Save nextPostId
    241259            $syncroData->nextPostId = $packDocId->nextPostId;
    242        
     260
    243261        /*******************************************************************
    244262        *                  --- Order Shipping Data  ---                     *
     
    247265            # shipping data (Queries)
    248266
    249             $table_name = $wpdb->prefix."woocommerce_order_items"; 
     267            $table_name = $wpdb->prefix."woocommerce_order_items";
    250268            $query = "SELECT * FROM %s WHERE order_id = %s and order_item_type = 'shipping'";
    251             $resultShipping = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $packDocId->nextPostId)));         
     269            $resultShipping = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $packDocId->nextPostId)));
    252270            //get tax value for shipping
    253             $table_name = $wpdb->prefix."woocommerce_order_itemmeta"; 
     271            $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    254272            $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = 'total_tax'";
    255             $resultTax = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));                     
    256             //get shipping tax rate 
     273            $resultTax = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));
     274            //get shipping tax rate
    257275            $getShippingTax = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_shipping='1'" ) );
    258276            //get shipping tax rate country
    259             $getShippingCountry = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_country FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_shipping='1'" ) );
     277            //$getShippingCountry = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_country FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_shipping='1'" ) );
    260278            //get value
    261             $table_name = $wpdb->prefix."woocommerce_order_itemmeta"; 
     279            $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    262280            $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = 'cost'";
    263             $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));       
     281            $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));
    264282
    265283
     
    275293                $syncroData->shipping_tax = $getShippingTax;
    276294            }
    277             if(isset($getShippingCountry)) {
     295           /* if(isset($getShippingCountry)) {
    278296                $syncroData->shipping_country = $getShippingCountry;
    279             }
     297            } */
    280298            if(isset($resultDB)) {
    281299                $syncroData->shipping_value = $resultDB->meta_value;
    282300            }
    283            
     301
    284302            #Find the type of shipment
    285303            $post = get_post( $_REQUEST['shipping_method'][0] );
     
    287305            $syncroData->post_title = isset( $post->post_title ) ? $post->post_title : '';
    288306            $syncroData->edescc = WC()->cart->coupon_discount_amounts['saco'];
    289        
     307
    290308
    291309
     
    293311        *                    --- Order Fees Data  ---                      *
    294312        ********************************************************************/
    295             //build common object       
     313            //build common object
    296314            $boFeesPack = new stdClass();
    297315            $bofees = [];
     
    300318
    301319            //get fee from mysql
    302             $table_name = $wpdb->prefix."woocommerce_order_items"; 
     320            $table_name = $wpdb->prefix."woocommerce_order_items";
    303321            $query = "SELECT * FROM %s WHERE order_id = %s and order_item_type = 'fee'";
    304             $resultsFee_bo = $wpdb->get_results(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $packDocId->nextPostId)));       
     322            $resultsFee_bo = $wpdb->get_results(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $packDocId->nextPostId)));
    305323            //get fee value from mysql
    306             $table_name = $wpdb->prefix."woocommerce_order_itemmeta"; 
     324            $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    307325            $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = '_line_total'";
    308                    
     326
    309327             #Obtain name and price of fees
    310              foreach ($resultsFee_bo as $resultFee_bo) { 
     328             foreach ($resultsFee_bo as $resultFee_bo) {
    311329                $resulBoDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultFee_bo->order_item_id)));
    312    
     330
    313331                    $boFee_name = $resultFee_bo->order_item_name;
    314332                    $boFee_value = $resulBoDB->meta_value;
    315                        
     333
    316334                array_push($bofees,[
    317335                'name' =>  $boFee_name,
    318336                'value' =>  $boFee_value
    319             ]);   
    320                
     337            ]);
     338
    321339            }
    322340            $boFeesPack = $bofees;
     
    324342
    325343            # Fetch fees data
    326            
     344
    327345            if(isset($resultFee)) {
    328346                $syncroData->fee_name = $resultFee->order_item_name;
     
    331349                $syncroData->fee_value = $resultFeeValue->meta_value;
    332350            }
    333        
     351
    334352
    335353
     
    355373            $syncroData->billing_address_1_ft = $order_meta['_billing_address_1'][0];
    356374            $syncroData->billing_city_ft = $order_meta['_billing_city'][0];
    357             $syncroData->billing_phone_ft = $order_meta['_billing_phone'][0]; 
    358             $syncroData->billing_postcode_ft = $order_meta['_billing_postcode'][0]; 
     375            $syncroData->billing_phone_ft = $order_meta['_billing_phone'][0];
     376            $syncroData->billing_postcode_ft = $order_meta['_billing_postcode'][0];
    359377            $syncroData->billing_nif_ft = $order_meta['_billing_'.$settings['backend']['fieldNif']][0];
    360378
     
    369387            # shipping data (Queries)
    370388            global $wpdb;
    371             $table_name = $wpdb->prefix."woocommerce_order_items"; 
     389            $table_name = $wpdb->prefix."woocommerce_order_items";
    372390            $query = "SELECT * FROM %s WHERE order_id = %s and order_item_type = 'shipping'";
    373391            $resultsFtShipping = $wpdb->get_results(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $syncroData->nOrder)));
    374392
    375             $table_name = $wpdb->prefix."woocommerce_order_itemmeta"; 
     393            $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    376394            $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = 'cost'";
    377395            //Obtain name and price of delivery
    378             foreach ($resultsFtShipping as $resultFtShipping) { 
    379                 $resultFtDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultFtShipping->order_item_id))); 
    380                    
     396            foreach ($resultsFtShipping as $resultFtShipping) {
     397                $resultFtDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultFtShipping->order_item_id)));
     398
    381399                $syncroData->ftShipping_name = $resultFtShipping->order_item_name;
    382400                $syncroData->ftShipping_value = $resultFtDB->meta_value;
    383401            }
    384        
     402
    385403            #get shipping country for ft
    386404            if($syncroData->shipping_country != ''){
    387                 $syncroData->shipping_country_ft = $syncroData->shipping_country;       
     405                $syncroData->shipping_country_ft = $syncroData->shipping_country;
    388406            } else {
    389407                $syncroData->shipping_country_ft =  $order_meta['_shipping_country'][0];
     
    396414        *            --- Invoice Addicional Fees Data  ---                 *
    397415        ********************************************************************/
    398            
     416
    399417            //Obtain id of order and products
    400418            $order = new WC_Order($orderid);
    401419            $orderPostId = $order->post->ID;
    402             //build common object       
     420            //build common object
    403421            $addPack = new stdClass();
    404422            $fees = [];
    405423
    406424            # fees data (Queries)
    407             global $wpdb; 
    408             $table_name = $wpdb->prefix."woocommerce_order_items"; 
     425            global $wpdb;
     426            $table_name = $wpdb->prefix."woocommerce_order_items";
    409427            $query = "SELECT * FROM %s WHERE order_id = %s and  order_item_type='fee'";
    410428            $resultsFees_ft = $wpdb->get_results(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $orderPostId)));
    411429
    412             $table_name = $wpdb->prefix."woocommerce_order_itemmeta"; 
     430            $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    413431            $query = "SELECT * FROM %s WHERE order_item_id = %s and (meta_key = 'cost' or meta_key='_line_total')";
    414432
    415433            #Obtain name and price of fees
    416             foreach ($resultsFees_ft as $resultFees_ft) { 
     434            foreach ($resultsFees_ft as $resultFees_ft) {
    417435                $resultFtDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultFees_ft->order_item_id)));
    418    
     436
    419437                    $fee_name = $resultFees_ft->order_item_name;
    420438                    $fee_value = $resultFtDB->meta_value;
    421                        
     439
    422440                array_push($fees,[
    423441                'name' =>  $fee_name,
    424442                'value' =>  $fee_value
    425             ]);   
    426                
     443            ]);
     444
    427445            }
    428446
    429447            $addPack = $fees;
    430448            $syncroData->fees_ft = $addPack;
    431              
     449
    432450        //$this->logs->writeFileLog('syncroData', $syncroData);
    433        
     451
    434452        return $syncroData;
    435453    }
    436  
    437     /******************************************************************
    438     *                   ---  Order Cart Data ---                      *
    439     *******************************************************************/
    440     public function processProducts($orderid) {
    441 
    442         $this->clearProductsSession();
    443 
    444         $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    445 
    446         $prodPack = new stdClass();
    447 
    448         $products = [];
    449         $cart_contents = WC()->cart->cart_contents;
    450 
    451         if (is_array($cart_contents)){
    452             foreach (WC()->cart->cart_contents as $key => $value){
    453                 //Obtain info about products in cart
    454                 $productData = WC()->cart->cart_contents[$key];
    455            
    456                 //obtain reference items in cart
    457                 if($productData['variation_id']!='' && $productData['variation_id'] != 0){
    458                     $productReference = wc_get_product( $productData['variation_id'] );
    459                 } else {
    460                     $productReference = wc_get_product( $productData['product_id'] );
    461                 }
    462 
    463                 $valueItem = $productData['line_total'];
    464 
    465                 if ($settings['backend']['includeTaxonSendCost']=="true") {
    466                     $valueItem += $productData['line_tax'];
    467                 }
    468                
    469                 array_push($products, [
    470                     'ref' => $productReference->get_sku(),
    471                     'qtt' => $productData['quantity'],
    472                     'epv' => $valueItem,
    473                     'design' => '',
    474                     'tax_country' => '',
    475                     'tax_rate' => ''
    476                 ]);
    477             }
    478            // $this->logs->writeFileLog('products_1', $products);
     454
     455    /*******************************************************************
     456    *                   ---  Order Cart Data ---                       *
     457    ********************************************************************/
     458        public function processProducts($orderid) {
     459
     460            $this->clearProductsSession();
     461
     462            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     463
     464            $prodPack = new stdClass();
     465
     466            $products = [];
     467            $cart_contents = WC()->cart->cart_contents;
     468
     469            if (is_array($cart_contents)){
     470                foreach (WC()->cart->cart_contents as $key => $value){
     471                    //Obtain info about products in cart
     472                    $productData = WC()->cart->cart_contents[$key];
     473
     474                    //obtain reference items in cart
     475                    if($productData['variation_id']!='' && $productData['variation_id'] != 0){
     476                        $productReference = wc_get_product( $productData['variation_id'] );
     477                    } else {
     478                        $productReference = wc_get_product( $productData['product_id'] );
     479                    }
     480
     481                    $valueItem = $productData['line_total'];
     482
     483                    if ($settings['backend']['includeTaxonSendCost']=="true") {
     484                        $valueItem += $productData['line_tax'];
     485                    }
     486
     487                    array_push($products, [
     488                        'ref' => $productReference->get_sku(),
     489                        'qtt' => $productData['quantity'],
     490                        'epv' => $valueItem,
     491                        'design' => '',
     492                        'tax_country' => '',
     493                        'tax_rate' => ''
     494                    ]);
     495                }
     496            // $this->logs->writeFileLog('products_1', $products);
     497            }
     498
     499            $this->setProductsSession($products);
     500
     501            if(empty($products[0]['ref'])){
     502                //Obtain id of order and products
     503                $order = new WC_Order($orderid);
     504
     505                foreach($order->get_items() as $key => $value){
     506                    //obtain reference items in cart
     507                    if($value['variation_id'] != '' && $value['variation_id'] != 0){
     508                        $prod = new WC_Product_Variation($value['variation_id']);
     509                    } else {
     510                        $prod = new WC_Product($value['product_id']);
     511                    }
     512
     513                    $valueItem = $value['line_total'];
     514
     515                    if ($settings['backend']['includeTaxonSendCost']=="true") {
     516                        $valueItem += $value['line_tax'];
     517                    }
     518
     519                    array_push($products, [
     520                        'ref' => $prod->get_sku(),
     521                        'qtt' => $value['qty'],
     522                        'epv' => $valueItem,
     523                        'design' => '',
     524                        'tax_country' => '',
     525                        'tax_rate' => ''
     526                    ]);
     527                }
     528                $this->setProductsSession($products);
     529            }
     530
     531            # get product ref & design + product tax rate country & order tax rate
     532            foreach ($products as &$product) {
     533                if($product['qtt']*$product['epv'] != 0){
     534                # get product ref & design
     535                global $wpdb;
     536                    $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref'] ) );
     537                    $getproducttype = wc_get_product($product_id);
     538                    $typeproduct = $getproducttype->get_type();
     539                    if ($typeproduct == 'variation'){
     540                        if ( $product_id ) $wc_product =  new WC_Product_Variation( $product_id );
     541                    }
     542                    else {
     543                        if ( $product_id ) $wc_product =  new WC_Product( $product_id );
     544                    }
     545
     546                    $product['design'] = $wc_product->get_name();
     547
     548
     549                    # get product tax rate country & order tax rate
     550                    // product id
     551                    $getProductId = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref'] ) );
     552                    // product From id
     553                    $getProduct = wc_get_product($getProductId);
     554                    // product tax rate country
     555                    $getTaxCountry = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_country FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_class='%s' LIMIT 1", $getProduct->get_tax_class() ) );
     556                    // order tax rate
     557                    $getTaxOrder = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key='rate_percent' ORDER BY order_item_id DESC " ) );
     558
     559                    if (isset($getTaxCountry)){
     560                        $product['tax_country'] = $getTaxCountry;
     561                    }
     562                    if (isset($getTaxCountry)){
     563                        $product['tax_rate'] = $getTaxOrder;
     564                    }
     565                }
     566            }
     567
     568
     569            //fulfill "prodpack" with all data
     570            $prodPack = $products;
     571
     572            //$this->logs->writeFileLog('prodPack', $prodPack);
     573
     574            return $prodPack;
    479575        }
    480576
    481         $this->setProductsSession($products);     
    482 
    483         if(empty($products[0]['ref'])){
    484             //Obtain id of order and products               
    485             $order = new WC_Order($orderid);       
    486                  
    487             foreach($order->get_items() as $key => $value){
    488                  //obtain reference items in cart
    489                 if($value['variation_id'] != '' && $value['variation_id'] != 0){
    490                     $prod = new WC_Product_Variation($value['variation_id']);
    491                 } else {
    492                     $prod = new WC_Product($value['product_id']);
    493                 }       
    494 
    495                 $valueItem = $value['line_total'];
    496 
    497                 if ($settings['backend']['includeTaxonSendCost']=="true") {
    498                     $valueItem += $value['line_tax'];
    499                 }
    500                
    501                 array_push($products, [
    502                     'ref' => $prod->get_sku(),
    503                     'qtt' => $value['qty'],
    504                     'epv' => $valueItem,
    505                     'design' => '',
    506                     'tax_country' => '',
    507                     'tax_rate' => ''
    508                 ]);
    509             }
    510             $this->setProductsSession($products);       
     577        public function clearProductsSession() {
     578            unset($_SESSION['listOfSku']);
     579            unset($_SESSION['listOfQuantity']);
     580            unset($_SESSION['listOfValueItem']);
    511581        }
    512582
    513         # get product ref & design + product tax rate country & order tax rate                                             
    514          foreach ($products as &$product) {
    515             if($product['qtt']*$product['epv'] != 0){
    516               # get product ref & design
    517               global $wpdb;
    518                 $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref'] ) );
    519                 $getproducttype = wc_get_product($product_id);
    520                 $typeproduct = $getproducttype->get_type();
    521                 if ($typeproduct == 'variation'){
    522                     if ( $product_id ) $wc_product =  new WC_Product_Variation( $product_id );
    523                 }
    524                 else {
    525                     if ( $product_id ) $wc_product =  new WC_Product( $product_id );
    526                 }
    527                
    528                 $product['design'] = $wc_product->get_name();
    529                
    530 
    531                 # get product tax rate country & order tax rate
    532                 // product id
    533                 $getProductId = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref'] ) );                       
    534                 // product From id
    535                 $getProduct = wc_get_product($getProductId);   
    536                 // product tax rate country
    537                 $getTaxCountry = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_country FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_class='%s' LIMIT 1", $getProduct->get_tax_class() ) );                                 
    538                 // order tax rate                       
    539                 $getTaxOrder = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key='rate_percent' ORDER BY order_item_id DESC " ) );
    540                
    541                 if (isset($getTaxCountry)){
    542                     $product['tax_country'] = $getTaxCountry;
    543                 }
    544                 if (isset($getTaxCountry)){
    545                     $product['tax_rate'] = $getTaxOrder;
    546                 }
    547              }
    548         }   
    549 
    550        
    551         //fulfill "prodpack" with all data
    552         $prodPack = $products;
    553 
    554         //$this->logs->writeFileLog('prodPack', $prodPack);   
    555        
    556         return $prodPack;
    557     }
    558 
    559     public function clearProductsSession() {
    560         unset($_SESSION['listOfSku']);
    561         unset($_SESSION['listOfQuantity']);
    562         unset($_SESSION['listOfValueItem']);     
    563     }
    564 
    565     public function setProductsSession($products){
    566         //Save items of cart
    567         $_SESSION['listOfSku'] = [];
    568         $_SESSION['listOfQuantity'] = [];
    569         $_SESSION['listOfValueItem'] = [];   
    570        
    571         foreach( $products as $product ) {
    572             array_push($_SESSION['listOfSku'], $product->sku);
    573             array_push($_SESSION['listOfQuantity'], $product->quantity);
    574             array_push($_SESSION['listOfValueItem'], $product->value); 
     583        public function setProductsSession($products){
     584            //Save items of cart
     585            $_SESSION['listOfSku'] = [];
     586            $_SESSION['listOfQuantity'] = [];
     587            $_SESSION['listOfValueItem'] = [];
     588
     589            foreach( $products as $product ) {
     590                array_push($_SESSION['listOfSku'], $product->sku);
     591                array_push($_SESSION['listOfQuantity'], $product->quantity);
     592                array_push($_SESSION['listOfValueItem'], $product->value);
     593            }
     594            return $products;
    575595        }
    576         return $products;
    577     }
    578    
     596
    579597    /*******************************************************************
    580598    *                   ---  Invoice Cart Data ---                     *
    581599    ********************************************************************/
    582     public function processFtProducts($orderid) {
    583 
    584         $this->clearProductsSession();
    585 
    586         $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    587 
    588         $ftproductPack = new stdClass();
    589 
    590         $ftProducts = [];
    591                
    592         //Obtain id of order and products               
    593         $order = new WC_Order($orderid);
    594        
    595         foreach($order->get_items() as $key => $value){
    596             //obtain reference items in cart
    597             if($value['variation_id'] != '' && $value['variation_id'] != 0){
    598                 $prod = new WC_Product_Variation($value['variation_id']);
    599             } else {
    600                 $prod = new WC_Product($value['product_id']);
    601             }       
    602             $sku = $prod->get_sku();
    603             $quantity = $value['qty'];
    604             $valueItem = $value['line_total'] + $value['line_tax'];
    605            
    606             array_push($ftProducts, [
    607                 'ref' =>  $sku,
    608                 'qtt' => $quantity,
    609                 'epv' => $valueItem,
    610                 'design' => '',
    611                 'etiliquido' => ''
    612             ]);   
    613         }
    614         //Save items of cart
    615         $this->setFtProductsSession($ftProducts);
    616        
    617 
    618         //FT from Backend if is clicked "button tip"
    619         if(empty($ftProducts[0]['ref'])){
     600        public function processFtProducts($orderid) {
     601
     602            $this->clearProductsSession();
     603
     604            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     605
     606            $ftproductPack = new stdClass();
     607
     608            $ftProducts = [];
     609
     610            //Obtain id of order and products
     611            $order = new WC_Order($orderid);
     612
    620613            foreach($order->get_items() as $key => $value){
    621614                //obtain reference items in cart
     
    624617                } else {
    625618                    $prod = new WC_Product($value['product_id']);
    626                 }       
     619                }
    627620                $sku = $prod->get_sku();
    628621                $quantity = $value['qty'];
    629622                $valueItem = $value['line_total'] + $value['line_tax'];
    630                
     623
    631624                array_push($ftProducts, [
    632625                    'ref' =>  $sku,
     
    634627                    'epv' => $valueItem,
    635628                    'design' => '',
    636                     'etiliquido' => '',
    637 
    638                 ]);   
     629                    'etiliquido' => ''
     630                ]);
    639631            }
    640632            //Save items of cart
    641633            $this->setFtProductsSession($ftProducts);
     634
     635
     636            //FT from Backend if is clicked "button tip"
     637            if(empty($ftProducts[0]['ref'])){
     638                foreach($order->get_items() as $key => $value){
     639                    //obtain reference items in cart
     640                    if($value['variation_id'] != '' && $value['variation_id'] != 0){
     641                        $prod = new WC_Product_Variation($value['variation_id']);
     642                    } else {
     643                        $prod = new WC_Product($value['product_id']);
     644                    }
     645                    $sku = $prod->get_sku();
     646                    $quantity = $value['qty'];
     647                    $valueItem = $value['line_total'] + $value['line_tax'];
     648
     649                    array_push($ftProducts, [
     650                        'ref' =>  $sku,
     651                        'qtt' => $quantity,
     652                        'epv' => $valueItem,
     653                        'design' => '',
     654                        'etiliquido' => '',
     655
     656                    ]);
     657                }
     658                //Save items of cart
     659                $this->setFtProductsSession($ftProducts);
     660            }
     661
     662            # get ft product ref & design
     663            foreach ($ftProducts as &$product) {
     664                if($product['qtt']*$product['epv'] != 0){
     665                # get product ref & design
     666                global $wpdb;
     667                    $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref']));
     668                    $getproducttype = wc_get_product($product_id);
     669                    $typeproduct = $getproducttype->get_type();
     670                    if ($typeproduct == 'variation'){
     671                        if ( $product_id ) $wc_prod =  new WC_Product_Variation( $product_id );
     672                    }
     673                    else {
     674                        if ( $product_id ) $wc_prod =  new WC_Product( $product_id );
     675                    }
     676
     677                    $product['design'] = $wc_prod->get_name();
     678                }
     679            }
     680
     681            $items = $order->get_items();
     682
     683            $key=0;
     684            foreach($items as $item => $values) {
     685                $ftProducts[$key]['etiliquido'] = $values['line_total'];
     686
     687                if($settings['backend']['includeTaxonSendCost']=="true"){
     688                    $ftProducts[$key]['etiliquido'] = $values['line_total']  + $values['line_tax'];
     689                }
     690                    $key++;
     691            }
     692
     693            //fulfill "prodpack" with all data
     694            $ftproductPack = $ftProducts;
     695
     696            //$this->logs->writeFileLog('prodPackft', $ftproductPack);
     697
     698            return $ftproductPack;
    642699        }
    643        
    644         # get ft product ref & design
    645         foreach ($ftProducts as &$product) {
    646             if($product['qtt']*$product['epv'] != 0){
    647               # get product ref & design
    648               global $wpdb;
    649                 $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['ref']));
    650                 $getproducttype = wc_get_product($product_id);
    651                 $typeproduct = $getproducttype->get_type();
    652                 if ($typeproduct == 'variation'){
    653                     if ( $product_id ) $wc_prod =  new WC_Product_Variation( $product_id );
    654                 }
    655                 else {
    656                     if ( $product_id ) $wc_prod =  new WC_Product( $product_id );
    657                 }
    658                
    659                 $product['design'] = $wc_prod->get_name();
    660             }
     700
     701        public function setFtProductsSession($ftProducts){
     702            //Save items of cart
     703            $_SESSION['listOfSku'] = [];
     704            $_SESSION['listOfQuantity'] = [];
     705            $_SESSION['listOfValueItem'] = [];
     706
     707            foreach( $ftProducts as $ftProduct ) {
     708                array_push($_SESSION['listOfSku'], $ftProduct->sku);
     709                array_push($_SESSION['listOfQuantity'], $ftProduct->quantity);
     710                array_push($_SESSION['listOfValueItem'], $ftProduct->value);
     711            }
     712            return $ftproductPack;
    661713        }
    662714
    663         $items = $order->get_items();
    664        
    665         $key=0;
    666         foreach($items as $item => $values) {               
    667             $ftProducts[$key]['etiliquido'] = $values['line_total'];
    668 
    669             if($settings['backend']['includeTaxonSendCost']=="true"){
    670                 $ftProducts[$key]['etiliquido'] = $values['line_total']  + $values['line_tax']; 
    671             }                   
    672                 $key++;                 
    673         }
    674 
    675         //fulfill "prodpack" with all data
    676         $ftproductPack = $ftProducts;
    677 
    678         //$this->logs->writeFileLog('prodPackft', $ftproductPack);   
    679        
    680         return $ftproductPack;
    681     }
    682    
    683     public function setFtProductsSession($ftProducts){
    684         //Save items of cart
    685         $_SESSION['listOfSku'] = [];
    686         $_SESSION['listOfQuantity'] = [];
    687         $_SESSION['listOfValueItem'] = [];   
    688        
    689         foreach( $ftProducts as $ftProduct ) {
    690             array_push($_SESSION['listOfSku'], $ftProduct->sku);
    691             array_push($_SESSION['listOfQuantity'], $ftProduct->quantity);
    692             array_push($_SESSION['listOfValueItem'], $ftProduct->value); 
    693         }
    694         return $ftproductPack;
    695     }
    696    
    697715
    698716
     
    711729        $order = new Order();
    712730        $ft = new Invoice();
    713        
     731
    714732        #settings data
    715733        $settings->createInvoice = $wooOrder->createInvoice;
     
    718736        $settings->fieldNif = $wooOrder->fieldNif;
    719737        $settings->includeTaxonSendCost = $wooOrder->includeTaxonSendCost;
    720         $settings->createExemptCl = $wooOrder->createExemptCl;
     738        $settings->createExemptPT = $wooOrder->createExemptPT;
    721739        $settings->typeOfReason = $wooOrder->typeOfReason;
     740        $settings->createExemptEU = $wooOrder->createExemptEU;
     741        $settings->typeOfReasonEU = $wooOrder->typeOfReasonEU;
     742        $settings->createExemptCO = $wooOrder->createExemptCO;
     743        $settings->typeOfReasonCO = $wooOrder->typeOfReasonCO;
    722744        $settings->warehouseOrder = $wooOrder->warehouseOrder;
    723745        $settings->typeOfOrder = $wooOrder->typeOfOrder;
     
    756778        $shipping->shipping_country = $wooOrder->shipping_country;
    757779        $shipping->shipping_value = $wooOrder->shipping_value;
    758        
    759         # customer data 
     780
     781        # customer data
    760782        $customer->nome = $wooOrder->billing_first_name. " " .$wooOrder->billing_last_name;
     783        $customer->email = $wooOrder->billing_email;
     784        $customer->morada = !empty($wooOrder->shipping_address_1) ? $wooOrder->shipping_address_1 : $wooOrder->billing_address_1;
     785        $customer->local = !empty($wooOrder->shipping_city) ? $wooOrder->shipping_city : $wooOrder->billing_city;
     786        $customer->provincia = !empty($wooOrder->shipping_city) ? $wooOrder->shipping_city : $wooOrder->billing_city;
     787        $customer->telefone = $wooOrder->billing_phone;
     788        $customer->codpost = !empty($wooOrder->shipping_postcode) ? $wooOrder->shipping_postcode : $wooOrder->billing_postcode;
     789        $customer->ncont = $wooOrder->billing_nif_ft;
     790        $customer->preco = $wooOrder->productPriceColumn;
     791        $customer->country = !empty($wooOrder->shipping_country) ? $wooOrder->shipping_country : $wooOrder->billing_country;
     792        $customer->user_email = $wooOrder->user_email;
     793
     794       /*  $customer->nome = $wooOrder->billing_first_name. " " .$wooOrder->billing_last_name;
    761795        $customer->email = $wooOrder->billing_email;
    762796        $customer->morada = $wooOrder->billing_address_1;
     
    768802        $customer->preco = $wooOrder->productPriceColumn;
    769803        $customer->country = $wooOrder->billing_country;
    770         $customer->user_email = $wooOrder->user_email;
    771  
     804        $customer->user_email = $wooOrder->user_email; */
     805
    772806        # order
    773         $order->post_Id = $wooOrder->post_ID; 
     807        $order->post_Id = $wooOrder->post_ID;
    774808        $order->doc_Id = $wooOrder->docId;
    775809        $order->order_Id = $wooOrder->orderId;
     
    786820        $ft->shipping_country = $wooOrder->shipping_country_ft;
    787821        $ft->cart = $ftprodPack;
    788         $ft->shipping_name = $wooOrder->ftShipping_name; 
     822        $ft->shipping_name = $wooOrder->ftShipping_name;
    789823        $ft->shipping_value = $wooOrder->ftShipping_value;
    790824        $ft->fees = $wooOrder->fees_ft;
    791         $ft->billing_name = $wooOrder->billing_first_name_ft. " " .$wooOrder->billing_last_name_ft; 
     825        $ft->billing_name = $wooOrder->billing_first_name_ft. " " .$wooOrder->billing_last_name_ft;
    792826        $ft->billing_email = $wooOrder->billing_email_ft;
    793827        $ft->billing_address_1 = $wooOrder->billing_address_1_ft;
     
    812846        $dataPack->ft = $ft;
    813847
    814      
     848
    815849        //$this->logs->writeFileLog('dataPack', $dataPack);
    816850
    817851        return $dataPack;
    818     } 
     852    }
    819853}
    820 ?>
Note: See TracChangeset for help on using the changeset viewer.