shipping
 options
 :service => 'DOM.EP'
 :notification_email
 :packing_instructions
 :show_postage_rate
 :cod, :cod_amount, :insurance, :insurance_amount, :signature_required, :pa18, :pa19, :hfp, :dns, :lad
12854
def build_shipment_request(origin, destination, package, line_items = [], options = {})
      builder = Nokogiri::XML::Builder.new do |xml|
        xml.public_send('non-contract-shipment', :xmlns => "http://www.canadapost.ca/ws/ncshipment") do
          xml.public_send('delivery-spec') do
            shipment_service_code_node(xml, options)
            shipment_sender_node(xml, origin, options)
            shipment_destination_node(xml, destination, options)
            shipment_options_node(xml, options)
            shipment_parcel_node(xml, package)
            shipment_notification_node(xml, options)
            shipment_preferences_node(xml, options)
            references_node(xml, options)             # optional > user defined custom notes
            shipment_customs_node(xml, destination, line_items, options)
            # COD Remittance defaults to sender
          end
        end
      end
      builder.to_xml
    end
960322
def _check_response_for_request_errors(self):
        
        if self.response.HighestSeverity == "ERROR":
            for notification in self.response.Notifications:  # pragma: no cover
                if notification.Severity == "ERROR":
                    if "Postal Code Not Found" in notification.Message:
                        raise FedexPostalCodeNotFound(notification.Code,
                                                      notification.Message)

                    elif "Invalid Postal Code Format" in self.response.Notifications:
                        raise FedexInvalidPostalCodeFormat(notification.Code,
                                                           notification.Message)
                    else:
                        raise FedexError(notification.Code,
                                         notification.Message)
1273540
def calculate_shipping_package
      
      store_config = invoice.site.store_config            
      if !store_config.auto_calculate_packages                        
        return self.custom_shipping_package(store_config, self)        
      end
      
      variants = self.line_items.sort_by{ |li| li.quantity * (li.variant.volume ? li.variant.volume : 0.00) * -1 }.collect{ |li| li.variant.downloadable ? nil : li.variant }.reject{ |v| v.nil? }      
      ShippingPackage.where(:site_id => self.invoice.site_id).reorder(:flat_rate_price).all.each do |sp|
        if sp.fits(variants)
          self.shipping_package_id = sp.id
          self.save
          return true          
        end 
      end                    
      Caboose.log("Error: line item #{li.id} (#{li.variant.product.title}) does not fit into any package.")
      return false
    end
224103
function quote($method = '') {
    global $order, $shipping_weight, $shipping_num_boxes, $total_count;

    // shipping adjustment
    switch (MODULE_SHIPPING_TABLE_MODE) {
      case ('price'):
        $order_total = $_SESSION['cart']->show_total() - $_SESSION['cart']->free_shipping_prices() ;
        break;
      case ('weight'):
        $order_total = $shipping_weight;
        break;
      case ('item'):
        $order_total = $total_count - $_SESSION['cart']->free_shipping_items();
        break;
    }

    $order_total_amount = $_SESSION['cart']->show_total() - $_SESSION['cart']->free_shipping_prices() ;

    $table_cost = preg_split("/[:,]/" , MODULE_SHIPPING_TABLE_COST);
    $size = sizeof($table_cost);
    for ($i=0, $n=$size; $i<$n; $i+=2) {
      if (round($order_total,9) <= $table_cost[$i]) {
        if (strstr($table_cost[$i+1], '%')) {
          $shipping = ($table_cost[$i+1]/100) * $order_total_amount;
        } else {
          $shipping = $table_cost[$i+1];
        }
        break;
      }
    }

    if (MODULE_SHIPPING_TABLE_MODE == 'weight') {
      $shipping = $shipping * $shipping_num_boxes;
      // show boxes if weight
      switch (SHIPPING_BOX_WEIGHT_DISPLAY) {
        case (0):
        $show_box_weight = '';
        break;
        case (1):
        $show_box_weight = ' (' . $shipping_num_boxes . ' ' . TEXT_SHIPPING_BOXES . ')';
        break;
        case (2):
        $show_box_weight = ' (' . number_format($shipping_weight * $shipping_num_boxes,2) . TEXT_SHIPPING_WEIGHT . ')';
        break;
        default:
        $show_box_weight = ' (' . $shipping_num_boxes . ' x ' . number_format($shipping_weight,2) . TEXT_SHIPPING_WEIGHT . ')';
        break;
      }
    }

    $this->quotes = array('id' => $this->code,
    'module' => MODULE_SHIPPING_TABLE_TEXT_TITLE . $show_box_weight,
    'methods' => array(array('id' => $this->code,
    'title' => MODULE_SHIPPING_TABLE_TEXT_WAY,
    'cost' => $shipping + (MODULE_SHIPPING_TABLE_HANDLING_METHOD == 'Box' ? MODULE_SHIPPING_TABLE_HANDLING * $shipping_num_boxes : MODULE_SHIPPING_TABLE_HANDLING) ) ));

    if ($this->tax_class > 0) {
      $this->quotes['tax'] = zen_get_tax_rate($this->tax_class, $order->delivery['country']['id'], $order->delivery['zone_id']);
    }

    if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title);

    return $this->quotes;
  }
400073
def _build_params(self):
        ''' 
        '''
        params = {}
        params['email'] = self.email
        params['token'] = self.token
        params['currency'] = self.currency

        # Atributos opcionais
        if self.receiver_email:
            params['receiver_email'] = self.receiver_email
        if self.reference:
            params['reference'] = self.reference
        if self.extra_amount:
            params['extra_amount'] = self.extra_amount
        if self.redirect_url:
            params['redirect_url'] = self.redirect_url
        if self.notification_url:
            params['notification_url'] = self.notification_url
        if self.max_uses:
            params['max_uses'] = self.max_uses
        if self.max_age:
            params['max_age'] = self.max_age

        #TODO: Incluir metadata aqui

        # Itens
        for index, item in enumerate(self.items, start=1):
            params['itemId%d' % index] = item['item_id']
            params['itemDescription%d' % index] = item['description']
            params['itemAmount%d' % index] = '%.2f' % item['amount']
            params['itemQuantity%s' % index] = item['quantity']
            if item.get('shipping_cost'):
                params['itemShippingCost%d' % index] = item['shipping_cost']
            if item.get('weight'):
                params['itemWeight%d' % index] = item['weight']

        # Sender
        if self.client.get('email'):
            params['senderEmail'] = self.client.get('email')
        if self.client.get('name'):
            params['senderName'] = ' '.join(self.client.get('name').split())
        if self.client.get('phone_area_code'):
            params['senderAreaCode'] = self.client.get('phone_area_code')
        if self.client.get('phone_number'):
            params['senderPhone'] = self.client.get('phone_number')
        if self.client.get('cpf'):
            params['senderCPF'] = self.client.get('cpf')
        if self.client.get('sender_born_date'):
            params['senderBornDate'] = self.client.get('sender_born_date')

        # Shipping
        if self.shipping.get('type'):
            params['shippingType'] = self.shipping.get('type')
        if self.shipping.get('cost'):
            params['shippingCost'] = '%.2f' % self.shipping.get('cost')
        if self.shipping.get('country'):
            params['shippingAddressCountry'] = self.shipping.get('country')
        if self.shipping.get('state'):
            params['shippingAddressState'] = self.shipping.get('state')
        if self.shipping.get('city'):
            params['shippingAddressCity'] = self.shipping.get('city')
        if self.shipping.get('postal_code'):
            params['shippingAddressPostalCode'] = self.shipping.get('postal_code')
        if self.shipping.get('district'):
            params['shippingAddressDistrict'] = self.shipping.get('district')
        if self.shipping.get('street'):
            params['shippingAddressStreet'] = self.shipping.get('street')
        if self.shipping.get('number'):
            params['shippingAddressNumber'] = self.shipping.get('number')
        if self.shipping.get('complement'):
            params['shippingAddressComplement'] = self.shipping.get('complement')

        return params
885488
def admin_update_line_item
      return if !user_is_allowed('orders', 'edit')
      
      resp = Caboose::StdClass.new({'attributes' => {}})
      li = OrderLineItem.find(params[:id])    
      
      save = true
      send_status_email = false    
      params.each do |name,value|
        case name
          when 'quantity'
            li.quantity = value
            li.save
                      	  
            # Recalculate everything
            r = ShippingCalculator.rate(li.order, li.order.shipping_method_code)
            li.order.shipping = r['negotiated_rate'] / 100
            li.order.handling = (r['negotiated_rate'] / 100) * 0.05
            tax_rate = TaxCalculator.tax_rate(li.order.shipping_address)
            li.order.tax = li.order.subtotal * tax_rate
            li.order.calculate_total
            li.order.save
            
          when 'tracking_number'
            li.tracking_number = value
            send_status_email = true
          when 'status'
            li.status = value
            resp.attributes['status'] = {'text' => value}
            send_status_email = true
        end
      end
      if send_status_email       
        OrdersMailer.customer_status_updated(li.order).deliver
      end
      resp.success = save && li.save
      render :json => resp
    end
1281153
function before_process() {
    global $order, $doPayPal, $messageStack;
    $options = array();
    $optionsShip = array();
    $optionsNVP = array();

    $options = $this->getLineItemDetails($this->selectCurrency($order->info['currency']));

    //$this->zcLog('before_process - 1', 'Have line-item details:' . "\n" . print_r($options, true));

    // Initializing DESC field: using for comments related to tax-included pricing, populated by getLineItemDetails()
    $options['DESC'] = '';

    $doPayPal = $this->paypal_init();
      /****************************************
       * Do DP checkout
       ****************************************/
      $this->zcLog('before_process - DP-1', 'Beginning DP mode' /* . print_r($_POST, TRUE)*/);
      // Set state fields depending on what PayPal wants to see for that country
      $this->setStateAndCountry($order->billing);
      if (zen_not_null($order->delivery['street_address'])) {
        $this->setStateAndCountry($order->delivery);
      }

      // Validate credit card data
      include(DIR_WS_CLASSES . 'cc_validation.php');
      $cc_validation = new cc_validation();
      $response = $cc_validation->validate($_POST['wpp_cc_number'], $_POST['wpp_cc_expdate_month'], $_POST['wpp_cc_expdate_year'],
                                           $_POST['wpp_cc_issuedate_month'], $_POST['wpp_cc_issuedate_year']);
      $error = '';
      switch ($response) {
        case -1:
          $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
          break;
        case -2:
        case -3:
        case -4:
          $error = TEXT_CCVAL_ERROR_INVALID_DATE;
          break;
        case false:
          $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
          break;
      }

      if (($response === false) || ($response < 1) ) {
        $this->zcLog('before_process - DP-2', 'CC validation results: ' . $error . '(' . $response . ')');
        $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $response . ' -->', 'error');
        zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
      }
      if (!in_array($cc_validation->cc_type, array('Visa', 'MasterCard', 'Switch', 'Solo', 'Discover', 'American Express', 'Maestro'))) {
//        $this->zcLog('before_process - DP-3', 'CC info: ' . $cc_validation->cc_type . ' ' . substr($cc_validation->cc_number, 0, 4) . str_repeat('X', (strlen($cc_validation->cc_number) - 8)) . substr($cc_validation->cc_number, -4) . ' ' . $error);
        $messageStack->add_session('checkout_payment', MODULE_PAYMENT_PAYPALDP_TEXT_BAD_CARD . '<!-- [' . $this->code . ' ' . $cc_validation->cc_type . '] -->', 'error');
        zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
      }

      // if CC validation passed, continue using the validated data
      $cc_type = $cc_validation->cc_type;
      $cc_number = $cc_validation->cc_number;
      $cc_first_name = ($_POST['wpp_payer_firstname'] != '' ? $_POST['wpp_payer_firstname'] : $_SESSION['customer_first_name']);
      $cc_last_name = ($_POST['wpp_payer_lastname'] != '' ? $_POST['wpp_payer_lastname'] : $_SESSION['customer_last_name']);
      $cc_checkcode = $_POST['wpp_cc_checkcode'];
      $cc_expdate_month = $cc_validation->cc_expiry_month;
      $cc_expdate_year = $cc_validation->cc_expiry_year;
      $cc_issuedate_month = $_POST['wpp_cc_issuedate_month'];
      $cc_issuedate_year = $_POST['wpp_cc_issuedate_year'];
      $cc_issuenumber = $_POST['wpp_cc_issuenumber'];
      $cc_owner_ip = current(explode(':', str_replace(',', ':', zen_get_ip_address())));

      // If they're still here, set some of the order object's variables.
      $order->info['cc_type'] = $cc_type;
      $order->info['cc_number'] = substr($cc_number, 0, 4) . str_repeat('X', (strlen($cc_number) - 8)) . substr($cc_number, -4);
      $order->info['cc_owner'] = $cc_first_name . ' ' . $cc_last_name;
      $order->info['cc_expires'] = ''; //$cc_expdate_month . substr($cc_expdate_year, -2);
      $order->info['ip_address'] = $cc_owner_ip;

      // Set currency
      $my_currency = $this->selectCurrency($order->info['currency'], 'DP');

      // if CC is switch or solo, must be GBP
      if (in_array($cc_type, array('Switch', 'Solo', 'Maestro'))) {
        $my_currency = 'GBP';
      }

//      $order->info['total'] = zen_round($order->info['total'], 2);
      $order_amount = $this->calc_order_amount($order->info['total'], $my_currency);
      $display_order_amount = $this->calc_order_amount($order->info['total'], $my_currency, TRUE);


      // 3D-Secure
      if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK') {
        // determine the card type and validate that authentication was attempted and completed if applicable
        if (($_SESSION['3Dsecure_requires_lookup'] || $this->requiresLookup($_POST['wpp_cc_number']) == true)) {  // authentication attempt required?
          // validate an acceptable lookup result
          if (isset($_SESSION['3Dsecure_enroll_lookup_attempted']) == false || strcasecmp($_SESSION['3Dsecure_enroll_lookup_attempted'], 'Y') != 0) {
            // lookup never attempted for required card, so need to redirect to payment-selection page
            $reason = 'Customer arrived on the order process page without attempting authentication lookup.';
            $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
            $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
            $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
            $errorText .= $this->code;
            zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');
            zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
          }
          // if enrolled, validate an acceptable authentication result
          if (strcasecmp('Y', $_SESSION['3Dsecure_enrolled']) == 0) {
            if (isset($_SESSION['3Dsecure_authentication_attempted']) == false || strcasecmp($_SESSION['3Dsecure_authentication_attempted'], 'Y') != 0) {
              $reason = 'Customer arrived on the order process page without completing required authentication.';
              $error = MODULE_PAYMENT_PAYPALDP_CANNOT_BE_COMPLETED;
              $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->' . '<!-- result: ' . $reason . ' -->', 'error');
              $errorText = $reason ."\n\nProblem occurred while customer " . $_SESSION['customer_id'] . ' ' . $_SESSION['customer_first_name'] . ' ' . $_SESSION['customer_last_name'] . ' was attempting checkout with 3D-Secure authentication.';
              $errorText .= $this->code;
              zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, MODULE_PAYMENT_PAYPALDP_TEXT_EMAIL_ERROR_SUBJECT, $errorText, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($errorText)), 'paymentalert');

              // remove the lookup/auth attempted status
              unset($_SESSION['3Dsecure_enroll_lookup_attempted']);
              unset($_SESSION['3Dsecure_authentication_attempted']);

              // authentication result was not acceptable, redirect
              zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
            }
          }
        }
        if ($cc_type != 'Solo') {  // PayPal doesn't support 3d-secure on Solo cards
          if (isset($_SESSION['3Dsecure_enrolled'])) {
            $options['MPIVENDOR3DS'] = $_SESSION['3Dsecure_enrolled'];
          }
          if ($_SESSION['3Dsecure_auth_eci'] != '') {
            $options['ECI'] = $_SESSION['3Dsecure_auth_eci'];
          }
          if (isset($_SESSION['3Dsecure_auth_xid']) and strlen($_SESSION['3Dsecure_auth_xid']) > 0) {
            $options['XID'] = $_SESSION['3Dsecure_auth_xid'];
            $options['CAVV'] = $_SESSION['3Dsecure_auth_cavv'];
            $options['AUTHSTATUS3DS'] = $_SESSION['3Dsecure_auth_status'];
          }
        }
      }
///////////////////////////


      // Initialize the paypal caller object.
      $doPayPal = $this->paypal_init();
      $optionsAll = array_merge($options,
                    array('STREET'      => $order->billing['street_address'],
                          'ZIP'         => $order->billing['postcode'],
                          'CITY'        => $order->billing['city'],
                          'STATE'       => $order->billing['state'],
                          'STREET2'     => $order->billing['suburb'],
                          'COUNTRYCODE' => $order->billing['country']['iso_code_2'],
                          'EXPDATE'     => $cc_expdate_month . $cc_expdate_year,
                          'EMAIL'       => $order->customer['email_address'],
                          'PHONENUM'    => $order->customer['telephone']));

      $optionsShip = array();
      if (isset($order->delivery) && $order->delivery['street_address'] != '') {
        $optionsShip= array('SHIPTONAME'   => ($order->delivery['name'] == '' ? $order->delivery['firstname'] . ' ' . $order->delivery['lastname'] : $order->delivery['name']),
                            'SHIPTOSTREET' => $order->delivery['street_address'],
                            'SHIPTOSTREET2' => $order->delivery['suburb'],
                            'SHIPTOCITY'   => $order->delivery['city'],
                            'SHIPTOZIP'    => $order->delivery['postcode'],
                            'SHIPTOSTATE'  => $order->delivery['state'],
                            'SHIPTOCOUNTRYCODE'=> $order->delivery['country']['iso_code_2']);
      }
      // if these optional parameters are blank, remove them from transaction
      if (isset($optionsShip['SHIPTOSTREET2']) && trim($optionsShip['SHIPTOSTREET2']) == '') unset($optionsShip['SHIPTOSTREET2']);
      if ($optionsAll['STREET2'] == '') unset($optionsAll['STREET2']);
      if (isset($optionsShip['SHIPTOPHONE']) && trim($optionsShip['SHIPTOPHONE']) == '') unset($optionsShip['SHIPTOPHONE']);

      // if State is not supplied, repeat the city so that it's not blank, otherwise PayPal croaks
      if ((!isset($optionsShip['SHIPTOSTATE']) || trim($optionsShip['SHIPTOSTATE']) == '') && isset($optionsShip['SHIPTOCITY'])) $optionsShip['SHIPTOSTATE'] = $optionsShip['SHIPTOCITY'];

      // Payment Transaction/Authorization Mode
      $optionsNVP['PAYMENTACTION'] = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Sale';
      if (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') $this->order_status = $this->order_pending_status;

//      if (in_array($cc_type, array('Switch', 'Solo'))) {
//        $optionsNVP['PAYMENTACTION'] = 'Authorization';
//      }
      $optionsAll['BUTTONSOURCE'] = $this->buttonSource;
      $optionsAll['CURRENCY']     = $my_currency;
      if (strlen($cc_owner_ip) > 7) {
        $optionsAll['IPADDRESS']    = $cc_owner_ip;
      }
      if ($cc_issuedate_month && $cc_issuedate_year) {
        $optionsAll['CARDSTART'] = $cc_issuedate_month . substr($cc_issuedate_year, -2);
      }
      if (isset($_POST['wpp_cc_issuenumber'])) $optionsAll['CARDISSUE'] = $_POST['wpp_cc_issuenumber'];

      // Add note to track that this was an API WPP transaction:
      $optionsAll['CUSTOM'] = 'DP-' . (int)$_SESSION['customer_id'] . '-' . time();

      // send the store name as transaction identifier, to help distinguish payments between multiple stores:
      $optionsAll['INVNUM'] = (int)$_SESSION['customer_id'] . '-' . time() . '-[' . substr(preg_replace('/[^a-zA-Z0-9_]/', '', STORE_NAME), 0, 30) . ']';  // (cannot send actual invoice number because it's not assigned until after payment is completed)

      if (MODULE_PAYMENT_PAYPALDP_MERCHANT_COUNTRY == 'UK' || (MODULE_PAYMENT_PAYPALWPP_PFVENDOR != '' && MODULE_PAYMENT_PAYPALWPP_PFPASSWORD != '')) { // Payflow params required
        if (isset($optionsAll['COUNTRYCODE'])) {
          $optionsAll['COUNTRY'] = $optionsAll['COUNTRYCODE'];
          unset($optionsAll['COUNTRYCODE']);
        }
        if (isset($optionsShip['SHIPTOCOUNTRYCODE'])) {
          $optionsShip['SHIPTOCOUNTRY'] = $optionsShip['SHIPTOCOUNTRYCODE'];
          unset($optionsShip['SHIPTOCOUNTRYCODE']);
        }
        if (isset($optionsShip['SHIPTOSTREET2'])) unset($optionsShip['SHIPTOSTREET2']);
        if (isset($optionsAll['STREET2'])) unset($optionsAll['STREET2']);
      }
      if (isset($optionsAll['DESC']) && $optionsAll['DESC'] == '') unset($optionsAll['DESC']);
      $this->zcLog('before_process - DP-4', 'options: ' . print_r(array_merge($optionsAll, $optionsNVP, $optionsShip), true) . "\n" . 'Rest of data: ' . "\n" . number_format($order_amount, 2) . ' ' . $cc_expdate_month . ' ' . substr($cc_expdate_year, -2) . ' ' . $cc_first_name . ' ' . $cc_last_name . ' ' . $cc_type);

      if (!isset($optionsAll['AMT'])) $optionsAll['AMT'] = number_format($order_amount, 2, '.', '');
      $response = $doPayPal->DoDirectPayment($cc_number,
                                           $cc_checkcode,
                                           $cc_expdate_month . substr($cc_expdate_year, -2),
                                           $cc_first_name, $cc_last_name,
                                           $cc_type,
                                           $optionsAll, array_merge($optionsNVP, $optionsShip));

      $this->zcLog('before_process - DP-5', 'resultset:' . "\n" . urldecode(print_r($response, true)));

      // CHECK RESPONSE
      $error = $this->_errorHandler($response, 'DoDirectPayment');

      if ($this->fmfResponse != '') {
        $this->order_status = $this->order_pending_status;
      }

      $this->feeamt = '';
      $this->taxamt = '';
      $this->pendingreason = '';
      $this->reasoncode = '';
      $this->numitems = sizeof($order->products);
      $this->responsedata = $response;

      if ($response['PNREF']) {
      // PNREF only comes from payflow mode
        $this->payment_type = MODULE_PAYMENT_PAYPALDP_PF_TEXT_TYPE;
        $this->transaction_id = $response['PNREF'];
        $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
        $this->avs = 'AVSADDR: ' . $response['AVSADDR'] . ', AVSZIP: ' . $response['AVSZIP'] . ', IAVS: ' . $response['IAVS'];
        $this->cvv2 = $response['CVV2MATCH'];
        $this->amt = $display_order_amount . ' ' . $my_currency;
        $this->payment_time = date('Y-m-d h:i:s');
        $this->responsedata['CURRENCYCODE'] = $my_currency;
        $this->responsedata['EXCHANGERATE'] = $order->info['currency_value'];
        $this->auth_code = $this->response['AUTHCODE'];
      } else {
        // here we're in NVP mode
        $this->transaction_id = $response['TRANSACTIONID'];
        $this->payment_type = MODULE_PAYMENT_PAYPALDP_DP_TEXT_TYPE;
        $this->payment_status = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'Authorization' : 'Completed';
        $this->pendingreason = (MODULE_PAYMENT_PAYPALDP_TRANSACTION_MODE == 'Auth Only') ? 'authorization' : '';
        $this->avs = $response['AVSCODE'];
        $this->cvv2 = $response['CVV2MATCH'];
        $this->correlationid = $response['CORRELATIONID'];
        $this->payment_time = urldecode($response['TIMESTAMP']);
        $this->amt = urldecode($response['AMT'] . ' ' . $response['CURRENCYCODE']);
        $this->auth_code = (isset($this->response['AUTHCODE'])) ? $this->response['AUTHCODE'] : $this->response['TOKEN'];
        $this->transactiontype = 'cart';
      }
  }
1110924
def to_array(self):
        
        array = super(SuccessfulPayment, self).to_array()
        array['currency'] = u(self.currency)  # py2: type unicode, py3: type str
        array['total_amount'] = int(self.total_amount)  # type int
        array['invoice_payload'] = u(self.invoice_payload)  # py2: type unicode, py3: type str
        array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id)  # py2: type unicode, py3: type str
        array['provider_payment_charge_id'] = u(self.provider_payment_charge_id)  # py2: type unicode, py3: type str
        if self.shipping_option_id is not None:
            array['shipping_option_id'] = u(self.shipping_option_id)  # py2: type unicode, py3: type str
        if self.order_info is not None:
            array['order_info'] = self.order_info.to_array()  # type OrderInfo
        return array
925609
function(objJoint, arrChainsOfRecipientPrivateElements, arrChainsOfCosignerPrivateElements){
						network.broadcastJoint(objJoint);
						if (!arrChainsOfRecipientPrivateElements){ // send notification about public payment
							if (recipient_device_address)
								walletGeneral.sendPaymentNotification(recipient_device_address, objJoint.unit.unit);
							if (recipient_device_addresses)
								recipient_device_addresses.forEach(function(r_device_address){
									walletGeneral.sendPaymentNotification(r_device_address, objJoint.unit.unit);
								});
						}

						if (Object.keys(assocPaymentsByEmail).length) { // need to send emails
							var sent = 0;
							for (var email in assocPaymentsByEmail) {
								var objPayment = assocPaymentsByEmail[email];
								sendTextcoinEmail(email, opts.email_subject, objPayment.amount, objPayment.asset, objPayment.mnemonic);
								if (++sent == Object.keys(assocPaymentsByEmail).length)
									handleResult(null, objJoint.unit.unit, assocMnemonics);
							}
						} else {
							handleResult(null, objJoint.unit.unit, assocMnemonics);
						}
					}
1213861
def tracking_number(self, service: str = 'usps') -> str:
        
        service = service.lower()

        if service not in ('usps', 'fedex', 'ups'):
            raise ValueError('Unsupported post service')

        services = {
            'usps': (
                '#### #### #### #### ####',
                '@@ ### ### ### US',
            ),
            'fedex': (
                '#### #### ####',
                '#### #### #### ###',
            ),
            'ups': (
                '1Z@####@##########',
            ),
        }
        mask = self.random.choice(services[service])  # type: ignore
        return self.random.custom_code(mask=mask)
1088550
public function postage($params, $content, $template, &$repeat)
    {
        if (!$repeat) {
            return (null !== $this->countryId) ? $content : "";
        }

        $customer = $this->getCurrentRequest()->getSession()->getCustomerUser();
        /** @var Address $address */
        /** @var Country $country */
        list($address, $country, $state) = $this->getDeliveryInformation($customer);

        if (null !== $country) {
            $this->countryId = $country->getId();
            // try to get the cheapest delivery for this country
            $this->getCheapestDelivery($address, $country);
        }

        $template->assign('country_id', $this->countryId);
        $template->assign('delivery_id', $this->deliveryId);
        $template->assign('postage', $this->postage ?: 0.0);
        $template->assign('postage_tax', $this->postageTax ?: 0.0);
        $template->assign('postage_title', $this->postageTaxRuleTitle ?: 0.0);
        $template->assign('is_customizable', $this->isCustomizable);
    }
9803
def listed(self):
        
        print("\nPackages in the queue:\n")
        for pkg in self.packages():
            if pkg:
                print("{0}{1}{2}".format(self.meta.color["GREEN"], pkg,
                                         self.meta.color["ENDC"]))
                self.quit = True
        if self.quit:
            print("")
167053
def shipping_json
      render :json => { :error => 'Not logged in.'          } and return if !logged_in?
      render :json => { :error => 'No shippable items.'     } and return if !@invoice.has_shippable_items?
      render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil?      
      
      @invoice.calculate
      
      #ops = @invoice.invoice_packages      
      #if params[:recalculate_invoice_packages] || ops.count == 0
      #  # Remove any invoice packages      
      #  LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil)
      #  InvoicePackage.where(:invoice_id => @invoice.id).destroy_all      
      #    
      #  # Calculate what shipping packages we'll need            
      #  InvoicePackage.create_for_invoice(@invoice)
      #end

      # Now get the rates for those packages            
      rates = ShippingCalculator.rates(@invoice)      
      render :json => rates                  
    end
415710
def _get_shipped_from(row):
    """"""
    try:
        spans = row.find('div', {'id': 'coltextR2'}).find_all('span')
        if len(spans) < 2:
            return None
        return spans[1].string
    except AttributeError:
        return None
77482
private function shipping()
    {
        if ($this->_order->getIsVirtual()) {
            $this->_paymentRequest->setShipping()->setAddressRequired()->withParameters('false');
        } else {
            $this->_paymentRequest->setShipping()->setAddressRequired()->withParameters('true');
            $this->setShippingInformation();
        }
    }
80170
def message(self, do_html=True, custom_email_template=None):
        
        context = {
            'build': self.build,
            'important_metadata': self.important_metadata,
            'metadata': self.metadata,
            'notification': self,
            'previous_build': self.previous_build,
            'regressions_grouped_by_suite': self.comparison.regressions_grouped_by_suite,
            'fixes_grouped_by_suite': self.comparison.fixes_grouped_by_suite,
            'known_issues': self.known_issues,
            'regressions': self.comparison.regressions,
            'fixes': self.comparison.fixes,
            'thresholds': self.thresholds,
            'settings': settings,
            'summary': self.summary,
        }

        html_message = ''
        if custom_email_template:
            text_template = jinja2.from_string(custom_email_template.plain_text)
            text_message = text_template.render(context)

            if do_html:
                html_template = jinja2.from_string(custom_email_template.html)
                html_message = html_template.render(context)
        else:
            text_message = render_to_string(
                'squad/notification/diff.txt.jinja2',
                context=context,
            )
            if do_html:
                html_message = render_to_string(
                    'squad/notification/diff.html.jinja2',
                    context=context,
                )
        return (text_message, html_message)
896172
def _message(self):
        """"""
        ascii_attachments = current_app.extensions['mail'].ascii_attachments
        encoding = self.charset or 'utf-8'

        attachments = self.attachments or []

        if len(attachments) == 0 and not self.alts:
            # No html content and zero attachments means plain text
            msg = self._mimetext(self.body, self.subtype)
        elif len(attachments) > 0 and not self.alts:
            # No html and at least one attachment means multipart
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            msg.attach(self._mimetext(self.body))
        else:
            # Anything else
            subtype = self.subtype or 'mixed'
            msg = MIMEMultipart(_subtype=subtype)
            alternative = MIMEMultipart(_subtype='alternative')
            alternative.attach(self._mimetext(self.body))
            for mimetype, content in self.alts.items():
                alternative.attach(self._mimetext(content, mimetype))
            msg.attach(alternative)

        if self.subject:
            msg['Subject'] = sanitize_subject(force_text(self.subject),
                                              encoding)

        msg['From'] = sanitize_address(self.sender, encoding)
        msg['To'] = ', '.join(
            list(set(sanitize_addresses(self.recipients, encoding)))
        )

        msg['Date'] = formatdate(self.date, localtime=True)
        # see RFC 5322 section 3.6.4.
        msg['Message-ID'] = self.msgId

        if self.cc:
            msg['Cc'] = ', '.join(
                list(set(sanitize_addresses(self.cc, encoding)))
            )

        if self.reply_to:
            msg['Reply-To'] = sanitize_address(self.reply_to, encoding)

        if self.extra_headers:
            for k, v in self.extra_headers.items():
                msg[k] = v

        SPACES = re.compile(r'[\s]+', re.UNICODE)
        for attachment in attachments:
            f = MIMEBase(*attachment.content_type.split('/'))
            f.set_payload(attachment.data)
            encode_base64(f)

            filename = attachment.filename
            if filename and ascii_attachments:
                # force filename to ascii
                filename = unicodedata.normalize('NFKD', filename)
                filename = filename.encode('ascii', 'ignore').decode('ascii')
                filename = SPACES.sub(u' ', filename).strip()

            try:
                filename and filename.encode('ascii')
            except UnicodeEncodeError:
                if not PY3:
                    filename = filename.encode('utf8')
                filename = ('UTF8', '', filename)

            f.add_header('Content-Disposition',
                         attachment.disposition,
                         filename=filename)

            for key, value in attachment.headers.items():
                f.add_header(key, value)

            if attachment.content_id:
                try:
                    f.replace_header('Content-ID', attachment.content_id)
                except KeyError:
                    f.add_header('Content-ID', attachment.content_id)

            msg.attach(f)
        if message_policy:
            msg.policy = message_policy

        return msg