Exemple #1
0
/**
 * Add export button to order actions column
 * @since 0.1
 * Changed for WC 2.1
 */
function WooParc_order_actions($column)
{
    global $post;
    $order = new WC_Order($post->ID);
    if (version_compare(WOOCOMMERCE_VERSION, "2.0.99") >= 0) {
        $shipping_method = $order->get_shipping_methods();
        $shipping_method = array_shift(array_slice($shipping_method, 0, 1));
    } else {
        $currency = get_option('woocommerce_currency');
        $currency = get_woocommerce_currency_symbol($currency);
    }
    switch ($column) {
        case "order_actions":
            ?>
<p style="display:block;clear:both;height:14px">
				<a class="button parc-link tips" data-tip="<?php 
            _e('Export to Parcelware', 'woo-parc');
            ?>
" href="<?php 
            echo wp_nonce_url(admin_url('?wooparc_submitted=exported&order_id=' . $post->ID . '&wooparc_type=single'), 'wooparc_nonce');
            ?>
"><img src="<?php 
            echo WooParc_icon($order);
            ?>
" alt="<?php 
            _e('Export to Parcelware', 'woo-parc');
            ?>
" width="14" style="display:inline;float:left;">
			<?php 
            if (isset($shipping_method['method_id']) && get_option('wooparc_actions_price', 0) == 1) {
                // for WC 2.1
                echo '<small style="display:inline;float:left;line-height:12px">&nbsp;' . wc_price($shipping_method['cost']) . '</small>';
            } elseif ($order->shipping_method_title && get_option('wooparc_actions_price', 0) == 1) {
                // for WC 2.0
                echo '<small style="display:inline;float:left;line-height:12px">&nbsp;' . $currency . $order->order_shipping . '</small>';
            }
            ?>
</a>
  			</p>
<?php 
            break;
        case "shipping_address":
            if (isset($shipping_method['method_id']) && get_option('wooparc_actions_price', 0) == 2) {
                // for WC 2.1
                echo '<small class="meta">' . __('Shipping', 'woocommerce') . ': ' . woocommerce_price($shipping_method['cost']) . '</small>';
            } elseif (get_option('wooparc_actions_price', 0) == 2) {
                // for WC 2.0
                if ($order->shipping_method_title) {
                    echo '<small class=meta style="display:inline;">' . __('Shipping Cost:', 'woo-parc') . ' ' . $currency . $order->order_shipping . '</small>';
                }
            }
            ?>
</a>
  			</p>
<?php 
            break;
    }
}
Exemple #2
0
function sr_woo_add_order($order_id, $refund_id = '')
{
    global $wpdb;
    $order = new WC_Order($order_id);
    $order_items = array($order_id => $order->get_items());
    $order_items['order_date'] = $order->order_date;
    $order_items['order_status'] = $order->post_status;
    $order_is_sale = 1;
    //Condn for woo 2.2 compatibility
    if (defined('SR_IS_WOO22') && SR_IS_WOO22 == "true") {
        $order_status = substr($order->post_status, 3);
    } else {
        $order_status = wp_get_object_terms($order_id, 'shop_order_status', array('fields' => 'slugs'));
        $order_status = !empty($order_status) ? $order_status[0] : '';
    }
    if ($order_status == 'on-hold' || $order_status == 'processing' || $order_status == 'completed') {
        $insert_query = "REPLACE INTO {$wpdb->prefix}sr_woo_order_items \n\t\t\t\t\t\t( `product_id`, `order_id`, `order_date`, `order_status`, `product_name`, `sku`, `category`, `quantity`, `sales`, `discount` ) VALUES ";
        $values = sr_items_to_values($order_items);
        if (count($values) > 0) {
            $insert_query .= implode(",", $values);
            $wpdb->query($insert_query);
        }
    } else {
        $wpdb->query("DELETE FROM {$wpdb->prefix}sr_woo_order_items WHERE order_id = {$order_id}");
        $order_is_sale = 0;
    }
    //chk if the SR Beta Snapshot table exists or not
    $table_name = "{$wpdb->prefix}woo_sr_orders";
    if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") == $table_name) {
        $oi_type = 'S';
        // For handling manual refunds
        if (!empty($refund_id)) {
            $order_id = $refund_id;
            $order = new WC_Order($order_id);
            $oi_type = 'R';
        }
        $order_items = $order->get_items(array('line_item', 'shipping'));
        $order_meta = get_post_meta($order_id);
        $order_sm = $order->get_shipping_methods();
        $oi_values = array();
        $t_qty = 0;
        $sm_id = '';
        foreach ($order_items as $oi_id => $item) {
            if ($item['type'] == 'shipping') {
                $sm_id = !empty($item['item_meta']['method_id'][0]) ? $item['item_meta']['method_id'][0] : '';
            } else {
                $t_qty += $item['qty'];
                $oi_values[] = "( " . $wpdb->_real_escape($oi_id) . ", '" . $wpdb->_real_escape(substr($order->order_date, 0, 10)) . "', \n\t\t    \t\t\t\t\t\t\t'" . $wpdb->_real_escape(substr($order->order_date, 12)) . "', " . $wpdb->_real_escape($order_is_sale) . ", \n\t\t    \t\t\t\t\t\t\t" . $wpdb->_real_escape($item['product_id']) . ", " . $wpdb->_real_escape($item['variation_id']) . ",\n\t\t    \t\t\t\t\t\t \t" . $wpdb->_real_escape($order_id) . ", '" . $wpdb->_real_escape($oi_type) . "', " . $wpdb->_real_escape($item['qty']) . ",\n\t\t    \t\t\t\t\t\t \t" . $wpdb->_real_escape($item['line_total']) . " )";
            }
        }
        $query = "REPLACE INTO {$wpdb->prefix}woo_sr_orders \n\t\t\t\t\t\t( `order_id`, `created_date`, `created_time`, `status`, `type`, `parent_id`, `total`, `currency`, `discount`, `cart_discount`, `shipping`, \n\t\t\t\t\t\t\t`shipping_tax`, `shipping_method`, `tax`, `qty`, `payment_method`, `user_id`, `billing_email`,\n\t\t\t\t\t\t\t`billing_country`, `customer_name` ) VALUES\n\t\t\t\t\t\t\t( " . $wpdb->_real_escape($order->id) . ", '" . $wpdb->_real_escape(substr($order->order_date, 0, 10)) . "',\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(substr($order->order_date, 12)) . "', '" . $wpdb->_real_escape($order->post_status) . "',\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape($order->post->post_type) . "', " . $wpdb->_real_escape($order->post->post_parent) . ", \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_order_total'][0]) ? $order_meta['_order_total'][0] : 0) . ",\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(!empty($order_meta['_order_currency'][0]) ? $order_meta['_order_currency'][0] : '') . "', \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_order_discount'][0]) ? $order_meta['_order_discount'][0] : 0) . ",\n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_cart_discount'][0]) ? $order_meta['_cart_discount'][0] : 0) . ",\n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_order_shipping'][0]) ? $order_meta['_order_shipping'][0] : 0) . ", \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_order_shipping_tax'][0]) ? $order_meta['_order_shipping_tax'][0] : 0) . ",\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape($sm_id) . "', \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_order_tax'][0]) ? $order_meta['_order_tax'][0] : 0) . ", \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($t_qty) ? $t_qty : 1) . ",\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(!empty($order_meta['_payment_method'][0]) ? $order_meta['_payment_method'][0] : '') . "', \n\t\t\t\t\t\t\t" . $wpdb->_real_escape(!empty($order_meta['_customer_user'][0]) ? $order_meta['_customer_user'][0] : 0) . ",\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(!empty($order_meta['_billing_email'][0]) ? $order_meta['_billing_email'][0] : '') . "', \n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(!empty($order_meta['_billing_country'][0]) ? $order_meta['_billing_country'][0] : '') . "',\n\t\t\t\t\t\t\t'" . $wpdb->_real_escape(!empty($order_meta['_billing_first_name'][0]) ? $order_meta['_billing_first_name'][0] : '') . ' ' . $wpdb->_real_escape(!empty($order_meta['_billing_last_name'][0]) ? $order_meta['_billing_last_name'][0] : '') . "' ) ";
        $wpdb->query($query);
        $query = "REPLACE INTO {$wpdb->prefix}woo_sr_order_items\n\t\t\t\t\t\t\t( `order_item_id`, `order_date`, `order_time`, `order_is_sale`, `product_id`, `variation_id`, `order_id`, `type`,\n\t\t\t\t\t\t\t`qty`, `total` ) VALUES ";
        if (count($oi_values) > 0) {
            $query .= implode(',', $oi_values);
            $wpdb->query($query);
        }
    }
}
 /**
  * If the order doesn't contain shipping methods because it contains synced or trial products but the related subscription(s) does have a shipping method.
  * This function will ensure the shipping address is still displayed in order emails and on the order received and view order pages.
  *
  * @param bool $needs_shipping
  * @param array $hidden_shipping_methods shipping method IDs which should hide shipping addresses (defaulted to array( 'local_pickup' ))
  * @param WC_Order $order
  *
  * @return bool $needs_shipping whether an order needs to display the shipping address
  *
  * @since 2.0.14
  */
 public static function maybe_display_shipping_address($needs_shipping, $hidden_shipping_methods, $order)
 {
     $order_shipping_methods = $order->get_shipping_methods();
     if (!$needs_shipping && wcs_order_contains_subscription($order) && empty($order_shipping_methods)) {
         $subscriptions = wcs_get_subscriptions_for_order($order);
         foreach ($subscriptions as $subscription) {
             foreach ($subscription->get_shipping_methods() as $shipping_method) {
                 if (!in_array($shipping_method['method_id'], $hidden_shipping_methods)) {
                     $needs_shipping = true;
                     break 2;
                 }
             }
         }
     }
     return $needs_shipping;
 }
 protected function get_selected_rates(WC_Order $order)
 {
     $shipping_methods = $order->get_shipping_methods();
     $shipping_method = reset($shipping_methods);
     if (!$shipping_method || !isset($shipping_method['wc_connect_packages'])) {
         return array();
     }
     $packages = json_decode($shipping_method['wc_connect_packages'], true);
     $rates = array();
     foreach ($packages as $idx => $package) {
         // Abort if the package data is malformed
         if (!$package['id'] || !$package['service_id']) {
             return array();
         }
         $rates[$package['id']] = $package['service_id'];
     }
     return $rates;
 }
 /**
  * Get shipping method names
  * @param  WC_Order $order
  * @return array
  */
 private function get_shipping_methods($order)
 {
     $shipping_methods = $order->get_shipping_methods();
     $shipping_method_names = array();
     foreach ($shipping_methods as $shipping_method) {
         $shipping_method_names[] = $shipping_method['name'];
     }
     return $shipping_method_names;
 }
/**
 * build shipping labels PDF
*/
function get_etiquetas_pdf()
{
    /**
     *
     * WooCommerce
     *
     * Biblioteca para PDF
     *
     */
    require_once "dompdf/dompdf_config.inc.php";
    $html .= '<!DOCTYPE html>';
    $html .= ' <html>';
    $html .= ' <head>';
    $html .= ' 	<title>Etiquetas Correios</title>';
    $html .= ' <style type="text/css">
*{font-size:15px;}
div.one{width:368px; position: absolute; top: 0; height: 142px; border: 1px dotted #fff; background: transparent; }

div.one div{padding:13px 18px 13px 25px;line-height:19px;}

.right {
	left: 379px;
}

html,
@page,
page,
body { padding: 0 !important; margin: 0px !important; position: relative; }

body {
	margin-top: 57px !important;
	margin-left: 17.7px !important;
	margin-right: 17.7px !important;
	font-family: helvetica !important;
}

@page .single-page {
  size: A4 portrait;
}

.single-page {
   page: teacher;
   page-break-after: always;
}

</style>';
    $html .= ' </head>';
    $html .= ' <body>';
    $html .= ' <page><div class="single-page">';
    $orders = $_GET['ids'];
    $orders = explode(",", $orders);
    $i = 0;
    $a = 0;
    foreach ($orders as $key => $value) {
        $pedido = $value;
        $order = new WC_Order($pedido);
        // $order = wc_get_order( $value );
        //altura
        $height = 142;
        // 144 tamanho real
        $top = ($height + 3) * $a;
        //esquerda//direita
        if ($i % 2) {
            $alinha = "right";
            $a++;
        } else {
            $alinha = "left";
        }
        $nome = $order->shipping_first_name;
        $sobrenome = $order->shipping_last_name;
        $endereco = $order->shipping_address_1;
        $endereco2 = $order->shipping_address_2;
        $cidade = $order->shipping_city;
        $uf = $order->shipping_state;
        $cep = $order->shipping_postcode;
        $rates = $order->get_shipping_methods();
        foreach ($rates as $key => $rate) {
            $tipoEnvio = $rate['method_id'];
            break;
        }
        $html .= '<div class="one ';
        $html .= $alinha;
        $html .= '" style="top: ' . $top . 'px;"><div>';
        #$html .= '#';
        #$html .= str_pad($order->id, 6, "0", STR_PAD_LEFT);
        $html .= '<b>DESTINAT&Aacute;RIO: </b>';
        if ($tipoEnvio == 'advanced_free_shipping') {
            #$html .= 'Carta Registrada';
        } else {
            #$html .= $tipoEnvio;
        }
        $html .= '</b><br /><p style="font-size: 10px;">';
        $html .= $nome . " " . $sobrenome;
        $html .= '<br />';
        $html .= $endereco;
        #$html .= ' - ';
        // campos do Extra Checkout Field
        $numero = $order->shipping_number;
        $bairro = $order->shipping_neighborhood;
        $html .= $numero;
        $html .= '<br/>';
        /**
         * verifica se o campo foi preenchido, evitando que fique espaços em branco na etiqueta
         */
        if ($bairro != "") {
            $html .= $bairro;
            $html .= '<br />';
        }
        #  	$html .= ' - ';
        // fim dos campos do Extra Checkout Field
        /**
         * verifica se o campo foi preenchido, evitando que fique espaços em branco na etiqueta
         */
        if ($endereco2 != "") {
            $html .= $endereco2;
            $html .= '<br />';
        }
        $html .= $cidade;
        $html .= ' - ';
        $html .= $uf;
        $html .= '<br />';
        $html .= 'CEP: ';
        $html .= $cep;
        $html .= '<br />';
        $html .= '<br />';
        /**
         * Verifica se o post tipo página responsável pelo endereço do remente já foi inserido no banco
         * Se foi, exibe o remetente, se não, insere um remetente padrão e exibe
         * O remetente padrão deve ser alterado no painel, nas páginas
         */
        $buscaRemetente = mysql_query("SELECT SQL_CACHE * FROM wp_posts WHERE post_password = '******'") or die(mysql_error());
        if (mysql_num_rows($buscaRemetente) == 0) {
            $insere = mysql_query("INSERT INTO wp_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status,  comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_content_filtered, post_parent, guid, menu_order, post_type, post_mime_type, comment_count) VALUES ('1', '2016-01-27 12:45:09', '2016-01-27 14:45:09', 'Nome da empresa<br>R. Nome da rua, 123 - Centro<br>Cidade - UF<br>CEP: 99888-777', 'Nosso endereço', '', 'publish', 'closed', 'closed', '123Mudar#\$', 'nosso-endereco', '', '', '2016-01-27 14:53:51', '2016-01-27 14:53:51', '', '0', 'http://localhost/wordpress/?page_id=', '0', 'page', '', '0')") or die(mysql_error());
            $buscaDeNovo = mysql_query("SELECT * FROM wp_posts WHERE post_password = '******'") or die(mysql_error());
            $r = mysql_fetch_array($buscaDeNovo);
            $html .= '<b>REMETENTE</b><br>';
            $html .= '<p style="font-size: 10px;">' . $r['post_content'] . '</p>';
        } else {
            $r = mysql_fetch_array($buscaRemetente);
            $html .= '<b>REMETENTE</b><br>';
            $html .= '<p style="font-size: 10px;">' . $r['post_content'] . '</p>';
        }
        $html .= '</p></div></div>';
        if ($i == 13) {
            $html .= '</div></page><page><div class="single-page">';
            $a = 0;
        }
        $i++;
    }
    $html .= ' </body>';
    $html .= '</html>';
    // wp_mail( '*****@*****.**', 'Etiqueta', $html );
    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $dompdf->set_paper('a4', 'landscape');
    $dompdf->stream("etiqueta.pdf", array('Attachment' => 0));
    exit;
}
function woo_ce_get_order_assoc_shipping_method_id( $order_id = 0 ) {

	global $export;

	if( class_exists( 'WC_Order' ) && !empty( $order_id ) ) {
		$output = '';
		$order = new WC_Order( $order_id );
		if( method_exists( 'WC_Order', 'get_shipping_methods' ) ) {
			if( $shipping_methods = $order->get_shipping_methods() ) {
				foreach( $shipping_methods as $shipping_item_id => $shipping_item ) {
					if( isset( $shipping_item['item_meta'] ) ) {
						$output = $shipping_item['item_meta']['method_id'];
						if( is_array( $output ) )
							$output = $output[0];
						break;
					}
				}
			}
			unset( $shipping_methods );
		}
		unset( $order );
		return apply_filters( 'woo_ce_get_order_assoc_shipping_method_id', $output );
	}

}
Exemple #8
0
 public function generate_invoice($orderId)
 {
     global $wpdb, $woocommerce;
     $order = new WC_Order($orderId);
     $order_items = $order->get_items();
     //Build Xml
     $szamla = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><xmlszamla xmlns="http://www.szamlazz.hu/xmlszamla" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.szamlazz.hu/xmlszamla xmlszamla.xsd"></xmlszamla>');
     //If custom details
     if (isset($_POST['note']) && isset($_POST['deadline']) && isset($_POST['completed'])) {
         $note = $_POST['note'];
         $deadline = $_POST['deadline'];
         $complated_date = $_POST['completed'];
     } else {
         $note = get_option('wc_szamlazz_note');
         $deadline = get_option('wc_szamlazz_payment_deadline');
         $complated_date = date('Y-m-d');
     }
     //Account & Invoice settings
     $beallitasok = $szamla->addChild('beallitasok');
     $beallitasok->addChild('felhasznalo', get_option('wc_szamlazz_username'));
     $beallitasok->addChild('jelszo', get_option('wc_szamlazz_password'));
     if (get_option('wc_szamlazz_invoice_type') != 'paper') {
         $beallitasok->addChild('eszamla', 'true');
     } else {
         $beallitasok->addChild('eszamla', 'false');
     }
     $beallitasok->addChild('szamlaLetoltes', 'true');
     //Invoice details
     $fejlec = $szamla->addChild('fejlec');
     $fejlec->addChild('keltDatum', date('Y-m-d'));
     $fejlec->addChild('teljesitesDatum', $complated_date);
     if ($deadline) {
         $fejlec->addChild('fizetesiHataridoDatum', date('Y-m-d', strtotime('+' . $deadline . ' days')));
     } else {
         $fejlec->addChild('fizetesiHataridoDatum', date('Y-m-d'));
     }
     $fejlec->addChild('fizmod', $order->payment_method_title);
     $fejlec->addChild('penznem', $order->get_order_currency());
     $fejlec->addChild('szamlaNyelve', 'hu');
     $fejlec->addChild('megjegyzes', $note);
     if ($order->get_order_currency() != 'HUF') {
         //if the base currency is not HUF, we should define currency rates
         $fejlec->addChild('arfolyamBank', '');
         $fejlec->addChild('arfolyam', 0);
     }
     $fejlec->addChild('rendelesSzam', $order->get_order_number());
     $fejlec->addChild('elolegszamla', 'false');
     $fejlec->addChild('vegszamla', 'false');
     //Seller details
     $elado = $szamla->addChild('elado');
     //Customer details
     $vevo = $szamla->addChild('vevo');
     $vevo->addChild('nev', ($order->billing_company ? $order->billing_company . ' - ' : '') . $order->billing_first_name . ' ' . $order->billing_last_name);
     $vevo->addChild('irsz', $order->billing_postcode);
     $vevo->addChild('telepules', $order->billing_city);
     $vevo->addChild('cim', $order->billing_address_1);
     $vevo->addChild('email', $order->billing_email);
     $vevo->addChild('adoszam', '');
     $vevo->addChild('telefonszam', $order->billing_phone);
     //Customer Shipping details if needed
     if ($order->shipping_address) {
         $vevo->addChild('postazasiNev', ($order->shipping_company ? $order->shipping_company . ' - ' : '') . $order->shipping_first_name . ' ' . $order->shipping_last_name);
         $vevo->addChild('postazasiIrsz', $order->shipping_postcode);
         $vevo->addChild('postazasiTelepules', $order->shipping_city);
         $vevo->addChild('postazasiCim', $order->shipping_address_1);
     }
     //Order Items
     $tetelek = $szamla->addChild('tetelek');
     foreach ($order_items as $termek) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', htmlspecialchars($termek["name"]));
         $tetel->addChild('mennyiseg', $termek["qty"]);
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', round($termek["line_total"], 2) / $termek["qty"]);
         $tetel->addChild('afakulcs', round($termek["line_tax"] / $termek["line_total"] * 100));
         $tetel->addChild('nettoErtek', round($termek["line_total"], 2));
         $tetel->addChild('afaErtek', round($termek["line_tax"], 2));
         $tetel->addChild('bruttoErtek', round($termek["line_total"], 2) + round($termek["line_tax"], 2));
         $tetel->addChild('megjegyzes', '');
     }
     //Shipping
     if ($order->get_shipping_methods()) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', htmlspecialchars($order->get_shipping_method()));
         $tetel->addChild('mennyiseg', '1');
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', round($order->order_shipping, 2));
         if ($order->order_shipping == 0) {
             $tetel->addChild('afakulcs', '0');
         } else {
             $tetel->addChild('afakulcs', round($order->order_shipping_tax / $order->order_shipping * 100));
         }
         $tetel->addChild('nettoErtek', round($order->order_shipping, 2));
         $tetel->addChild('afaErtek', round($order->order_shipping_tax, 2));
         $tetel->addChild('bruttoErtek', round($order->order_shipping, 2) + round($order->order_shipping_tax, 2));
         $tetel->addChild('megjegyzes', '');
     }
     //Extra Fees
     $fees = $order->get_fees();
     if (!empty($fees)) {
         foreach ($fees as $fee) {
             $tetel = $tetelek->addChild('tetel');
             $tetel->addChild('megnevezes', htmlspecialchars($fee["name"]));
             $tetel->addChild('mennyiseg', 1);
             $tetel->addChild('mennyisegiEgyseg', '');
             $tetel->addChild('nettoEgysegar', round($fee["line_total"], 2));
             $tetel->addChild('afakulcs', round($fee["line_tax"] / $fee["line_total"] * 100));
             $tetel->addChild('nettoErtek', round($fee["line_total"], 2));
             $tetel->addChild('afaErtek', round($fee["line_tax"], 2));
             $tetel->addChild('bruttoErtek', round($fee["line_total"], 2) + round($fee["line_tax"], 2));
             $tetel->addChild('megjegyzes', '');
         }
     }
     //Discount
     if ($order->order_discount > 0) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', 'Kedvezmény');
         $tetel->addChild('mennyiseg', '1');
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', -$order->order_discount);
         $tetel->addChild('afakulcs', 0);
         $tetel->addChild('nettoErtek', -$order->order_discount);
         $tetel->addChild('afaErtek', 0);
         $tetel->addChild('bruttoErtek', -$order->order_discount);
         $tetel->addChild('megjegyzes', '');
     }
     //Generate XML
     $xml_szamla = apply_filters('wc_szamlazz_xml', $szamla, $order);
     $xml = $xml_szamla->asXML();
     //Temporarily save XML
     $UploadDir = wp_upload_dir();
     $UploadURL = $UploadDir['basedir'];
     $location = realpath($UploadURL . "/wc_szamlazz/");
     $xmlfile = $location . '/' . $orderId . '.xml';
     $test = file_put_contents($xmlfile, $xml);
     //Generate cookie
     $cookie_file = $location . '/szamlazz_cookie.txt';
     //Agent URL
     $agent_url = 'https://www.szamlazz.hu/szamla/';
     //Geerate Cookie if not already exists
     if (!file_exists($cookie_file)) {
         file_put_contents($cookie_file, '');
     }
     // a CURL inicializálása
     $ch = curl_init($agent_url);
     // A curl hívás esetén tanúsítványhibát kaphatunk az SSL tanúsítvány valódiságától
     // függetlenül, ez az alábbi CURL paraméter állítással kiküszöbölhető,
     // ilyenkor nincs külön SSL ellenőrzés:
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     // POST-ban küldjük az adatokat
     curl_setopt($ch, CURLOPT_POST, true);
     // Kérjük a HTTP headert a válaszba, fontos információk vannak benne
     curl_setopt($ch, CURLOPT_HEADER, true);
     // változóban tároljuk a válasz tartalmát, nem írjuk a kimenetbe
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // Beállítjuk, hol van az XML, amiből számlát szeretnénk csinálni (= file upload)
     // az xmlfile-t itt fullpath-al kell megadni
     if (!class_exists('CurlFile')) {
         curl_setopt($ch, CURLOPT_POSTFIELDS, array('action-xmlagentxmlfile' => '@' . $xmlfile));
     } else {
         curl_setopt($ch, CURLOPT_POSTFIELDS, array('action-xmlagentxmlfile' => new CurlFile($xmlfile)));
     }
     // 30 másodpercig tartjuk fenn a kapcsolatot (ha valami bökkenő volna)
     curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     // Itt állítjuk be, hogy az érkező cookie a $cookie_file-ba kerüljön mentésre
     curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
     // Ha van már cookie file-unk, és van is benne valami, elküldjük a Számlázz.hu-nak
     if (file_exists($cookie_file) && filesize($cookie_file) > 0) {
         curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
     }
     // elküldjük a kérést a Számlázz.hu felé, és eltároljuk a választ
     $agent_response = curl_exec($ch);
     // kiolvassuk a curl-ból volt-e hiba
     $http_error = curl_error($ch);
     // ezekben a változókban tároljuk a szétbontott választ
     $agent_header = '';
     $agent_body = '';
     $agent_http_code = '';
     // lekérjük a válasz HTTP_CODE-ját, ami ha 200, akkor a http kommunikáció rendben volt
     // ettől még egyáltalán nem biztos, hogy a számla elkészült
     $agent_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     // a válasz egy byte kupac, ebből az első "header_size" darab byte lesz a header
     $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
     // a header tárolása, ebben lesznek majd a számlaszám, bruttó nettó összegek, errorcode, stb.
     $agent_header = substr($agent_response, 0, $header_size);
     // a body tárolása, ez lesz a pdf, vagy szöveges üzenet
     $agent_body = substr($agent_response, $header_size);
     // a curl már nem kell, lezárjuk
     curl_close($ch);
     // a header soronként tartalmazza az információkat, egy tömbbe teszük a külön sorokat
     $header_array = explode("\n", $agent_header);
     // ezt majd true-ra állítjuk ha volt hiba
     $volt_hiba = false;
     // ebben lesznek a hiba információk, plusz a bodyban
     $agent_error = '';
     $agent_error_code = '';
     // menjünk végig a header sorokon, ami "szlahu"-val kezdődik az érdekes nekünk és írjuk ki
     foreach ($header_array as $val) {
         if (substr($val, 0, strlen('szlahu')) === 'szlahu') {
             // megvizsgáljuk, hogy volt-e hiba
             if (substr($val, 0, strlen('szlahu_error:')) === 'szlahu_error:') {
                 // sajnos volt
                 $volt_hiba = true;
                 $agent_error = substr($val, strlen('szlahu_error:'));
             }
             if (substr($val, 0, strlen('szlahu_error_code:')) === 'szlahu_error_code:') {
                 // sajnos volt
                 $volt_hiba = true;
                 $agent_error_code = substr($val, strlen('szlahu_error_code:'));
             }
         }
     }
     // ha volt http hiba dobunk egy kivételt
     $response = array();
     $response['error'] = false;
     if ($http_error != "") {
         $response['error'] = true;
         $response['messages'][] = 'Http hiba történt:' . $http_error;
         return $response;
     }
     //Delete the XML if not debug mode
     if (!get_option('wc_szamlazz_debug')) {
         unlink($xmlfile);
     } else {
         //Rename XML file for security
         $random_file_name = substr(md5(rand()), 5);
         rename($xmlfile, $location . '/' . $orderId . '-' . $random_file_name . '.xml');
     }
     if ($volt_hiba) {
         $response['error'] = true;
         // ha a számla nem készült el kiírjuk amit lehet
         $response['messages'][] = 'Agent hibakód: ' . $agent_error_code;
         $response['messages'][] = 'Agent hibaüzenet: ' . urldecode($agent_error);
         $response['messages'][] = 'Agent válasz: ' . urldecode($agent_body);
         //Update order notes
         $order->add_order_note(__('Szamlazz.hu számlakészítás sikertelen! Agent hibakód: ', 'wc-szamlazz') . $agent_error_code);
         // dobunk egy kivételt
         return $response;
     } else {
         //Get the Invoice ID from the response header
         $szlahu_szamlaszam = '';
         foreach ($header_array as $val) {
             if (substr($val, 0, strlen('szlahu_szamlaszam')) === 'szlahu_szamlaszam') {
                 $szlahu_szamlaszam = substr($val, strlen('szlahu_szamlaszam:'));
                 break;
             }
         }
         //Build response array
         $response['messages'][] = __('Számla sikeresen létrehozva és elküldve a vásárlónak emailben.', 'wc-szamlazz');
         $response['invoice_name'] = $szlahu_szamlaszam;
         //Store as a custom field
         update_post_meta($orderId, '_wc_szamlazz', $szlahu_szamlaszam);
         //Update order notes
         $order->add_order_note(__('Szamlazz.hu számla sikeresen létrehozva. A számla sorszáma: ', 'wc-szamlazz') . $szlahu_szamlaszam);
         //Download & Store PDF - generate a random file name so it will be downloadable later only by you
         $random_file_name = substr(md5(rand()), 5);
         $pdf_file_name = 'szamla_' . $random_file_name . '_' . $orderId . '.pdf';
         $pdf_file = $location . '/' . $pdf_file_name;
         file_put_contents($pdf_file, $agent_body);
         //Store the filename
         update_post_meta($orderId, '_wc_szamlazz_pdf', $pdf_file_name);
         //Return the download url
         $response['link'] = '<p><a href="' . $this->generate_download_link($orderId) . '" id="wc_szamlazz_download" class="button button-primary" target="_blank">' . __('Számla megtekintése', 'wc-szamlazz') . '</a></p>';
         return $response;
     }
 }
Exemple #9
0
    function syn_meta_box_tracking()
    {
        global $woocommerce, $post, $syn_carriers;
        $order = new WC_Order($post->ID);
        $methods = $order->get_shipping_methods();
        $default_carrier = '';
        if (!empty($methods)) {
            foreach ($methods as $method) {
                if (strpos($method['method_id'], ':') !== false) {
                    $method_id = explode(':', $method['method_id']);
                    $default_carrier = $method_id[0];
                    break;
                }
            }
        }
        $tracking_events = get_post_meta($post->ID, '_tracking_events', true);
        $tracking_number = get_post_meta($post->ID, '_tracking_number', true);
        $tracking_carrier = get_post_meta($post->ID, '_tracking_carrier', true);
        $date_shipped = get_post_meta($post->ID, '_tracking_date_shipped', true);
        if (!$date_shipped || empty($date_shipped)) {
            $date_shipped = get_post_meta($post->ID, '_date_shipped', true);
        }
        if (!$tracking_number) {
            $tracking_number = '';
        }
        if (!$tracking_carrier) {
            $tracking_carrier = $default_carrier;
        }
        if (!$date_shipped) {
            $date_shipped = time();
        }
        if (!is_array($tracking_number)) {
            $tracking_number = array($tracking_number);
        }
        if (!is_array($tracking_carrier)) {
            $tracking_carrier = array($tracking_carrier);
        }
        if (!is_array($date_shipped)) {
            $date_shipped = array($date_shipped);
        }
        $carriers = array();
        foreach ($syn_carriers as $carrier_id => $carrier) {
            $carriers[$carrier_id] = $carrier['carrier_name'];
        }
        ?>
		<style>
			.tracking_carrier{
				clear:both;
			}
			#syn-shipment-tracking .tracking_group p.first{
				float: left;
				width: 49%;
				clear: left;
				margin-top:0px;
			}
			#syn-shipment-tracking .tracking_group p.last{
				float: right;
				width: 49%;
				clear: none;
				margin-top:0px;
			}
			#syn-shipment-tracking h3.hndle{
				border-bottom: 1px solid #DDD;
			}
			#syn-shipment-tracking div.inside{
				margin: 0px;
				padding:0px;
			}
			.tracking_carrier label{
				font-size: 1em;
				display: block;
				font-weight: 600;
				margin: 0!important;
				vertical-align: middle;
				width: 100%;
			}
			.tracking_carrier select,
			.tracking_carrier input.allwidth{
				width: 100%;
			}
			.tracking_link{
				font-weight: bold;
			}
			h4#add_tracking {
				margin: 0!important;
			}
			.tracking_group{
				border-top: 1px solid #DDD;
				border-bottom: 1px solid #DFDFDF;
				padding: 10px 12px;
				position:relative;
			}
			.tracking_container{
				border-top: 1px solid #eee;
				background: #f8f8f8;
			}
			.tracking_container > .tracking_carrier:first-child{
				margin-top:0px;
			}
			.tracking_link_container{
				padding: 10px 12px;
			}
			#poststuff #syn-shipment-tracking .tracking_group a.delete_tracking_row {
				text-indent: -9999px;
				height: 1em;
				width: 1em;
				display: none;
				position: absolute;
				top: -.5em;
				right: -.5em;
				font-size: 1.4em;
			}
			#poststuff #syn-shipment-tracking .tracking_group a.delete_tracking_row:before{
				font-family:WooCommerce;
				speak:none;
				font-weight:400;
				font-variant:normal;
				text-transform:none;
				line-height:1;
				-webkit-font-smoothing:antialiased;
				margin:0;
				text-indent:0;
				position:absolute;
				top:0;
				left:0;
				width:100%;
				height:100%;
				text-align:center;
				content:"\e013";
				color:#fff;
				background-color:#000;
				-webkit-border-radius:100%;
				border-radius:100%;
				box-shadow:0 1px 2px rgba(0,0,0,.2);
			}
			#poststuff #syn-shipment-tracking .tracking_group:hover a.delete_tracking_row{
				display: block;
			}
			#poststuff #syn-shipment-tracking .tracking_group a.delete_tracking_row:hover{
				box-shadow:0 1px 2px rgba(0,0,0,0);
			}
			a.view_progress{
				clear: both;
			}
		</style>
		<script>
			var nbTracking = <?php 
        echo count($tracking_number);
        ?>
;
			jQuery(function(){
				jQuery( ".tracking_group .tracking_carrier" ).prop( "name", "syn_tracking_carrier[]" );
				jQuery("#order_status").change(function(){
					if( jQuery(this).val() == 'completed' && jQuery('#date_shipped').val() == '' ){
						var dNow = new Date();
						var localdate = dNow.getFullYear() + '-' + ("0" + (dNow.getMonth() + 1)).slice(-2) + '-' + ("0" + dNow.getDate()).slice(-2);
						jQuery('#date_shipped').val( localdate );
					}
				});
				jQuery('#syn-shipment-tracking').on('click','a.add_tracking_number',function(){
					nbTracking++;
					row = jQuery(this).data( 'row' );
					row = row.replace( new RegExp('{i}', 'g'), nbTracking );
					if( jQuery(".tracking_group").length > 0 ){
						jQuery(".tracking_group:last").after( '<div class="tracking_group tracking_container">' + row + '</div>' );
					}else{
						jQuery("#syn-shipment-tracking .inside").after( '<div class="tracking_group tracking_container">' + row + '</div>' );
					}
					jQuery( ".date-picker-field" ).datepicker({
						dateFormat: "yy-mm-dd",
						numberOfMonths: 1,
						showButtonPanel: true,
					});
					jQuery( ".tracking_group .tracking_carrier" ).prop( "name", "syn_tracking_carrier[]" );
					return false;
				});
				jQuery('#syn-shipment-tracking').on('click','a.delete_tracking_row',function(){
					$row = jQuery(this).closest('.tracking_group');
			
					var row_id = $row.attr( 'data-order_item_id' );
			
					if ( row_id ) {
						$row.append('<input type="hidden" name="delete_order_item_id[]" value="' + row_id + '" />').hide();
					} else {
						$row.remove();
					}
			
					return false;
				});
			});
		</script>
		<?php 
        foreach ($tracking_number as $key => $track_number) {
            echo '<div class="tracking_group tracking_container">';
            woocommerce_wp_select(array('id' => 'syn_tracking_carrier_' . $key, 'name' => 'syn_tracking_carrier[]', 'label' => __('Carrier', 'syn_shipping'), 'class' => 'allwidth tracking_carrier', 'wrapper_class' => 'tracking_carrier first', 'options' => $carriers, 'value' => $tracking_carrier[$key]));
            woocommerce_wp_text_input(array('id' => 'date_shipped_' . $key, 'name' => 'syn_date_shipped[]', 'label' => __('Date shipped:', 'syn_shipping'), 'placeholder' => 'YYYY-MM-DD', 'description' => '', 'class' => 'date-picker-field allwidth', 'wrapper_class' => 'tracking_carrier last', 'value' => !empty($date_shipped[$key]) ? date('Y-m-d', $date_shipped[$key]) : ''));
            woocommerce_wp_text_input(array('id' => 'tracking_number_' . $key, 'name' => 'syn_tracking_number[]', 'label' => __('Tracking number:', 'syn_shipping'), 'class' => 'allwidth', 'wrapper_class' => 'tracking_carrier', 'placeholder' => '', 'description' => '', 'value' => $tracking_number[$key]));
            if (!empty($tracking_number[$key]) && isset($syn_carriers[$tracking_carrier[$key]])) {
                $link = sprintf($syn_carriers[$tracking_carrier[$key]]['tracking_url'], $tracking_number[$key]);
                echo sprintf('<a href="%s" target="_blank" class="tracking_link">' . __('Track this shipment', 'syn_shipping') . '</a>', $link);
            }
            /*
            if( isset( $tracking_events[ $tracking_number[ $key ] ] ) && ! empty( $tracking_events[ $tracking_number[ $key ] ] ) ){
            				if( $tracking_events[ $tracking_number[ $key ] ][ 'delivered' ] )
            					echo( '<span style="float:right;">DELIVERED</span>' );
            			}
            */
            echo '<a href="#" class="delete_tracking_row">×</a><div class="clear"></div></div>';
        }
        ob_start();
        woocommerce_wp_select(array('id' => 'syn_tracking_carrier_{i}', 'name' => 'syn_tracking_carrier[]', 'label' => __('Carrier', 'syn_shipping'), 'class' => 'allwidth tracking_carrier', 'wrapper_class' => 'tracking_carrier first', 'options' => $carriers, 'value' => $default_carrier));
        woocommerce_wp_text_input(array('id' => 'syn_date_shipped_{i}', 'name' => 'syn_date_shipped[]', 'label' => __('Date shipped:', 'syn_shipping'), 'placeholder' => 'YYYY-MM-DD', 'description' => '', 'class' => 'date-picker-field allwidth', 'wrapper_class' => 'tracking_carrier last', 'value' => date('Y-m-d')));
        woocommerce_wp_text_input(array('id' => 'tracking_number_{i}', 'name' => 'syn_tracking_number[]', 'label' => __('Tracking number:', 'syn_shipping'), 'class' => 'allwidth', 'wrapper_class' => 'tracking_carrier', 'placeholder' => '', 'description' => '', 'value' => ''));
        echo '<a href="#" class="delete_tracking_row">×</a><div class="clear"></div>';
        $template = htmlentities(ob_get_clean());
        echo '<div class="tracking_link_container"><h4 id="add_tracking"><a href="#" class="add_tracking_number" data-row="' . $template . '">+ ' . __('Add tracking number', 'syn_shipping') . ' <span class="tips" data-tip="' . __('You can add multiple tracking for this order.', 'syn_shipping') . '">[?]</span></a></a></h4></div>';
    }
 /**
  * HTML for checkout recipient page / emails etc.
  *
  * @param string $content
  * @param WC_Order $wc_order
  * @return string
  */
 static function checkout_order_shipping_to_display_shipped_via($content, $wc_order)
 {
     $shipping_methods = $wc_order->get_shipping_methods();
     foreach ($shipping_methods as $id => $shipping_method) {
         if ($shipping_method['method_id'] == self::ID . ':servicepakke' && key_exists('fraktguiden_pickup_point_info_cached', $shipping_method) && $shipping_method['fraktguiden_pickup_point_info_cached']) {
             $info = $shipping_method['fraktguiden_pickup_point_info_cached'];
             $content = $content . '<div class="bring-order-details-pickup-point"><div class="bring-order-details-selected-text">' . self::get_i18n()['PICKUP_POINT'] . ':</div><div class="bring-order-details-info-text">' . str_replace("|", '<br>', $info) . '</div></div>';
         }
     }
     return $content;
 }
 public function maybe_create_subscription($order_id)
 {
     if (empty(MP_Integration::$api_key)) {
         return;
     }
     $is_subscription = WC()->session->get('mp_is_sub');
     if ($is_subscription) {
         update_post_meta($order_id, 'mp_order_type', 'new');
         $renewal_frequency = WC()->session->get('mp_sub_freq');
         update_post_meta($order_id, 'mp_frequency', $renewal_frequency);
         $order = new WC_Order($order_id);
         $customer = $order->get_user();
         $order_items = $order->get_items();
         $subscription_items = array();
         foreach ($order_items as $item_id => $item) {
             $subscription_items[] = array('productId' => (int) $item['product_id'], 'variationId' => (int) $item['variation_id'], 'quantity' => (int) $item['qty'], 'discountPercent' => 0);
         }
         $first_name = $customer->first_name;
         if (empty($first_name)) {
             $first_name = $order->billing_first_name;
         }
         $last_name = $customer->last_name;
         if (empty($last_name)) {
             $last_name = $order->billing_last_name;
         }
         $shipping_methods = $order->get_shipping_methods();
         $shipping_method_id = null;
         $shipping_method_name = null;
         $shipping_cost = 0;
         if (!empty($shipping_methods)) {
             $shipping_method_id = key($shipping_methods);
             $shipping_method = $shipping_methods[$shipping_method_id];
             $shipping_method_name = $shipping_method['name'];
             $shipping_cost = $shipping_method['cost'];
         }
         $data = array('apiKey' => MP_Integration::$api_key, 'subscription' => array('renewalFrequencyId' => $renewal_frequency, 'shippingMethodId' => $shipping_method_id, 'shippingMethodName' => $shipping_method_name, 'shippingCost' => $shipping_cost), 'customer' => array('externalId' => $customer->ID, 'email' => $customer->user_email, 'firstName' => $first_name, 'lastName' => $last_name), 'order' => array('orderId' => $order_id, 'orderTypeId' => 'new', 'orderDate' => $order->order_date), 'subscriptionItems' => $subscription_items);
         $data_json = json_encode(array($data));
         $ch = curl_init(MP_Environment::MP_URL . '/methods/api_CreateNewSubscription');
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
         curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_json)));
         $subscription_id = null;
         $response = json_decode(curl_exec($ch));
         if (curl_errno($ch)) {
             // TODO - error handling
             echo curl_error($ch);
             exit;
         } else {
             if (is_object($response)) {
                 // TODO - error handling
                 var_dump($response);
                 exit;
             } else {
                 $subscription_id = $response;
             }
         }
         curl_close($ch);
         if (!empty($subscription_id)) {
             update_post_meta($order_id, 'mp_subscription_id', $subscription_id);
             update_user_meta($customer->ID, 'mp_subscription_id', $subscription_id);
         }
     }
 }
 /**
  * Get the order data for the given ID.
  *
  * @since  2.5.0
  * @param  WC_Order $order The order instance
  * @return array
  */
 protected function get_order_data($order)
 {
     $order_post = get_post($order->id);
     $dp = wc_get_price_decimals();
     $order_data = array('id' => $order->id, 'order_number' => $order->get_order_number(), 'created_at' => $this->format_datetime($order_post->post_date_gmt), 'updated_at' => $this->format_datetime($order_post->post_modified_gmt), 'completed_at' => $this->format_datetime($order->completed_date, true), 'status' => $order->get_status(), 'currency' => $order->get_order_currency(), 'total' => wc_format_decimal($order->get_total(), $dp), 'subtotal' => wc_format_decimal($order->get_subtotal(), $dp), 'total_line_items_quantity' => $order->get_item_count(), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'total_discount' => wc_format_decimal($order->get_total_discount(), $dp), 'shipping_methods' => $order->get_shipping_method(), 'payment_details' => array('method_id' => $order->payment_method, 'method_title' => $order->payment_method_title, 'paid' => isset($order->paid_date)), 'billing_address' => array('first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address_1' => $order->billing_address_1, 'address_2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postcode' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email, 'phone' => $order->billing_phone), 'shipping_address' => array('first_name' => $order->shipping_first_name, 'last_name' => $order->shipping_last_name, 'company' => $order->shipping_company, 'address_1' => $order->shipping_address_1, 'address_2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postcode' => $order->shipping_postcode, 'country' => $order->shipping_country), 'note' => $order->customer_note, 'customer_ip' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'customer_id' => $order->get_user_id(), 'view_order_url' => $order->get_view_order_url(), 'line_items' => array(), 'shipping_lines' => array(), 'tax_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array());
     // add line items
     foreach ($order->get_items() as $item_id => $item) {
         $product = $order->get_product_from_item($item);
         $product_id = null;
         $product_sku = null;
         // Check if the product exists.
         if (is_object($product)) {
             $product_id = isset($product->variation_id) ? $product->variation_id : $product->id;
             $product_sku = $product->get_sku();
         }
         $meta = new WC_Order_Item_Meta($item, $product);
         $item_meta = array();
         foreach ($meta->get_formatted(null) as $meta_key => $formatted_meta) {
             $item_meta[] = array('key' => $meta_key, 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']);
         }
         $order_data['line_items'][] = array('id' => $item_id, 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : null, 'name' => $item['name'], 'product_id' => $product_id, 'sku' => $product_sku, 'meta' => $item_meta);
     }
     // Add shipping.
     foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
         $order_data['shipping_lines'][] = array('id' => $shipping_item_id, 'method_id' => $shipping_item['method_id'], 'method_title' => $shipping_item['name'], 'total' => wc_format_decimal($shipping_item['cost'], $dp));
     }
     // Add taxes.
     foreach ($order->get_tax_totals() as $tax_code => $tax) {
         $order_data['tax_lines'][] = array('id' => $tax->id, 'rate_id' => $tax->rate_id, 'code' => $tax_code, 'title' => $tax->label, 'total' => wc_format_decimal($tax->amount, $dp), 'compound' => (bool) $tax->is_compound);
     }
     // Add fees.
     foreach ($order->get_fees() as $fee_item_id => $fee_item) {
         $order_data['fee_lines'][] = array('id' => $fee_item_id, 'title' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : null, 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp));
     }
     // Add coupons.
     foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {
         $order_data['coupon_lines'][] = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp));
     }
     $order_data = apply_filters('woocommerce_cli_order_data', $order_data);
     return $this->flatten_array($order_data);
 }
 function typograffit_woocommerce_payment_complete($order_id)
 {
     //OK
     if (isset($order_id)) {
         $order = new WC_Order($order_id);
         //Create Printful API Object
         $pf = new Printful_Client(API_KEY);
         //ITEMS
         $items = $order->get_items();
         $items_arr = array();
         $shippingMethods = $order->get_shipping_methods();
         foreach ($shippingMethods as $methds) {
             $wc_shippingMethod = $methds['method_id'];
         }
         $shippingMethod = str_replace('printful_shipping_', '', $wc_shippingMethod);
         foreach ($items as $item) {
             $product_id = $item['product_id'];
             $product_author = $this->getAuthor($product_id);
             //create JSON every products
             $product_name = $item['name'];
             $product_variation_id = $item['variation_id'];
             $qty = $item['qty'];
             $size = $item['pa_size'];
             $hashLine = $this->getPostName($product_id);
             $enlarge_image_url = '';
             if ($product_author == 999) {
                 //this is 'Custom Product'.
                 if (isset($size)) {
                     //this is 'T-shirt'.
                     //$thumbnailSize = $this->getThumbnailSize( $size );
                     $printful_variant_id = $this->getPrintfulVarId($size);
                     //$preview_thumbnail_id = get_post_meta($product_variation_id, '_thumbnail_id', true);
                     if ($size == 'xs' || $size == 'xs-ja') {
                         $enlarge_image_url = 'http://typograffit.com/wp-content/uploads/typo/' . $hashLine . '/enlarge_10_12.png';
                     } else {
                         $enlarge_image_url = 'http://typograffit.com/wp-content/uploads/typo/' . $hashLine . '/enlarge_12_16.png';
                     }
                     //$front_thumbnail_id = get_post_meta($product_id, '_typogenerated_id', true);
                     //$front_thumbnail_att = wp_get_attachment_image_src($front_thumbnail_id,'full');
                     $preview_thumbnail_id = get_post_meta($product_id, '_thumbnail_id', true);
                     $preview_thumbnail_att = wp_get_attachment_image_src($preview_thumbnail_id, 'full');
                 }
             } elseif ($product_author == 998) {
                 //this is 'Tote'.
                 //$thumbnailSize = '';
                 $printful_variant_id = '863';
                 $enlarge_image_url = 'http://typograffit.com/wp-content/uploads/typo/' . $hashLine . '/enlarge_10_12.png';
                 //$front_thumbnail_id = get_post_meta($product_id, '_typogenerated_id', true);
                 //$front_thumbnail_att = wp_get_attachment_image_src($front_thumbnail_id,'full');
                 $preview_thumbnail_id = get_post_meta($product_id, '_thumbnail_id', true);
                 $preview_thumbnail_att = wp_get_attachment_image_src($preview_thumbnail_id, 'full');
             } else {
                 //This is 'Store Product'.
                 $printful_variant_id = $product_variation_id;
                 /* Q. NO front image */
                 //$front_thumbnail_att = wp_get_attachment_image_src($front_thumbnail_id,'full');
                 $preview_thumbnail_id = get_post_meta($product_id, '_thumbnail_id', true);
                 $preview_thumbnail_att = wp_get_attachment_image_src($preview_thumbnail_id, 'full');
             }
             $item_arr = array('variant_id' => $printful_variant_id, 'name' => $product_name, 'quantity' => $qty, 'files' => array(array('url' => $enlarge_image_url), array('type' => 'preview', 'url' => $preview_thumbnail_att[0])));
             array_push($items_arr, $item_arr);
         }
         //SHIPPING ADDRESS
         $shipping_first_name = $order->shipping_first_name;
         $shipping_last_name = $order->shipping_last_name;
         $shipping_name = $shipping_first_name . ' ' . $shipping_last_name;
         $shipping_address = $order->shipping_address_1 . ' ' . $order->shipping_address_2;
         $shipping_city = $order->shipping_city;
         $shipping_state_code = $order->shipping_state;
         $shipping_country_code = $order->shipping_country;
         $shipping_zip = $order->shipping_postcode;
         //check in local env
         $order_json = array('external_id' => $order_id, 'shipping' => $shippingMethod, 'recipient' => array('name' => $shipping_name, 'address1' => $shipping_address, 'city' => $shipping_city, 'state_code' => $shipping_state_code, 'country_code' => $shipping_country_code, 'zip' => $shipping_zip), 'items' => $items_arr);
         $filename = dirname(__FILE__) . '/json.txt';
         $fp = fopen($filename, 'a') or dir('cannot open');
         fwrite($fp, sprintf(json_encode($order_json)));
         fclose($fp);
         //POST to Printful API
         $order_arr = $pf->post('orders', array('external_id' => $order_id, 'shipping' => $shippingMethod, 'recipient' => array('name' => $shipping_name, 'address1' => $shipping_address, 'city' => $shipping_city, 'state_code' => $shipping_state_code, 'country_code' => $shipping_country_code, 'zip' => $shipping_zip), 'items' => $items_arr));
     } else {
         error_log("ERROR : No Order ID");
     }
 }
Exemple #14
0
function handlePaymentCompleted($order_id)
{
    echo "-- handlePaymentCompleted";
    $order = new WC_Order($order_id);
    $customer = new WC_Customer($order_id);
    $addresses = $order->get_address("shipping");
    /*
    $To = get_option('admin_email').",dev_support@soixanteseize.com";
        $Objet = $email_heading = "Vérifiez la commande ".$order_id;
        $message = $response[1];
        ob_start();
        include(COURIIERPATH.'views/mails/woo-couriier-order-ready.php');
        $Body = ob_get_clean();
        trace($Body);
        //sendCC($To, $Objet, $Body);
    
        return;
    */
    $adresse = $addresses["address_1"] . ", ";
    if ($addresses["address_2"] != "") {
        $adresse .= $addresses["address_2"] . ", ";
    }
    $adresse .= $addresses["city"] . " ";
    $adresse .= $addresses["postcode"] . " ";
    //$postcode = $addresses["postcode"];
    //trace($order);
    //trace($customer);
    //trace($order->get_address("shipping") );
    //trace($adresse);
    $chosen_methods = $order->get_shipping_methods();
    if (count($chosen_methods) > 0) {
        //$la_methode = object();
        foreach ($chosen_methods as $c_method) {
            //                trace($method);
            $chosen_method = $c_method['item_meta']['method_id'][0];
        }
        //trace($chosen_method);
        $available_methods = WC()->session->get('shipping_methods_' . $addresses["postcode"]);
        //trace($available_methods);
        $offerIdTarifs = '';
        foreach ($available_methods as $method) {
            //trace($method->speed);
            switch ($method->speed) {
                case 2:
                    if ($chosen_method == 'couriier_classic_shipping_method') {
                        $offerIdTarifs = $method->ref;
                    }
                    break;
                case 1:
                    if ($chosen_method == 'couriier_rapide_shipping_method') {
                        $offerIdTarifs = $method->ref;
                    }
                    break;
                case 0:
                    if ($chosen_method == 'couriier_flash_shipping_method') {
                        $offerIdTarifs = $method->ref;
                    }
                    break;
            }
        }
        //return;
        $adresse = $customer->get_address() . " " . $customer->get_postcode() . ", " . $customer->get_city();
        $recipientLatLng = geoloc($adresse);
        //trace($customer);
        //trace($recipientLatLng);
        //trace($offerIdTarifs);
        //return;
        $body = array(array('offerIdTarifs' => $offerIdTarifs, 'pickupName' => get_bloginfo("name"), 'pickupLatitude' => PICKUPLAT, 'pickupLongitude' => PICKUPLNG, 'pickupAddress' => PICKUPADRESSE, 'pickupAddress2' => "test", 'pickupTel' => PICKUPTEL, 'pickupZip' => PICKUPZIP, 'pickupCity' => PICKUPCITY, 'recipientName' => $order->get_formatted_shipping_full_name(), 'recipientLatitude' => $recipientLatLng["lat"], 'recipientLongitude' => $recipientLatLng["lng"], 'recipientAddress' => $addresses["address_1"], 'recipientAddress2' => $addresses["address_2"], 'recipientTel' => $order->billing_phone, 'recipientZip' => $addresses["postcode"], 'recipientCity' => $addresses["city"], 'timeManagement' => "2015-04-24 00:00:00", 'deliveryType' => "En main propre"));
        //trace($body);
        //return;
        $body = json_encode($body);
        $url = COURIIER_WS . '/orders';
        //trace($url);
        $response = api_call_post($url, $body);
        //trace($response);
        $response = json_decode($response['body']);
        //trace($response);
        $couriier_order_id = $response[0]->id;
        //trace($order_id);
        //return;
        if ($couriier_order_id) {
            /**
                url_order_follow
                    **/
            $url_order_follow = $response[0]->following_url;
            //trace($url_order_follow);
            if ($url_order_follow) {
                $To = $order->billing_email;
                $Objet = $email_heading = "Votre lien pour suivre la livraison Couriier";
                ob_start();
                include COURIIERPATH . 'views/mails/woo-couriier-order-follow.php';
                $Body = ob_get_clean();
                sendCC($To, $Objet, $Body);
            }
            /**
                url_order_ready
                    **/
            $url_rest_order_ready = get_bloginfo("url") . '/wc-api/couriier-order-ready?order_id=' . $order_id . '&couriier_order_id=' . $couriier_order_id;
            //$url_order_ready = COURIIER_WS.'/order/'.$couriier_order_id.'/ready';
            //trace($url_rest_order_ready);
            //return;
            $To = get_option('admin_email') . ",dev_support@soixanteseize.com";
            $Objet = $email_heading = "Votre lien pour lancer la livraison Couriier";
            ob_start();
            include COURIIERPATH . 'views/mails/woo-couriier-order-ready.php';
            $Body = ob_get_clean();
            //trace($Body);
            sendCC($To, $Objet, $Body);
            //return;
        }
    } else {
        $To = get_option('admin_email') . ",dev_support@soixanteseize.com";
        $Objet = $email_heading = "U+026A0 Vérifiez la commande " . $order_id;
        $message = $response[1];
        ob_start();
        include COURIIERPATH . 'views/mails/woo-couriier-blank.php';
        $Body = ob_get_clean();
        //trace($Body);
        sendCC($To, $Objet, $Body);
    }
    //sendCC($To, $Objet, $Body);
}
Exemple #15
0
 /**
  * Test: get_shipping_methods
  */
 function test_get_shipping_methods()
 {
     $object = new WC_Order();
     $rate = new WC_Shipping_Rate('flat_rate_shipping', 'Flat rate shipping', '10', array(), 'flat_rate');
     $item = new WC_Order_Item_Shipping();
     $item->set_props(array('method_title' => $rate->label, 'method_id' => $rate->id, 'total' => wc_format_decimal($rate->cost), 'taxes' => $rate->taxes, 'meta_data' => $rate->get_meta_data()));
     $object->add_item($item);
     $object->save();
     $this->assertCount(1, $object->get_shipping_methods());
 }
Exemple #16
0
/**
 * Create shipping for a sub-order if neccessary
 *
 * @param WC_Order $parent_order
 * @param int $order_id
 * @param array $product_ids
 * @return type
 */
function dokan_create_sub_order_shipping($parent_order, $order_id, $seller_products)
{
    // take only the first shipping method
    $shipping_methods = $parent_order->get_shipping_methods();
    $shipping_method = is_array($shipping_methods) ? reset($shipping_methods) : array();
    // bail out if no shipping methods found
    if (!$shipping_method) {
        return;
    }
    $shipping_products = array();
    $packages = array();
    // emulate shopping cart for calculating the shipping method
    foreach ($seller_products as $product_item) {
        $product = get_product($product_item['product_id']);
        if ($product->needs_shipping()) {
            $shipping_products[] = array('product_id' => $product_item['product_id'], 'variation_id' => $product_item['variation_id'], 'variation' => '', 'quantity' => $product_item['qty'], 'data' => $product, 'line_total' => $product_item['line_total'], 'line_tax' => $product_item['line_tax'], 'line_subtotal' => $product_item['line_subtotal'], 'line_subtotal_tax' => $product_item['line_subtotal_tax']);
        }
    }
    if ($shipping_products) {
        $package = array('contents' => $shipping_products, 'contents_cost' => array_sum(wp_list_pluck($shipping_products, 'line_total')), 'applied_coupons' => array(), 'destination' => array('country' => $parent_order->shipping_country, 'state' => $parent_order->shipping_state, 'postcode' => $parent_order->shipping_postcode, 'city' => $parent_order->shipping_city, 'address' => $parent_order->shipping_address_1, 'address_2' => $parent_order->shipping_address_2));
        $wc_shipping = WC_Shipping::instance();
        $pack = $wc_shipping->calculate_shipping_for_package($package);
        if (array_key_exists($shipping_method['method_id'], $pack['rates'])) {
            $method = $pack['rates'][$shipping_method['method_id']];
            $cost = wc_format_decimal($method->cost);
            $item_id = wc_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'shipping'));
            if ($item_id) {
                wc_add_order_item_meta($item_id, 'method_id', $method->id);
                wc_add_order_item_meta($item_id, 'cost', $cost);
            }
            return $cost;
        }
    }
    return 0;
}
 /**
  * When a new order is inserted, add subscriptions related order meta.
  *
  * @since 1.0
  */
 public static function add_order_meta($order_id, $posted)
 {
     global $woocommerce;
     if (!WC_Subscriptions_Cart::cart_contains_subscription_renewal('child') && WC_Subscriptions_Order::order_contains_subscription($order_id)) {
         // This works because the 'woocommerce_add_order_item_meta' runs before the 'woocommerce_checkout_update_order_meta' hook
         // Set the recurring totals so totals display correctly on order page
         update_post_meta($order_id, '_order_recurring_discount_cart', WC_Subscriptions_Cart::get_recurring_discount_cart());
         update_post_meta($order_id, '_order_recurring_discount_cart_tax', WC_Subscriptions_Cart::get_recurring_discount_cart_tax());
         update_post_meta($order_id, '_order_recurring_discount_total', WC_Subscriptions_Cart::get_recurring_discount_total());
         update_post_meta($order_id, '_order_recurring_shipping_tax_total', WC_Subscriptions_Cart::get_recurring_shipping_tax_total());
         update_post_meta($order_id, '_order_recurring_shipping_total', WC_Subscriptions_Cart::get_recurring_shipping_total());
         update_post_meta($order_id, '_order_recurring_tax_total', WC_Subscriptions_Cart::get_recurring_total_tax());
         update_post_meta($order_id, '_order_recurring_total', WC_Subscriptions_Cart::get_recurring_total());
         // Set the recurring payment method - it starts out the same as the original by may change later
         update_post_meta($order_id, '_recurring_payment_method', get_post_meta($order_id, '_payment_method', true));
         update_post_meta($order_id, '_recurring_payment_method_title', get_post_meta($order_id, '_payment_method_title', true));
         $order = new WC_Order($order_id);
         $order_fees = $order->get_fees();
         // the fee order items have already been set, we just need to to add the recurring total meta
         $cart_fees = $woocommerce->cart->get_fees();
         foreach ($order->get_fees() as $item_id => $order_fee) {
             // Find the matching fee in the cart
             foreach ($cart_fees as $fee_index => $cart_fee) {
                 if (sanitize_title($order_fee['name']) == $cart_fee->id) {
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_total', wc_format_decimal($cart_fee->recurring_amount));
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', wc_format_decimal($cart_fee->recurring_tax));
                     unset($cart_fees[$fee_index]);
                     break;
                 }
             }
         }
         // Get recurring taxes into same format as _order_taxes
         $order_recurring_taxes = array();
         foreach (WC_Subscriptions_Cart::get_recurring_taxes() as $tax_key => $tax_amount) {
             $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => WC_Tax::get_rate_code($tax_key), 'order_item_type' => 'recurring_tax'));
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'rate_id', $tax_key);
                 wc_add_order_item_meta($item_id, 'label', WC_Tax::get_rate_label($tax_key));
                 wc_add_order_item_meta($item_id, 'compound', absint(WC_Tax::is_compound($tax_key) ? 1 : 0));
                 wc_add_order_item_meta($item_id, 'tax_amount', wc_format_decimal(isset(WC()->cart->recurring_taxes[$tax_key]) ? WC()->cart->recurring_taxes[$tax_key] : 0));
                 wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_format_decimal(isset(WC()->cart->recurring_shipping_taxes[$tax_key]) ? WC()->cart->recurring_shipping_taxes[$tax_key] : 0));
             }
         }
         $payment_gateways = $woocommerce->payment_gateways->payment_gateways();
         if ('yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments', 'no')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         } elseif (isset($payment_gateways[$posted['payment_method']]) && !$payment_gateways[$posted['payment_method']]->supports('subscriptions')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         }
         $cart_item = WC_Subscriptions_Cart::cart_contains_subscription_renewal();
         if (isset($cart_item['subscription_renewal']) && 'parent' == $cart_item['subscription_renewal']['role']) {
             update_post_meta($order_id, '_original_order', $cart_item['subscription_renewal']['original_order']);
         }
         // WC 2.1+
         if (!WC_Subscriptions::is_woocommerce_pre('2.1')) {
             // Recurring coupons
             if ($applied_coupons = $woocommerce->cart->get_coupons()) {
                 foreach ($applied_coupons as $code => $coupon) {
                     if (!isset($woocommerce->cart->recurring_coupon_discount_amounts[$code])) {
                         continue;
                     }
                     $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'recurring_coupon'));
                     // Add line item meta
                     if ($item_id) {
                         woocommerce_add_order_item_meta($item_id, 'discount_amount', isset($woocommerce->cart->recurring_coupon_discount_amounts[$code]) ? $woocommerce->cart->recurring_coupon_discount_amounts[$code] : 0);
                     }
                 }
             }
             // Add recurring shipping order items
             if (WC_Subscriptions_Cart::cart_contains_subscriptions_needing_shipping()) {
                 $packages = $woocommerce->shipping->get_packages();
                 $checkout = $woocommerce->checkout();
                 foreach ($packages as $i => $package) {
                     if (isset($package['rates'][$checkout->shipping_methods[$i]])) {
                         $method = $package['rates'][$checkout->shipping_methods[$i]];
                         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'recurring_shipping'));
                         if ($item_id) {
                             woocommerce_add_order_item_meta($item_id, 'method_id', $method->id);
                             woocommerce_add_order_item_meta($item_id, 'cost', WC_Subscriptions::format_total($method->cost));
                             woocommerce_add_order_item_meta($item_id, 'taxes', array_map('wc_format_decimal', $method->taxes));
                             do_action('woocommerce_subscriptions_add_recurring_shipping_order_item', $order_id, $item_id, $i);
                         }
                     }
                 }
             }
             // Remove shipping on original order if it was added but is not required
             if (!WC_Subscriptions_Cart::charge_shipping_up_front()) {
                 foreach ($order->get_shipping_methods() as $order_item_id => $shipping_method) {
                     woocommerce_update_order_item_meta($order_item_id, 'cost', WC_Subscriptions::format_total(0));
                 }
             }
         } else {
             update_post_meta($order_id, '_recurring_shipping_method', get_post_meta($order_id, '_shipping_method', true), true);
             update_post_meta($order_id, '_recurring_shipping_method_title', get_post_meta($order_id, '_shipping_method_title', true), true);
         }
     }
 }
 /**
  * Returns Fraktguiden shipping method items.
  *
  * @return array
  */
 public function get_fraktguiden_shipping_items()
 {
     $result = [];
     $shipping_methods = $this->order->get_shipping_methods();
     foreach ($shipping_methods as $item_id => $shipping_method) {
         $method_id = wc_get_order_item_meta($item_id, 'method_id', true);
         if (strpos($method_id, Fraktguiden_Helper::ID) !== false) {
             $result[$item_id] = $shipping_method;
         }
     }
     return $result;
 }