Repositório de alguns códigos usando javascript (backend e frontend) e ISML para a plataforma Salesforce.
TEMPLATE EXEMPLO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<isdecorate template="account/pt_account"> | |
<isinclude template="util/modules"> | |
<isloop items="${pdict.items}" var="item"> | |
<img src="${item.media.m}" alt=""/> | |
</isloop> | |
</isdecorate> |
DO CONTROLLER ENVIAR EMAIL AO CLIENTE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sendEmailToCustomer(product) { | |
var customerEmail = customer.profile.email; | |
var EmailModel = require('app_storefront_controllers/cartridge/scripts/models/EmailModel'); | |
var fromEmail = dw.system.Site.current.preferences.custom.noreplyWishlistEmail | |
var options = { | |
recipient: customerEmail, | |
subject: Resource.msg('email.subject', 'wishlist', null), | |
template: 'mail/product.isml', | |
from: fromEmail, | |
context: { | |
Product: product | |
} | |
} | |
EmailModel.sendMail(options); | |
} |
CRIAR FORMULÁRIO COM XML E TEMPLATE
CONTROLLER QUE RENDERIZA FORMULÁRIO E TRATA RESULTADO DO BOTÃO SUBMIT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var guard = require('app_storefront_controllers/cartridge/scripts/guard'); | |
var ISML = require('dw/template/ISML'); | |
var newsletterForm = session.forms.newsletter; | |
function start() { | |
newsletterForm.clearFormElement(); | |
ISML.renderTemplate('newsletter/newslettersignup',{ | |
ContinueURL: dw.web.URLUtils.https('Newsletter-HandleForm') | |
}); | |
} | |
function handleForm(){ | |
var Transaction = require('dw/system/Transaction'); | |
var submitButton = request.triggeredFormAction; | |
var newsletterObj; | |
var newsletterModel | |
if (submitButton && submitButton.formId == 'subscribe') { | |
try { | |
Transaction.wrap(function() { | |
newsletterModel = require('~/cartridge/scripts/NewsLetterModel'); | |
newsletterObj = newsletterModel.CreateNewsLetterObject(newsletterForm); | |
}); | |
newsletterModel.SendEmailToSubscriber(newsletterObj); | |
ISML.renderTemplate('newsletter/newslettersuccess', { | |
Subscription: newsletterObj | |
}); | |
} | |
catch(e){ | |
var error = e; | |
ISML.renderTemplate('newsletter/newslettererror'); | |
} | |
} | |
else{ | |
ISML.renderTemplate('newsletter/newslettersignup',{ | |
ContinueURL: dw.web.URLUtils.https('Newsletter-HandleForm') | |
}); | |
} | |
} | |
exports.Start = guard.ensure(['get'], start); | |
exports.HandleForm = guard.ensure([], handleForm); |
CRIAR UM CUSTOM OBJECT
PEGA UM CUPOM CODE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getCouponCode() { | |
var CouponMgr = require('dw/campaign/CouponMgr'); | |
var coupon = CouponMgr.getCoupon('newsletter20off'); | |
var couponCode = coupon.getNextCouponCode(); | |
return couponCode; | |
} |
BUSCA POR PRODUTOS DE UMA MARCA ESPECÍFICA E GERA XML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const File = require('dw/io/File'); | |
const FileWriter = require('dw/io/FileWriter'); | |
const XMLStreamWriter = require('dw/io/XMLStreamWriter'); | |
const ProductMgr = require('dw/catalog/ProductMgr'); | |
exports.execute = function(args) { | |
try { | |
// Brand from job parameters | |
var brand = args.brand; | |
var products = ProductMgr.queryAllSiteProducts(); | |
var productsWithBrand = []; | |
while (products.hasNext()) { | |
var product = products.next(); | |
// Collect all products with a specific brand | |
if(product.brand == brand) { | |
productsWithBrand.push(product); | |
} | |
} | |
// Save XML on: /on/demandware.servlet/webdav/Sites/Impex/src/exports/categoryAssign.xml | |
var impexPath = File.IMPEX + File.SEPARATOR + 'src' + File.SEPARATOR + 'exports' + File.SEPARATOR + 'categoryAssign.xml'; | |
var file = new File(impexPath); | |
var fileWriter = new FileWriter(file, 'UTF-8'); | |
var xsw = new XMLStreamWriter(fileWriter); | |
/* The code below should write a XML similar to this onde: | |
<?xml version="1.0" encoding="UTF-8"?> | |
<catalog xmlns="http://www.demandware.com/xml/impex/catalog/2006-10-31" catalog-id="apparel-catalog"> | |
<category-assignment category-id="womens-clothing-tops" product-id="008884303989"> | |
<primary-flag>true</primary-flag> | |
</category-assignment> | |
</catalog> | |
*/ | |
xsw.writeStartDocument("UTF-8", "1.0"); | |
xsw.writeStartElement('catalog'); | |
xsw.writeAttribute('xmlns', 'http://www.demandware.com/xml/impex/catalog/2006-10-31'); | |
xsw.writeAttribute('catalog-id', 'apparel-catalog'); | |
for(var i = 0; i < productsWithBrand.length; i++) { | |
xsw.writeStartElement('category-assignment'); | |
xsw.writeAttribute('category-id', 'womens-clothing-tops'); | |
xsw.writeAttribute('product-id', productsWithBrand[i].ID); | |
xsw.writeStartElement('primary-flag'); | |
xsw.writeCharacters('true'); | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
} | |
xsw.writeEndElement(); | |
xsw.writeEndDocument(); | |
xsw.flush(); | |
} catch(e) { | |
// let errorXML = e; | |
} finally { | |
xsw.close(); | |
fileWriter.close(); | |
} | |
} |
BUSCA POR ORDERS E ESCREVE UM XML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const File = require('dw/io/File'); | |
const FileWriter = require('dw/io/FileWriter'); | |
const XMLStreamWriter = require('dw/io/XMLStreamWriter'); | |
const OrderMgr = require('dw/order/OrderMgr'); | |
const Order = require('dw/order/Order'); | |
exports.execute = function(args) { | |
try { | |
// Order possible status values: | |
// EXPORT_STATUS_NOTEXPORTED | |
// EXPORT_STATUS_EXPORTED | |
// EXPORT_STATUS_READY | |
// EXPORT_STATUS_FAILED | |
var query = "exportStatus=" + Order.EXPORT_STATUS_NOTEXPORTED; | |
query += " or exportStatus=" + Order.EXPORT_STATUS_READY; | |
query += " or exportStatus=" + Order.EXPORT_STATUS_FAILED; | |
var orders = OrderMgr.queryOrders(query, "orderNo asc", null); | |
// uncomment count to debug | |
// var count = orders.getCount(); | |
writeOrdersXML(orders); | |
} catch(e) { | |
let errorXML = e; | |
} finally { | |
xsw.close(); | |
fileWriter.close(); | |
} | |
} | |
function writeOrdersXML(orders) { | |
// Save XML on: /on/demandware.servlet/webdav/Sites/Impex/src/exports/exportOrders.xml | |
var impexPath = File.IMPEX + File.SEPARATOR + 'src' + File.SEPARATOR + 'exports' + File.SEPARATOR + 'exportOrders.xml'; | |
var file = new File(impexPath); | |
var fileWriter = new FileWriter(file, 'UTF-8'); | |
var xsw = new XMLStreamWriter(fileWriter); | |
// Start to write the XML Order | |
xsw.writeStartElement('orders'); | |
xsw.writeAttribute('xmlns', 'http://www.demandware.com/xml/impex/catalog/2006-10-31'); | |
while(orders.hasNext()) { | |
var order = orders.next(); | |
xsw.writeStartElement('order'); | |
xsw.writeAttribute('order-no', order.getOrderNo()); | |
xsw.writeStartElement('order-date'); | |
xsw.writeCharacters(order.getCreationDate()); | |
xsw.writeEndElement(); | |
xsw.writeStartElement('customer'); | |
xsw.writeStartElement('customer-name'); | |
xsw.writeCharacters(order.getCustomerName()); | |
xsw.writeEndElement(); | |
xsw.writeStartElement('customer-no'); | |
xsw.writeCharacters(order.getCustomerNo()); | |
xsw.writeEndElement(); | |
xsw.writeStartElement('customer-email'); | |
xsw.writeCharacters(order.getCustomerEmail()); | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
xsw.writeStartElement('adjusted-merchandize-total'); | |
xsw.writeStartElement('gross-price'); | |
xsw.writeCharacters(order.getAdjustedMerchandizeTotalGrossPrice()); | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
xsw.writeStartElement('product-lineitems'); | |
// LOOP product-lineitems | |
var productLineItems = order.getAllProductLineItems(); | |
var prodLineItemsSize = productLineItems.size(); | |
var prodLineItemsArray = productLineItems.toArray(); | |
for(var i = 0; i < prodLineItemsSize; i++) { | |
xsw.writeStartElement('product-lineitem'); | |
xsw.writeStartElement('product-id'); | |
xsw.writeCharacters(prodLineItemsArray[i].productID); | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
} | |
xsw.writeEndElement(); | |
xsw.writeStartElement('payments'); | |
// LOOP payments | |
var orderPaymentInstrumentsArray = order.paymentInstruments.toArray(); | |
for (var j = 0; j < orderPaymentInstrumentsArray.length; j++) { | |
xsw.writeStartElement('payment'); | |
xsw.writeStartElement('payment-method'); | |
xsw.writeCharacters(orderPaymentInstrumentsArray[j].paymentMethod); | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
} | |
xsw.writeEndElement(); | |
xsw.writeEndElement(); | |
} | |
xsw.writeEndElement(); | |
xsw.flush(); | |
} |
ADICIONAR PRODUCT AO CART COM AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('./util'); | |
var page = require('./page'); | |
var dialog = require('./dialog'); | |
var addDirectlyToCart = function (e) { | |
e.preventDefault(); | |
let addDirectlyToCartLink = $('#hiddenLinkAddDirectlyToCart').attr('href'); | |
let productID = $('#productIdInput')[0].value; | |
let form = $('#productIdForm'); | |
$.ajax({ | |
url: addDirectlyToCartLink, | |
type: 'GET', | |
data: { | |
pid: productID | |
}, | |
crossDomain: true, | |
success: function(response) { | |
// When product does not exist | |
if (response.isProductMaster == null) { | |
openDialog(Resources.PRODUCTID_NOTFOUND); | |
} else if (response.isProductMaster) { // product exists and it is a master product | |
openDialog(Resources.PRODUCTID_ISMASTER); | |
} else { // product does exist and it is not master product | |
ajaxAddProduct(form); | |
} | |
}, | |
error: function(jqXHR, exception) { | |
console.log('FAIL'); | |
} | |
}); | |
}; | |
function ajaxAddProduct(form) { | |
console.log('inside ajaxAddProduct'); | |
// form must have an inpud with 'name' pid | |
$.ajax({ | |
url: util.ajaxUrl(Urls.addProduct), | |
type: 'POST', | |
crossDomain: true, | |
data: form.serialize(), | |
success: function(response) { | |
console.log('SUCCESS ajaxAddProduct'); | |
page.redirect(Urls.cartShow); | |
}, | |
error: function(jqXHR, exception) { | |
console.log('FAIL ajaxAddProduct'); | |
} | |
}); | |
} | |
module.exports = function () { | |
$('#productIdButton').on('click', addDirectlyToCart); | |
}; |
RETORNA DADOS DO CONTROLLER PARA O AJAX QUE O CHAMOU
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Response.renderJSON({ | |
isProductMaster: isProductMaster | |
}); |
NO FRONTEND ABRIR DIALOG
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function openDialog(resourceMsg) { | |
dialog.open({ | |
html: '<h1>' + resourceMsg + '</h1>', | |
options: { | |
buttons: [{ | |
text: Resources.OK, | |
click: function () { | |
$(this).dialog('close'); | |
} | |
}] | |
} | |
}); | |
} |
FAZER REQUISIÇÃO HTTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function performHttpRequest(requestURL) { | |
var message = null; | |
var requestResult = {}; | |
var httpClient = new HTTPClient(); | |
var status = new Status(Status.OK); | |
httpClient.setTimeout(25000); | |
httpClient.setTimeout(25000); | |
try { | |
httpClient.open('GET', requestURL); | |
httpClient.send(); | |
if ( httpClient.statusCode == 200 ) { | |
message = httpClient.text; | |
} else { | |
// error handling | |
status = new Status(Status.ERROR, httpClient.statusCode, 'Code: ' + httpClient.statusCode + ' Message: ' + httpClient.statusMessage); | |
} | |
var responseHeaders = new HashMap(); | |
let key; | |
for (key in httpClient.allResponseHeaders.keySet()) { | |
let value = httpClient.getResponseHeader(key); | |
responseHeaders.put(key, value); | |
} | |
requestResult.ResponseHeaders = responseHeaders; | |
} catch(e) { | |
let exception = e; | |
message = "An error occured with status code " + e; | |
status = new Status(Status.ERROR, httpClient.statusCode, e ); | |
} | |
requestResult.RawData = message; | |
requestResult.Status = status; | |
return requestResult; | |
} |
CRIAR E USAR SERVIÇO LocalServiceRegistry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CRIAR SERVIÇO LocalServiceRegistry | |
'use strict'; | |
const LocalServiceRegistry = require('dw/svc/LocalServiceRegistry'); | |
var flickrGetPhotos = LocalServiceRegistry.createService("flickr.get.photos", { | |
createRequest: function(svc, params) { | |
var serviceUrl = svc.getConfiguration().getCredential().getURL(); | |
// set the correct call URL | |
// svc.URL = serviceUrl + "?format=json&lang=en-us&nojsoncallback=true"; | |
svc.URL = serviceUrl + "?format=" + params.format + "&lang=" + params.lang + "&nojsoncallback=" + params.nojsoncallback; | |
// Need to set some header | |
svc.setEncoding('UTF-8'); | |
svc.setRequestMethod("GET"); | |
// svc.addHeader("Authorization", "Bearer " + params.token); | |
return svc; | |
}, | |
execute: function(svc, params) { | |
svc.send(params); | |
}, | |
parseResponse: function(svc, client) { | |
return client.text; | |
} | |
}); | |
exports.flickrGetPhotos = flickrGetPhotos; | |
// USO DE UM LocalServiceRegistry CRIADO | |
'use strict'; | |
var guard = require('app_storefront_controllers/cartridge/scripts/guard'); | |
var ISML = require('dw/template/ISML'); | |
var FlickrServiceRegistry = require('../scripts/FlickrServiceRegistry'); | |
function show() { | |
let svc = FlickrServiceRegistry.flickrGetPhotos; | |
// FlickrEndPoint: https://api.flickr.com/services/feeds/photos_public.gne | |
// Parameters: ?format=json&lang=en-us&nojsoncallback=true | |
let result = svc.setThrowOnError().call({ 'format':'json', 'lang':'en-us', 'nojsoncallback':'true' }); | |
if(result.isOk()) { | |
let content = result.getObject(); | |
let flickrFeed = JSON.parse(content); | |
let photoItems = flickrFeed.items; | |
ISML.renderTemplate( | |
'flickrfeed',{ | |
items : photoItems | |
} | |
); | |
} | |
} | |
exports.Show = guard.ensure(['get'], show); |
CREDENTIALS
Name: https.flickr.photos
URL: https://api.flickr.com/services/feeds/photos_public.gne
PROFILES
Name: Flickr Profile
Connection Timeout (ms): 10,000
Enable Circuit Breaker: check
Max Circuit Breaker Calls: 30
Circuit Breaker Interval (ms): 5,000
Enable Rate Limit: check
Max Rate Limit Calls: 30
Rate Limit Interval (ms): 5,000
SERVICES
Name: flickr.get.photos
Type: HTTP
Enabled: check
Service mode: Live
Log Name Prefix: flickrws
Communication Log Enabled: NO check
Force PRD behavior in non-PRD environments: check
Profile: Flickr Profile
Credentials: https.flickr.photos
<?xml version="1.0" encoding="UTF-8"?>
<oauth-providers xmlns="http://www.demandware.com/xml/impex/oauthprovider/2013-07-16">
<oauth-provider provider-id="Facebook">
<description>Facebook</description>
<client-id></client-id>
<client-secret></client-secret>
<scopes>email,public_profile</scopes>
<authorization-url>https://www.facebook.com/dialog/oauth</authorization-url>
<token-url>https://graph.facebook.com/oauth/access_token</token-url>
<user-info-url>https://graph.facebook.com/me?fields=email,first_name,last_name</user-info-url>
<access-token-name>access_token</access-token-name>
<redirect-pipeline-node>Login-OAuthReentry</redirect-pipeline-node>
</oauth-provider>
<oauth-provider provider-id="Google">
<description>Google</description>
<client-id></client-id>
<client-secret></client-secret>
<scopes>email,profile,openid</scopes>
<authorization-url>https://accounts.google.com/o/oauth2/auth</authorization-url>
<token-url>https://accounts.google.com/o/oauth2/token</token-url>
<user-info-url>https://www.googleapis.com/oauth2/v2/userinfo</user-info-url>
<access-token-name>access_token</access-token-name>
<redirect-pipeline-node>Login-OAuthReentry</redirect-pipeline-node>
</oauth-provider>
</oauth-providers>
Exemplos De Código Salesforce >>>>> Download Now
ResponderExcluir>>>>> Download Full
Exemplos De Código Salesforce >>>>> Download LINK
>>>>> Download Now
Exemplos De Código Salesforce >>>>> Download Full
>>>>> Download LINK pk