VtexUtils.js
A collection of utilities methods for Vtex stores.
Table of contents
Main
dist/├── vtex-utils.js (UMD)├── vtex-utils.min.js (UMD, compressed)├── vtex-utils.common.js (CommonJS, default)└── vtex-utils.esm.js (ES Module)
Getting started
Direct download
Download the script here and include it.
Package Managers
VtexUtils.js supports npm under the name vtex-utils
.
npm install vtex-utils --save
Module Loaders
VtexUtils.js can also be loaded as an CommonJS or ES6 module (recomended).
// CommomJSvar VtexUtils = ; // ES6 module;
Usage
With UMD (Universal Module Definition), the package is available on VTEX
namespace.
// Initialize constructorvar vtexUtils = ; // VtexHelpersvar vtexHelpers = vtexUtilsvtexHelpers; // GlobalHelpers (from UtilifyJS)var globalHelpers = vtexUtilsglobalHelpers; // LocationHelpers (from UtilifyJS)var locationHelpers = vtexUtilslocationHelpers; // Storage (from Store2 | https://github.com/nbubna/store)var storage = vtexUtilsstorage
UtilifyJS
Docs for vtexUtils.globalHelpers
and vtexUtils.locationHelpers
methods can be found on UtilifyJS
Vtex Methods
vtexHelpers.formatPrice(number[, thousands[, decimals[, length[, currency]]]])
Formats Vtex price
-
number:
- Type:
Integer
- The number to format
- Type:
-
thousands (optional):
- Type:
String
- Default:
'.'
- The thousands delimiter
- Type:
-
decimals (optional):
- Type:
String
- Default:
','
- The decimal delimiter
- Type:
-
length (optional):
- Type:
Integer
- Default:
2
- The length of decimal
- Type:
-
currency (optional):
- Type:
String
- Default:
'R$ '
- Set currency
- Type:
Example
vtexHelpers; // R$ 12,34vtexHelpers; // R$ 1.234,56vtexHelpers; // R$ 1234,560vtexHelpers; // $ 1,234.56
vtexHelpers.unformatPrice(value[, decimal[, formatNumber]])
Unformat Vtex price. Value can be a single string or an array of values
-
value:
- Type:
String|Array
- Price formatted
- Type:
-
decimal (optional):
- Type:
String
- Default:
','
- The decimal delimiter
- Type:
-
formatNumber (optional):
- Type:
Boolean
- Default:
false
- Thousands separator (pt-BR default:
'.'
)
- Type:
Example
var priceFormatted = 'R$ 1.234,56';vtexHelpers; // {unformatted: 123456, real: '1234', cents: '56'}vtexHelpers; // {unformatted: 123456, real: '1.234', cents: '56'} vtexHelpers;/*[ {unformatted: 1234, real: '12', cents: '34'} {unformatted: 2345, real: '23', cents: '45'} {unformatted: 3456, real: '34', cents: '56'}]*/
vtexHelpers.setInstallment(price, minPrice, maxInstallments[, interest])
Take the value of the installment with min price and max installments given
-
price:
- Type:
String|Number
- Price to get installments. Can be formatted price or a integer value.
- Type:
-
minPrice:
- Type:
String|Number
- Min price for each installment. Can be formatted price or a integer value.
- Type:
-
maxInstallments:
- Type:
Number
- Max installments
- Type:
-
interest (optional):
- Type:
Number
- Default:
0
- Interest rate
- Type:
Example
vtexHelpers // {installments: 8, installmentValue: 43737, interest: 0}vtexHelpers // {installments: 8, installmentValue: 43737, interest: 0}
vtexHelpers.getPercentage(oldPrice, newPrice[, length])
Get the percentage of a discount
-
oldPrice:
- Type:
String|Number
- Original price. Can be formatted price or a integer value.
- Type:
-
newPrice:
- Type:
String|Number
- Price with discount. Can be formatted price or a integer value.
- Type:
-
length (optional):
- Type:
Number
- Default:
0
- Number of decimals
- Type:
Example
vtexHelpers; // 17 (17% OFF)vtexHelpers; // 17.18 (17.18% OFF)
vtexHelpers.applyDiscountPercent(price, percent[, formatted])
Returns a discount amount or adding a set value.
-
price:
- Type:
String|Number
- Price to apply discount. Can be formatted price or a integer value.
- Type:
-
percent:
- Type:
String|Number
- Percentage to apply. Can be formatted price or a integer value.
- Type:
-
formatted (optional):
- Type:
Boolean
- Default:
false
- Format result
- Type:
Example
vtexHelpers; // {discountPrice: 355, priceWithDiscount: 599, priceWithIncrease: 1310}vtexHelpers; // {discountPrice: 355, priceWithDiscount: 599, priceWithIncrease: 1310}vtexHelpers; // {discountPrice: 355, priceWithDiscount: 599, priceWithIncrease: 1310}vtexHelpers; // {discountPrice: 'R$ 3,55', priceWithDiscount: 'R$ 5,99', priceWithIncrease: 'R$ 13,10'}
vtexHelpers.fixProductSearchPrice(val)
Formats price from Vtex API /api/catalog_system/pub/products/search/
to use in formatPrice
method
- val:
- Type:
Number
- Value to convert
- Type:
Example
vtexHelpers; // 25025
vtexHelpers.getFirstAvailableSku(product)
Get first available SKU from Vtex API /api/catalog_system/
end point
Returns an object with first available SKU or false if all are unvailable
- product:
- Type:
Object
- Product full data
- Type:
Example
vtexjscatalog ;
vtexHelpers.getOriginalImage(src)
Get the original VTEX image source from a thumb
- src:
- Type:
String
- The source of the thumb
- Type:
Example
vtexHelpers;// http://domain.vteximg.com.br/arquivos/ids/155242/image.png
vtexHelpers.getResizedImage(src, width, height)
Change the width & height from a given VTEX image source
-
src:
- Type:
String
- The source of the image
- Type:
-
width:
- Type:
String | Integer
- The new image with
- Type:
-
height:
- Type:
String | Integer
- The new image height
- Type:
Example
vtexHelpers;// http://domain.vteximg.com.br/arquivos/ids/155242-500-600/image.png vtexHelpers;// http://domain.vteximg.com.br/arquivos/ids/155242-100-100/image.png
vtexHelpers.getResizeImageByRatio(src, type, newSize, aspectRatio)
Resize proportionally an VTEX image by aspect ratio
-
src:
- Type:
String
- The source of the image
- Type:
-
type:
- Type:
String
- Type to resize (width or height)
- Type:
-
newSize:
- Type:
Number
- New size to redimensioning
- Type:
-
aspectRatio:
- Type:
Number
- Image aspect ratio (calculate by (width / height))
- Type:
Example
var imgSrc = 'http://domain.vteximg.com.br/arquivos/ids/155242-292-292/image.png';var newSize = 250;var aspectRatio = 10/15; vtexHelpers;// http://domain.vteximg.com.br/arquivos/ids/155242-250-375/image.png vtexHelpers;// http://domain.vteximg.com.br/arquivos/ids/155242-167-250/image.png
vtexHelpers.getServerTime(callback)
Get the Vtex server time
- callback:
- Type:
Function
- The callback to call when the request finishes. The callback will a javascript Date object.
- Type:
Example
vtexHelpers;
vtexHelpers.getCategories([categoryId[, depth]])
Get category tree
-
categoryId (optional):
- Type:
Integer
- Default:
undefined
- Return the specific Category
- Type:
-
depth (optional):
- Type:
Integer
- Default:
50
- The tree depth
- Type:
Example
vtexHelpers; // Return all categories vtexHelpers; // Return first level from category id
vtexHelpers.getProductSpec(data, specName[, defaultVal])
Get product specification
-
data:
- Type:
Object
- Vtex API data from
/api/catalog_system/pub/products/search/
endpoint
- Type:
-
specName:
- Type:
String
- Specification name
- Type:
-
defaultVal (optional):
- Type:
Boolean|String
- Default:
false
- Value to return if spec doesn't exists
- Type:
Example
// Data from API '/api/catalog_system/pub/products/search/'var response = Características: "Cor real" "Ocasião" "Composição" "Cor" Composição: "Liga Mista, Pedra Natural Pirita" Cor: "Dourado" Cor real: "Ouro" Ocasião: "Weekend" allSpecifications: "Cor real" "Ocasião" "Composição" "Cor" // More data...; vtexHelpers; // 'Dourado'vtexHelpers; // falsevtexHelpers; // 'Branco'
vtexHelpers.getShipping(postalCode[, skuId[, quantity]])
Get product shipping value.
-
postalCode:
- Type:
String
- Postal code to calculate. Can be
xxxxx-xxx
orxxxxxxxx
format
- Type:
-
skuId (optional):
- Type:
Integer
- Default:
skuId
- Sku ID to calculate. If not passed, get first sku available on product page from
skuJson
global variable. If this method used on other pages,skuId
is required
- Type:
-
quantity (optional):
- Type:
Integer
- Default:
1
- Product quantity to calculate
- Type:
Example
// On product page with a valid postal codevtexHelpers ; /* Case success, will return an object with properties: { error: false, formattedResponse: { shippingValue: 'R$ 10,00', shippingText: 'Entrega em 4 dias úteis para o CEP 01010-010', shippingType: 'Frete Transportadora' } fullResponse: '<table><thead>...' // Original content from api } Case failed (invalid postal code, invalid sku ID, etc.), will return { error: true, formattedResponse: { shippingText: 'Não é possível calcular o valor do Frete para o CEP informado' } fullResponse: '<div class="cep-invalido" id="divFreteInvalido">...' // Original content from api }*/
vtexHelpers.replaceBreakLines(str)
Replace break lines from product descriptions/more
- str:
- Type:
String
- String to replace
- Type:
Example
var string = 'Foo\nBar\n\rBaz\r'; vtexHelpers; // 'Foo<br />Bar<br /><br />Baz<br />'
vtexHelpers.stringIdsToArray(str[, separator])
Convert a string IDs given into an integer array values
-
str:
- Type:
String
- String with IDs
- Type:
-
separator (optional):
- Type:
String
- Default:
','
- Separator to split
- Type:
Example
var commaStr = '1, 2, 3, 4';; // [1, 2, 3, 4] var dashedStr = ' - 1 - 2 - 3 - 4 - ';; // [1, 2, 3, 4]
vtexHelpers.checkLogin()
Check if the user is logged into Vtex
Example
vtexHelpers;
vtexHelpers.openPopupLogin([noReload[, url]])
Open default Vtex popup login.
Before use, don't forget to import Vtex Controller <vtex.cmc:welcomeMessage/>
-
noReload (optional):
- Type:
Boolean
- Default:
false
- Reload page after login
- Type:
-
url (optional):
- Type:
Boolean
- Default:
'/'
- Url to rdirect
- Type:
Example
vtexHelpers; // Open popup and reload page after success loginvtexHelpers; // Open popup and don't reload page after success loginvtexHelpers; // Open popup and don't reload page after success login and redirect to Account page
TIP
Use $(window).on('closed.vtexid', callback)
event to set any property if noReload
is true
If noReload
is true
, it'll ignore url
param
vtexHelpers.addToCart(items[, expectedOrderFormSections[, salesChannel]])
Open default Vtex popup login.
Require vtexjs
.
-
items:
- Type:
Array
- An Array of Objects with item(s) to add
- Type:
-
expectedOrderFormSections (optional):
- Type:
Array
- Default:
null
- Fields to retrieve
- Type:
-
salesChannel (optional):
- Type:
Integer/String
- Default:
1
- Sales Channel id
- Type:
Example
var items = id: 1 quantity: 1 seller: '1' id: 2 quantity: 2 seller: '1' ; vtexHelpers;
vtexHelpers.clearCart()
Remove all items from cart.
Require vtexjs
.
Example
vtexHelpers ;
vtexHelpers.notifyMe(name, email, skuId)
Send notify me data for unavailable products.
Return a promise.
-
name:
- Type:
String
- Customer name
- Type:
-
email:
- Type:
String
- Customer e-mail
- Type:
-
skuId:
- Type:
Integer
- Sku ID (if product ID passed, will return a fail promise)
- Type:
Example
var name = 'Test Notify';var email = 'test.notify@email.com';var skuId = 12321; vtexHelpers ;
Rivets Utilify
Docs for RivetsUtilify can be found here
To set RivetsUtilify:
// Import RivetsUtilify<script type="text/javascript" src="rivets-utilify.min.js"></script> // Initialize constructorvar vtexUtils = ; // Sets methodvtexUtils;
Tests
Tests are using mocha. To run the tests use:
$ npm test
License
VtexUtils.js is open-sourced software licensed under the MIT license.
Dependencies
jQuery 1.8.3+
vtexjs