Skip to content
This repository has been archived by the owner on Apr 21, 2022. It is now read-only.
/ spire-js Public archive

Spire JavaScript Client

License

Notifications You must be signed in to change notification settings

spiresystems/spire-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

48 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.CompanyList Companies
spire.customer.CustomerList Customers
spire.employee.EmployeeList Employees
spire.gl.GLAccountList GL Accounts
spire.gl.GLTransactionList GL Transactions
spire.inventory.InventoryAdjustmentList Inventory Adjustments and Transfers
spire.inventory.InventoryList Inventory
spire.inventory.PriceMatrixList Price Matrices
spire.job.JobList Jobs
spire.paymentMethod.PaymentMethodList Payment Methods
spire.paymentTerms.PaymentTermsList Payment Terms
spire.payroll.TimecardList Timecards
spire.purchasing.PurchaseHistoryList Purchase History
spire.purchasing.PurchaseOrderList Purchase Orders
spire.sales.SalesHistoryList Sales History
spire.sales.SalesOrderList Sales Orders
spire.salesperson.SalespersonList Salespeople
spire.territory.TerritoryList Territories
spire.vendor.VendorList Vendors

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.Company Spire Company
spire.customer.Customer Customer
spire.employee.Employee Employee
spire.gl.GLAccount GL Account
spire.gl.GLTransaction GL Transaction
spire.gl.GLTransactionItem GL Transaction Item
spire.inventory.InventoryAdjustment Inventory Adjustment and Transfer
spire.inventory.InventoryAdjustmentItem Inventory Adjustment Item
spire.inventory.Inventory Inventory
spire.inventory.PriceMatrix Price Matrix
spire.paymentMethod.PaymentMethod Payment Method
spire.paymentTerms.PaymentTerms Payment Terms
spire.payroll.Timecard Timecard
spire.payroll.TimecardEntry Timecard Entry
spire.purchasing.PurchaseHistory Purchase History
spire.purchasing.PurchaseOrder Purchase Order
spire.purchasing.PurchaseOrderItem Purchase Order Item
spire.sales.SalesHistory Sales History
spire.sales.SalesHistoryItem Sales History Item
spire.sales.SalesOrder Sales Order
spire.sales.SalesOrderItem Sales Order Item
spire.sales.SalesOrderPayment Sales Order Payment
spire.salesperson.Salesperson Salesperson
spire.territory.Territory Territory
spire.vendor.Vendor Vendor

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

Method Description
save Creates the object if new (POST), otherwise updates it (PUT)
destroy Attempts to delete the object (DELETE)
fetch Refreshes 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'

About

Spire JavaScript Client

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published