0.2.1 • Published 5 years ago

spire-js v0.2.1

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

Spire JavaScript Client

This package provides convenient access to the Spire REST API from applications written in JavaScript.

Installation

Install the package with:

npm install spire-js

Usage

Import the Spire package

var spire = require('spire-js');

Or if your JavaScript environment supports ES6:

import spire from 'spire-js';

Connect to Your Spire Server

Supply a hostname or IP address for your Spire server.

spire.connectServer(address);

If your Spire Server is running on a different port than the default (10880) you can pass the port to connectServer:

spire.connectServer('127.0.0.1', 10881);

Connections from Server Environment (Node.js)

For Spire Server 3.2 and earlier using a self-signed certificate you will need to disable certificate validation:

export NODE_TLS_REJECT_UNAUTHORIZED=0

Authenticate a User

Supply a username and password for a Spire account on the connected server:

spire.authenticate(username, password);

Listing Companies

To list companies that have been setup on your Spire server, create a CompanyList instance and call fetch:

var companies = new spire.company.CompanyList();
companies.fetch({
  success: function(results) {
    var company = results.get('inspire');
    // Do stuff with company...
  }
});

The CompanyList collection will be populated with instances of Company for each company that is configured on your server. See Company for details about the attributes of a Company object.

Setting Company

Requests for resources owned by a particular company require the company to be set on your Spire API instance prior to using them. Provide a Company instance obtained above, or a company name (string) as the company argument here:

spire.setCompany('inspire');

Working With Collections

The following collections are provided by this package:

Description
spire.company.CompanyListCompanies
spire.customer.CustomerListCustomers
spire.employee.EmployeeListEmployees
spire.gl.GLAccountListGL Accounts
spire.gl.GLTransactionListGL Transactions
spire.inventory.InventoryAdjustmentListInventory Adjustments and Transfers
spire.inventory.InventoryListInventory
spire.inventory.PriceMatrixListPrice Matrices
spire.job.JobListJobs
spire.paymentMethod.PaymentMethodListPayment Methods
spire.paymentTerms.PaymentTermsListPayment Terms
spire.payroll.TimecardListTimecards
spire.purchasing.PurchaseHistoryListPurchase History
spire.purchasing.PurchaseOrderListPurchase Orders
spire.sales.SalesHistoryListSales History
spire.sales.SalesOrderListSales Orders
spire.salesperson.SalespersonListSalespeople
spire.territory.TerritoryListTerritories
spire.vendor.VendorListVendors

Collections can be queried by providing an object to the fetch() method:

var salesOrders = new spire.sales.SalesOrderList();

salesOrders.fetch({
  data: {
    start: 0,                // Starting offset
    limit: 100,              // Limit number of results
    //fields: 'id,orderNo',  // Comma separated list of fields to return (defaults to all fields)
    //q: 'search query',     // Search for keywords

    // Filter results
    filter: JSON.stringify({
        orderDate: spire.utils.formatDate(new Date())  // Today's orders
    })
  },

  success: function(collection, response, options) {
    // Actions to perform on success
    collection.map(function(order) {
      // 'Inflate' order
      order.fetch({
        success: function(order) {
          console.log(order);
        }
      });
    });
  },

  error: function(collection, response, options) {
    // Actions to perform on error
  },

  reset: false  // Reset collection with new objects or append to it
                // (defaults to append)
});

Model instances populated during a fetch operation may not have all of their attributes defined because the collection endpoint on the Spire server does not always provide a complete representation. This is more common with complex objects like orders, and is generally to preserve the performance of the list. To "inflate" the Model instance you can call fetch() on each one (which dispatches a request to the server for the complete representation) and will populate the undefined attributes.

Alternately, you can get a specific record from the server using the getOrFetch method on the collection (model instances returned will be fully inflated):

salesOrders.getOrFetch(1, function(err, model) {
  if(err) {
    console.log('An error occurred');
  } else {
    console.log(model);
  }
});

Once a collection is populated with model instances (following a successful fetch) you can get a specific ID from the collection using either its primary key (usually 'id'), or by specifying a user-facing key like orderNo (this may not work in all cases).

salesOrders.get(1);

// OR

salesOrders.get('00000100-0', 'orderNo');

More information about working with collections can be found here:

ampersand-rest-collection

Working With Model Objects

The following models are provided by this package:

Description
spire.company.CompanySpire Company
spire.customer.CustomerCustomer
spire.employee.EmployeeEmployee
spire.gl.GLAccountGL Account
spire.gl.GLTransactionGL Transaction
spire.gl.GLTransactionItemGL Transaction Item
spire.inventory.InventoryAdjustmentInventory Adjustment and Transfer
spire.inventory.InventoryAdjustmentItemInventory Adjustment Item
spire.inventory.InventoryInventory
spire.inventory.PriceMatrixPrice Matrix
spire.paymentMethod.PaymentMethodPayment Method
spire.paymentTerms.PaymentTermsPayment Terms
spire.payroll.TimecardTimecard
spire.payroll.TimecardEntryTimecard Entry
spire.purchasing.PurchaseHistoryPurchase History
spire.purchasing.PurchaseOrderPurchase Order
spire.purchasing.PurchaseOrderItemPurchase Order Item
spire.sales.SalesHistorySales History
spire.sales.SalesHistoryItemSales History Item
spire.sales.SalesOrderSales Order
spire.sales.SalesOrderItemSales Order Item
spire.sales.SalesOrderPaymentSales Order Payment
spire.salesperson.SalespersonSalesperson
spire.territory.TerritoryTerritory
spire.vendor.VendorVendor

The create, read, update, delete (CRUD) functions are provided by the following methods on a Model instance:

MethodDescription
saveCreates the object if new (POST), otherwise updates it (PUT)
destroyAttempts to delete the object (DELETE)
fetchRefreshes the object from the server

To load a specific object by ID:

var salesOrder = new spire.sales.SalesOrder({id: 1});
salesOrder.fetch({
  success: function() {
    console.log('Successfully loaded object');
  },

  error: function() {
    console.log('An error occurred');
  }
});

To delete an object:

salesOrder.destroy({
  success: function() {
    console.log('Successfully deleted object');
  },

  error: function() {
    console.log('An error occurred');
  }
});

Change an attribute and update the object:

salesOrder.requiredDate = new Date();
salesOrder.save();

Example Sales Order Creation

// Create an order instance
var salesOrder = new spire.sales.SalesOrder();

// Create a customer
var customer = new spire.customer.Customer();
customer.name = 'Arya Stark';
customer.save();
salesOrder.customer = customer;

// Create an item
var item = new spire.sales.SalesOrderItem();
item.inventory.whse = '00';
item.inventory.partNo = 'TEST';  // partNo must exist in whse
salesOrder.items.add(item);

salesOrder.save();

More information about working with individual model objects can be found here:

ampersand-model

Custom Types

Decimal

Generally values returned from the Spire API as JSON map to native JavaScript types. A notable exception is decimal values returned from the Spire API as strings. It is inconvenient to work with string and int objects for business operations, and native floating point Numeric objects won't work for this purpose, so this library provides a types.Decimal type. Objects returned from the API are automatically deserialized with this type where necessary, and serialized back to strings for persistence operations. The decimal type currently employed is actually a big.js object that has been lightly modified to add thousands separators via the format() method.

Example:

var dec = new spire.types.Decimal('1021.25');
dec.format();
// 1,021.25

Utilities

Date Formatting

The Spire API expects local date strings to be in the format 'YYYY-MM-DD' for communication with the server. The spire.utils namespace provides the formatDate function that will take a JavaScript Date object and serialize it into a string in the expected format. This is generally not required when working with collections and model objects; however, it can be helpful when building filter criteria.

spire.utils.formatDate(new Date());
// '2017-10-16'