•  914-288-5685
  •   sales@revindex.com
   Search
FR
0
 
  • Register
 
Login
Revindex
  • Products
    • -Comodo PCI Scan
    • -RapidSSL Certificate
    • -RapidSSL Wildcard Certificate
    • -Revindex Generic Skin
    • -Revindex Impersonator
    • -Revindex Omni Skin
    • -Revindex Optimizer
    • -Revindex Polo Skin
    • -Revindex Priority Support
    • -Revindex Storefront
    • -Revindex Storefront Service Plan
    • -Revindex Storefront Source
    • -Revindex Storefront Source Service Plan
    • -Revindex Task Scheduler
    • -Revindex Wiki
    • -Software License Modification
  • Services
    • -Design
    • -Programming
    • -Hosting
    • -Merchant Account
  • Resources
    • -Downloads
    • -Knowledge Base
      • --ASCII Characters
      • --HTML Entities
      • --Revindex Impersonator
      • --Revindex Optimizer
      • --Revindex Storefront
      • --Revindex Task Scheduler
      • --Revindex Wiki
      • --Standard DNN Tokens
    • -Tools
      • --Remote Ping
      • --Unit Converter
      • --URL Encoder Decoder
      • --HTML Encoder Decoder
      • --GUID Generator
    • -Blogs
  • Support
    • -Forum
    • -Frequently Asked Questions
    • -Support Ticket
  • Company
    • -About Us
    • -Customer Portfolio
    • -Customer Reviews
    • -Resellers
  • Free Trial
You are here: Resources ⁄ Knowledge Base ⁄ Revindex Storefront

Revindex Storefront

Email Export Print

Export order (Powershell)

Here's a simple example using Powershell to export pending orders to send for fulfillment via email.


# SalesOrderExport.ps1
#
# This script will export all pending orders with products belonging to 
# a distributor and send the CSV file using email.
# It will keep track of all the order details fulfilled in a local file.
# It will mark the order as shipped and completed when every order detail
# has been fulfilled.
######################################################################


# Configuration
######################################################################


$APIKey = '00000000-0000-0000-0000-000000000000'
$APIUrl = 'http://domain.com/DesktopModules/Revindex.Dnn.RevindexStorefront/Api/Rest/V1/ServiceHandler.ashx?portalid=0'
$APIUsername = 'host'


# Number of days to look back at orders
$BackOrderDays = -7


# The distributor to match
$DistributorID = 1


$FulfillmentEmailBody = 'Order fulfillment text body'


# The email(s) to send fulfillment file. Separated multiple emails by semicolon.
$FulfillmentEmailRecipient = 'vendor@localhost.com'


$FulfillmentEmailSender = 'support@localhost.com'
$FulfillmentEmailSubject = 'Order fulfillment'
$FulfillmentFileName = ('Fulfillment.' + [DateTime]::Now.ToString('yyyyMMdd') + '.txt')


$LogFileName = ('Log.' + [DateTime]::Now.ToString('yyyyMMdd') + '.txt')


$NetworkTimeout = 30000


# The email(s) to notify on success/error. Separated multiple emails by semicolon.
$NotificationRecipient = 'support@localhost.com'


$NotificationSender = 'support@localhost.com'


$OrderCompletionFileName = 'OrderCompletion.txt'


$SMTPPassword = 'xxxxxx'
$SMTPServer = 'mail.localhost.com'
$SMTPUser = 'mailer'


# The folder to store files, logs, etc. defaults to the current execution path
$WorkingFolder = ((Split-Path $MyInvocation.MyCommand.Path) + '\')


# Functions
######################################################################


# Function to help post HTTP request to web service
Function PostWebRequest([String] $url, [String] $data, [int] $timeout)
{    
    $buffer = [System.Text.Encoding]::UTF8.GetBytes($data)
    [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($url)
    $webRequest.Timeout = $timeout
    $webRequest.Method = "POST"
    $webRequest.ContentType = "application/x-www-form-urlencoded"
    $webRequest.ContentLength = $buffer.Length;


    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($buffer, 0, $buffer.Length)
    $requestStream.Flush()
    $requestStream.Close()


    [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
    $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
    $result = $streamReader.ReadToEnd()
    return $result
}


# Function to send email
Function SendEmail([String]$smtpServer, [String] $smtpUser, [String] $smtpPassword, [String] $sender, [String] $recipient, [String] $subject, [String] $body, [String] $attachment)
{
    $msg = New-Object System.Net.Mail.MailMessage
    $msg.From = $sender
    $msg.ReplyTo = $sender
    
    foreach ($r in $recipient.Split(';'))
    {
        if ($r)
        {
            $msg.To.Add($r)
        }
    }
    $msg.subject = $subject
    $msg.body = $body
    
    if ($attachment -and [System.IO.File]::Exists($attachment))
    {
        $att = New-Object System.Net.Mail.Attachment($attachment)
        $msg.Attachments.Add($att)
    }


    $smtp = New-Object System.Net.Mail.SmtpClient($smtpServer)
    $smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPassword);
    $smtp.Send($msg)
}


# Start program
######################################################################


Try
{    
    # Load order completion data into array
    $OrderCompletion = @()
    if ([System.IO.File]::Exists($WorkingFolder + $OrderCompletionFileName))
    {
        $OrderCompletion = @(Import-Csv ($WorkingFolder + $OrderCompletionFileName))
    }    


    # Get sales orders needing to be fulfilled
    $StartDate = [DateTime]::Now.AddDays($BackOrderDays).ToString("s")
    $StopDate = [DateTime]::Now.ToString("s")


    $xRequest = [Xml] "

1.0

$APIUsername
$APIKey

GetSalesOrdersByDateRange

$StartDate
$StopDate

"
[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
if ($xResponse.response.code -ne '2000')
{
Throw New-Object System.InvalidOperationException("Error executing GetSalesOrdersByDateRange. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
}
[System.Xml.XmlElement]$salesOrders = $xResponse.SelectSingleNode('/response/return/salesOrders')
foreach ($salesOrder in $salesOrders.SelectNodes('salesOrder'))
{
# Look for pending order status
if ($salesOrder.status -eq '1')
{
# Query sales order details
$xRequest = [Xml] ("

1.0

$APIUsername
$APIKey

GetSalesOrderDetails

" + $salesOrder.salesOrderID + "
$StopDate

")
[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
if ($xResponse.response.code -ne '2000')
{
Throw New-Object System.InvalidOperationException("Error executing GetSalesOrderDetails. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
}
[System.Xml.XmlElement]$salesOrderDetails = $xResponse.SelectSingleNode('/response/return/salesOrderDetails')
foreach ($salesOrderDetail in $salesOrderDetails.SelectNodes('salesOrderDetail'))
{
# Make sure we haven't already fulfilled this sales order detail otherwise we can skip it
if (($OrderCompletion | Where-Object {$_.SalesOrderDetailID -eq $salesOrderDetail.salesOrderDetailID }))
{
continue
}
# Query product info for matching distributor
$xRequest = [Xml] ("

1.0

$APIUsername
$APIKey

GetActiveProductVariant

" + $salesOrderDetail.productVariantID + "

")
[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
if ($xResponse.response.code -ne '2000')
{
Throw New-Object System.InvalidOperationException("Error executing GetActiveProductVariant. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
}
$productVariant = $xResponse.response.return.productVariant
if ($productVariant.distributorID -eq $DistributorID)
{
# Append data to CSV file
if (![System.IO.File]::Exists($WorkingFolder + $FulfillmentFileName))
{
# Write CSV headers
('Date,SalesOrderID,SalesOrderDetailID,SKU,DistributorSKU,Quantity') >> ($WorkingFolder + $FulfillmentFileName)
}
# Append data to CSV
($salesOrder.orderDate + ',' + $salesOrder.salesOrderID + ',' + $salesOrderDetail.salesOrderDetailID + ',' + $productVariant.sku + ',' + $productVariant.distributorSKU + ',' + $salesOrderDetail.quantity) >> ($WorkingFolder + $FulfillmentFileName)
# Keep track of completed sales order details. Add order detail to our tracking array
$OrderCompletion += New-Object -TypeName PSObject -Property @{ DistributorID = $DistributorID
Date = [DateTime]::Now.ToString("s")
SalesOrderID = $salesOrder.salesOrderID
SalesOrderDetailID = $salesOrderDetail.salesOrderDetailID }
}
}
# Update order status to Completed and Shipped if all sales order details have been accounted for.
$orderIsComplete = $true
foreach ($salesOrderDetail in $salesOrderDetails.SelectNodes('salesOrderDetail'))
{
if (!($OrderCompletion | Where-Object {$_.SalesOrderDetailID -eq $salesOrderDetail.salesOrderDetailID }))
{
$orderIsComplete = $false
break
}
}
if ($orderIsComplete)
{
# Update order status to shipped (3) and order completed (4).
$xRequest = [Xml] ("

1.0

$APIUsername
$APIKey

UpdateSalesOrder

" + $salesOrder.salesOrderID + "
" + $salesOrder.salesPaymentStatus + "
3
4

")
[Xml]$xResponse = PostWebRequest $APIUrl $xRequest.InnerXml $NetworkTimeout
if ($xResponse.response.code -ne '2000')
{
Throw New-Object System.InvalidOperationException("Error executing UpdateSalesOrder. Response: " + $xResponse.response.code + ' ' + $xResponse.response.message)
}
# Remove records from order completion tracking belonging to this order
$OrderCompletion = @($OrderCompletion | Where-Object { $_.SalesOrderID -ne $salesOrder.salesOrderID })
}
}
}
# Send email to fulfill orders
if ([System.IO.File]::Exists($WorkingFolder + $FulfillmentFileName))
{
SendEmail $SMTPServer $SMTPUser $SMTPPassword $FulfillmentEmailSender $FulfillmentEmailRecipient $FulfillmentEmailSubject $FulfillmentEmailBody ($WorkingFolder + $FulfillmentFileName)
}
# Persist tracking to order completion file
$OrderCompletion | Export-Csv -NoTypeInformation ($WorkingFolder + $OrderCompletionFileName)
# Log completion
([DateTime]::Now.ToString("s") + "`t" + 'Fufillment completed successfully') >> ($WorkingFolder + $LogFileName)
# Notify progress
SendEmail $SMTPServer $SMTPUser $SMTPPassword $NotificationSender $NotificationRecipient 'Fulfillment completed successfully' 'Fulfillment completed successfully' ($WorkingFolder + $LogFileName)
}
Catch
{
# Log errors
([DateTime]::Now.ToString("s") + "`t" + $_.Exception.Message) >> ($WorkingFolder + $LogFileName)
# Notify error
SendEmail $SMTPServer $SMTPUser $SMTPPassword $NotificationSender $NotificationRecipient 'Fulfillment failed' 'Fulfillment failed' ($WorkingFolder + $LogFileName)
}

Comments

Add comment
Previous Next

Search

Search

Contents

  • Users Manual
    • Overview
    • Installation
      • Requirements
      • How to install
      • Quick start settings
      • License key
      • Common installation errors
      • Adding module controls
      • How module controls interact
      • How to move modules
      • How to SSL secure your pages
      • How to improve performance
      • How to upgrade
      • How to install DNN on local machine
      • Web farm
      • How to uninstall
      • How to re-install with data
      • How to migrate product data
    • Administration
      • Configuration
        • General
        • Currencies
        • Payment
          • Gateways
            • Authorize.Net AIM
            • Authorize.Net CIM
            • Authorize.Net SIM
            • Barclaycard DirectLink
            • BluePay
            • Cardstream Direct
            • CashFlows Remote API
            • Chase Paymentech Orbital Gateway
            • Corduro
            • CyberSource
            • Dotpay
            • Elavon Virtual Merchant
            • eProcessing Network
            • eWay Direct Payment Australia
            • FirstData Global Gateway Web Service
            • FTNI
            • FTNI ACH
            • InternetSecure
            • Intuit QuickBooks Merchant Service
            • MasterCard Internet Gateway Service Hosted
            • Merchant e-Solutions
            • Mollie
            • Moneris eSelectPlus Canada
            • NMI
            • PayFast Website Payment
            • Payment Express PxPay
            • Payment Express PxPost
            • PayPal Express Checkout
            • PayPal Payment Gateway
            • PayPal Payments Standard
            • PayPal Website Payments Pro
            • Paystation 3-Party
            • PayTrace
            • PayU Business
            • PayU Enterprise
            • Peach Payments
            • Princeton CardConnect
            • PSiGate XML Messenger
            • Sage Pay Direct
            • Sage Pay Form
            • Sage Payments Direct
            • Stripe
            • Suomen Verkkomaksut
            • Total Apps
            • Towah
            • USA ePay
            • Virtual Card Services Pay
            • WorldPay Corporate XML Direct
            • Zooz
            • Custom gateway
          • How to offer free products without payment
          • How to avoid duplicate order number error
        • Taxes
          • Providers
            • Avalara
            • TaxJar
            • Zip2Tax
          • How to use a tax table
        • Packages
        • Packing
          • Single package
          • Single product
          • Volume fit
        • Shipping
          • Shipping Availability
          • Shipping Rate
          • Providers
            • ABF
            • Australia Post
            • Canada Post
            • CouriersPlease
            • DHL Express
            • FedEx
            • Purolator
            • Shipwire
            • Southeastern
            • Unishippers
            • UPS
            • USPS
          • How to configure real-time shipping
        • Fulfillment
          • ShipWorks
        • Handling
          • How to charge handling for payment type
        • Communications
          • Cart abandon email
          • Order alert email
          • Order invoice email
          • Order invoice print
          • Order quote email
          • Order quote print
          • Order receipt email
          • Order receipt print
          • Order update email
          • Packing slip print
          • Payment alert email
          • Recurring order payment retry email
          • Recurring order reminder email
          • Right receipt email
          • Voucher receipt email
          • How to troubleshoot email not receiving
          • How to make HTML editor behave
        • Reports
          • How to create custom reports
          • How to export data from custom report
        • Rewards points
        • Analytics
        • Sitemap
        • Affiliates
        • Address validation
          • Avalara
        • Fraud risk
          • FraudLabs Pro
          • Sift Science
        • Channels
          • eBay
        • Accounting
          • QuickBooks
          • Xero
      • Catalog
        • Categories
          • Category availability
        • Distributors
        • Manufacturers
        • Warehouses
        • Product attributes
          • Groups
          • Definitions
        • Products
          • Attributes
          • Gallery Images
          • SEO
          • Product Availability
          • Custom fields
          • Variant groups
          • Variants
            • Inventory
            • Warehouse
            • Price
            • Product Modifier
            • Product Promotion
            • Subscription Products
            • Taxable Products
            • Weight & Dimensions
            • Variant Availability
            • Attributes
            • Gallery Images
            • Quoted products
            • Bundled products
            • Booking products
            • Required Products
            • Downloadable Products
            • Custom fields
            • Actions
            • Extensions
          • Cross-sell products
          • How to create a simple product
          • How to create a recurring product
          • How to create a setup fee
          • How to create overridable price product
          • How to create a configurable price product
          • How to create downloadable products
          • How to create a catalog product
          • How to create a voucher product
          • How to email external license key
          • How to show product without category
          • How to give first month recurring free
          • How to create a deferred product
          • How to sell on eBay
          • How advanced URL provider works
          • How to delete all products
        • Vouchers
        • Rights
      • Sales
        • Orders
          • Order, Payment & Shipping Status
          • Payments
            • How to refund payment
          • Preorders
          • How to accept offline orders
          • Why do order numbers skip?
          • How to auto delete incomplete orders
          • How to delete all orders
        • Recurring Orders
        • Bookings
        • Rights
        • Vouchers
      • Marketing
        • Coupons
          • Coupon Availability
        • Promotions
          • Handling Type Promotion
          • Product Type Promotion
          • Sales Order Detail Type Promotion
          • Shipping Type Promotion
          • Tax Type Promotion
      • Access Control
      • Log Level
    • Category
      • How to expand all categories
      • How to add categories to Web site menu
    • Distributor
    • Manufacturer
    • Product List
      • Hosting Multiple Module Controls
      • How to change default sort order
      • How to change the number of grid columns
      • How to change page size
      • How to default to list view
      • How to force products from a category
      • How to show featured products
    • Product Detail
      • Hosting Multiple Module Controls
      • How to force product
      • How to set number of related products
    • Product Filter
    • Product Search
      • How search works
    • Product Showcase
    • Product Comparison
    • Cart Summary
      • How to change payment acceptance mark
    • Cart
      • How to increase cart session time
      • How to cleanup on logout
    • Checkout
      • Anonymous Checkout
      • Multiple step or single page checkout
      • Checkout Availability
      • Actions
      • How to assign security role on checkout
      • How to change payment acceptance mark
      • How to hide unwanted country
      • How to set default country
      • How to include registration form in checkout
      • How to create a single login & register page
      • How numbers are calculated and rounded
      • How to require terms & agreement
    • Confirmation
    • Currency
    • Quick Order
    • Wish List
    • Manage Address
    • Manage Product Download
    • Manage Order
    • Manage Payment
    • Manage Recurring Order
    • Manage Rewards Points
    • Manage Rights
    • Manage Vouchers
    • Manage Wish List
    • Multi-seller marketplace
      • Sellers
      • Administration
      • Order splitting
    • Text and languages
      • International languages
      • Static Localization and Language Packs
        • How to format the currency symbol
        • How to create your own language pack
        • How to format page title
      • Content Localization
        • How to localize XSL email template
    • Design and Styling
      • Display Templates
        • Understanding CSS Precedence
        • How to override CSS styles
        • How to style buttons
        • How to upgrade display templates
        • How to edit template in Visual Studio
        • How to expand panel by default
        • Removing unwanted elements
        • Styling Telerik controls
      • Models
        • CartModel
        • CartSummaryViewModel
        • CartViewModel
        • CategoryModel
        • CategoryViewModel
        • CheckoutModel
        • CheckoutViewModel
        • CodeType
        • ConfirmationModel
        • ConfirmationViewModel
        • CrosssellProductModel
        • CrosssellProductViewModel
        • DistributorFilterModel
        • DistributorModel
        • DistributorViewModel
        • DynamicFormCodeModel
        • DynamicFormFieldModel
        • DynamicFormModel
        • GalleryFormatType
        • GalleryModel
        • IntervalType
        • InventoryUnitType
        • LoginModel
        • ManageWishListModel
        • ManufacturerFilterModel
        • ManufacturerModel
        • ManufacturerViewModel
        • PagerModel
        • PaymentMethodModel
        • PaymentMethodType
        • PriceFilterModel
        • ProductAttributeDefinitionModel
        • ProductAttributeDefinitionSelectionModel
        • ProductAttributeFilterModel
        • ProductAttributeGroupModel
        • ProductAttributeModel
        • ProductAttributeType
        • ProductComparisonModel
        • ProductComparisonViewModel
        • ProductComponentModel
        • ProductComponentType
        • ProductDetailModel
        • ProductDetailViewModel
        • ProductFilterModel
        • ProductFilterViewModel
        • ProductInventoryEmptyBehaviorType
        • ProductListModel
        • ProductListPageViewDisplayOrderType
        • ProductListViewModel
        • ProductModel
        • ProductPartModel
        • ProductReviewModel
        • ProductReviewViewModel
        • ProductSearchViewModel
        • ProductShowcaseDisplayEffectType
        • ProductShowcaseScrollDirectionType
        • ProductShowcaseViewModel
        • ProductVariantGroupFieldType
        • ProductVariantGroupModel
        • ProductVariantGroupOptionModel
        • ProductVariantModel
        • RecurringIntervalType
        • RegistrationModel
        • RequiredProductModel
        • SalesOrderDetailModel
        • SalesOrderDetailStatusType
        • SalesOrderModel
        • SalesOrderSetModel
        • SalesPaymentModel
        • SalesType
        • SellerModel
        • ShoppingModel
        • UserAddressModel
        • UserModel
        • UserPaymentModel
        • ValidationResultModel
        • WishListModel
        • WishListType
        • WishListViewModel
    • Shopping Cart Flow
      • Customer initiates checkout
      • Merchant fulfills new order
      • Merchant cancels bad order
      • Merchant fulfills recurring order
      • Understanding payment risk
      • How to force order and payment status
    • Page action
      • Examples
    • Import and Export
      • Overview
      • Data Types
      • Entities
        • Category
        • Distributor
        • Gallery
        • Manufacturer
        • Product
        • Product Attribute
        • Product Attribute Definition
        • Product Attribute Group
        • Product Category
        • Product Component
        • Product Part
        • Product Review
        • Product Variant
        • Product Variant Group
        • Product Variant Group Option
        • Product Variant Option
        • Recurring Sales Order
        • Related Product
        • Required Product
        • Right
        • Sales Order
        • Sales Order Detail
        • Similar Product
        • Voucher
        • Warehouse
      • Examples
        • Export products
        • Insert products
        • Update products
        • Delete products
        • Export products (SQL)
        • Export orders (SQL)
        • How to bulk update gallery images
        • How to bulk update product keys
      • Site Wide Import and Export
    • REST API
      • Overview
      • Data Types
      • Authentication
      • Services
        • Category
        • Coupon
        • CrosssellProduct
        • Distributor
        • Gallery
        • Locale
        • Manufacturer
        • Portal
        • Product
        • ProductAttribute
        • ProductAttributeDefinition
        • ProductAttributeGroup
        • ProductCategory
        • ProductComponent
        • ProductPart
        • ProductVariant
        • ProductVariantGroup
        • ProductVariantGroupOption
        • ProductVariantOption
        • RecurringSalesOrder
        • RelatedProduct
        • RequiredProduct
        • Right
        • RightDefinition
        • SalesOrder
        • SalesOrderDetail
        • SalesPayment
        • SalesPromotion
        • ShippingMethod
        • TaxClass
        • User
        • UserPayment
        • Voucher
        • VoucherDefinition
        • Warehouse
      • Examples
        • Export order (Powershell)
        • Export order 2 (Powershell)
        • Export products (Powershell)
        • QuickBooks export customer (Powershell)
        • QuickBooks export sales order (Powershell)
        • Shipwire export order (Powershell)
        • Retrieve product (C#)
        • CSV bulk import
    • XML and XSL
      • XSL Transform
      • XSL Tokens
      • Debugging XSL
    • String Tokens
    • Lookup Values
      • Account Types
      • Country and Subdivision Codes
      • Inventory Unit Types
      • Package Types
      • Payment Gateway Response Codes
      • Payment Gateway AVS Response Codes
      • Payment Gateway CVV Response Codes
      • Payment Method Types
      • Payment Origin Types
      • Payment Term Types
      • Recurring Interval Types
      • Recurring Sales Order Status Types
      • Rewards Points Operation Types
      • Rewards Points Status Types
      • Sales Order Detail Status Types
      • Sales Order Origin Types
      • Sales Types
      • Sales Order Status Types
      • Sales Payment Status Types
      • Sales Payment Transaction Types
      • Shipping Status Types
      • Voucher Interval Types
      • Voucher Status Types
    • Compliances
      • GDPR
      • PCI
  • Release notes

Powered by Revindex Wiki

Copyright Revindex Inc. : Terms Of Use : Privacy Statement
Copyright Revindex Inc. : Terms Of Use : Privacy Statement