cocoel-sdk

0.7.0 • Public • Published

cocoel-sdk

sdk and toolkit for cocoel.io implementation

Installation

Into your project's root directory run the following command:

npm

npm i -P cocoel-sdk

yarn

yarn add cocoel-sdk

This package only has 4 dependencies:

  • axios@0.17.1
  • socket.io-client@2.0.4
  • validator@9.4.0

Usage

// signIn

import CocoelSDK from 'cocoel-sdk';

CocoelSDK.signIn({ username: 'foosername', password: 'SuperSecret' }).then((res) => {
  // fetching User data

  const cocoel = new CocoelSDK(res.token);

  cocoel.getUser()
    .then(userData => console.log(`Hello ${userData.PersonalInfo.name}`))
    .catch(error => console.error(error));
}).catch(error => console.error(error));

If you have alredy signedIn in another part of the code, you can simply call new CocoelSDK() without pass any token.

// fetching User data
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.getUser()
  .then(userData => console.log(`Hello ${userData.PersonalInfo.name}`))
  .catch(error => console.error(error));

API

This package is a Class who generates all aviable methods for cocoel.io public actions and only needs the JWT or signIn for first time with is static method.

Auth

constructor(JWT [, baseURL = 'http://cocoel.io/api/', lang = 'es'])

It takes the JWT and build all methods and tools.

The JWT is required, but can be omited only if you have alredy signIn or signUp because is stored in localStorage.

static signIn({ username, password } [, baseURL = 'http://cocoel.io/api/', lang = 'es'])

Static method for auth and return a promise who resolves the JWT.

Example
import CocoelSDK from 'cocoel-sdk';

CocoelSDK.signIn({ username: 'foosername', password: 'SuperSecret' })
  .then(res => console.log(res)) // { token: 'eyJhbGciOiJIUzI1NiI...' }
  .catch(error => console.error(error));

The token object has the following structure:

// @flow

type TokenType = {
  token: string
};

static signUp({ username, password, email, PersonalInfo: { name, lastName } } [, baseURL = 'http://cocoel.io/api/', lang = 'es'])

Static method for register a new user and return a promise who resolves the JWT.

Example
import CocoelSDK from 'cocoel-sdk';

CocoelSDK.signUp({
  username: 'foosername',
  password: 'SuperSecret',
  email: 'foo@bar.com',
  phoneNumber: '5511272165',
  PersonalInfo: {
    name: 'Foo',
    lastName: 'Bar',
  },
}).then(res => console.log(res)) // { token: 'eyJhbGciOiJIUzI1NiI...' }
  .catch(error => console.error(error));

The user object has the following structure:

// @flow

type TokenType = {
  PersonalInfo: {
    name: string,
    lastName: string
  },
  username: string,
  email: string
  validEmail: boolean,
  phoneNumber: string,
  validPhoneNumber: boolean
};

signOut()

Method for delete all credentials and socket connections for current session and return a promise who resolves when everything is done, there is no rejections posible.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.signOut().then(() => console.log('Session finished'));

User

getUser()

Method for fetch user basic data and return a promise who resolves with and object.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.getUser()
  .then(userData => console.log(`Hello ${userData.PersonalInfo.name}`))
  .catch(error => console.error(error));

The user object has the following structure:

// @flow

type UserType = {
  PersonalInfo: {
    name: string,
    lastName: string
  },
  username: string,
  email: string
  validEmail: boolean,
  phoneNumber: string,
  validPhoneNumber: boolean
};

updateUser(newUserData)

Method for update user basic data who recibes newUserData object only with new data, for example, if want to change the email, just sending: { email: 'foo@bigcompany.com' } will be enough.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.updateUser({
  PersonalInfo: {
    name: 'Foorgan',
    lastName: 'Barman',
  },
  email: 'awesome_guy@aol.com',
  phoneNumber: '5511272165',
})
  .then(() => console.log('User updated'))
  .catch(error => console.error(error));

The user object with the valid fields who can change has the following structure:

// @flow

type UserType = {
  PersonalInfo: {
    name: string,
    lastName: string
  },
  email: string
  validEmail: boolean,
  phoneNumber: string,
  validPhoneNumber: boolean
};

If you wanted for getting the new information, we suggest use suscribeUserChanges() method.

suscribeUserChanges([callback(error, newUserData, getUserMethod)])

Method for create a socket tunnel and execute callback with new userData as parameter everytime the userData changes. This method can be executed without callback and if was suscribed before and passed a callback, the same callback still works, this is because if you have unsuscribe and suscribe later don't have to pass the callback again.

When this method is called with a callback, the callback will be executed inmediatly end returning the actual userData. But if is called without callback, the callback only will be executed once the socket is dispatched.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.suscribeUserChanges((error, newUserData) => {
  if (error) return new Error(error);
  console.log(newUserData); // This will execute async and everytime someone changes his user info
});

The newUserData object has the following structure:

// @flow

type UserType = {
  PersonalInfo: {
    name: string,
    lastName: string
  },
  username: string,
  email: string
  validEmail: boolean,
  phoneNumber: string,
  validPhoneNumber: boolean
};

unsuscribeUserChanges()

This method close the socket tunnel oppened only in the suscribeUserChanges(callback) method. This is reversible calling again the suscribeUserChanges() without a callback to preserve the original callback.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.suscribeUserChanges(); // Now you won't be able to listen user changes on real time

removeUser()

Method for remove cureent user and reasign its commerces to a delegate employee if its exists. This method returns a promise and resolves if everything works well.

Also after this method is resolves, the stored token will be deleted.

¡WARNING! This method is irreversible and must be used carefully. Its recomended use some validation before run this method.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.removeUser()
  .then(() => console.log('User deleted'))
  .catch(error => console.error(error));

Commerce

getCommerces()

Method for fetch 2 lists with basic commerce info data and return a promise who resolves with and object. The lists are the own commerces and employeed commerces.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.getCommerces().then((listOfCommerces) => {
  listOfCommerces.Commerces.owner.forEach((commerce) => {
    console.log(`You are owner of ${commerce.name}`);
  });

  listOfCommerces.Commerces.employee.forEach((commerce) => {
    console.log(`You are employee of ${commerce.name}`);
  });
}).catch(error => console.error(error));

The commerces list object has the following structure:

// @flow

type Commerces = {
  Commerces: {
    owner: Array<{
      publicId: string,
      branchOffice: boolean, // True if is a branchOffice
      created: string, // Datetime, is a string and can be parsed
      active: boolean, // false if is in deleting process
      name: string,
      masterOffice: string // Public id of the masterOffice
    }>,
    employee: Array<{
      publicId: string,
      branchOffice: boolean, // True if is a branchOffice
      created: string, // Datetime, is a string and can be parsed
      active: boolean, // false if is in deleting process
      name: string,
      masterOffice: string // Public id of the masterOffice
    }>
  }
}

suscribeCommercesChanges([callback(error, newCommercesList, getCommercesMethod)])

Method for create a socket tunnel and execute callback with new commerces list as parameter everytime own commerce or when you are employeed changes. This method can be executed without callback and if was suscribed before and passed a callback, the same callback still works, this is because if you have unsuscribe and suscribe later don't have to pass the callback again.

When this method is called with a callback, the callback will be executed inmediatly end returning the actual commerces list. But if is called without callback, the callback only will be executed once the socket is dispatched.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.suscribeCommercesChanges((error, newListOfCommerces) => {
  if (error) return new Error(error);

  // The following will execute async and everytime someone changes one of the commerce in the list

  listOfCommerces.Commerces.owner.forEach((commerce) => {
    console.log(`You are owner of ${commerce.name}`);
  });

  listOfCommerces.Commerces.employee.forEach((commerce) => {
    console.log(`You are employee of ${commerce.name}`);
  });
});

The commerces list object has the following structure:

// @flow

type Commerces = {
  Commerces: {
    owner: Array<{
      publicId: string,
      branchOffice: boolean, // True if is a branchOffice
      created: string, // Datetime, is a string and can be parsed
      active: boolean, // false if is in deleting process
      name: string,
      masterOffice: string // Public id of the masterOffice
    }>,
    employee: Array<{
      publicId: string,
      branchOffice: boolean, // True if is a branchOffice
      created: string, // Datetime, is a string and can be parsed
      active: boolean, // false if is in deleting process
      name: string,
      masterOffice: string // Public id of the masterOffice
    }>
  }
}

unsuscribeCommercesChanges()

This method close the socket tunnel oppened only in the suscribeCommercesChanges(callback) method. This is reversible calling again the suscribeCommercesChanges() without a callback to preserve the original callback.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.unsuscribeCommercesChanges(); // Now you won't be able to listen commerces list changes on real time

addCommerce(commerce)

Method for create a new commerse and return a promise who resolves the new commerce object.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK;

cocoel.newCommerce({
  name: 'Teston',
  brachOffice: false,
  Address: {
    country: 'México',
    state: 'Veracruz',
    city: 'Orizaba',
    zipCode: '94399',
    Assentiment: {
      kind: 'Colonia',
      name: 'Centro',
    },
    street: 'Oriente 6',
    externalNumber: '1068',
    internalNumber: 'Local 4',
    references: 'Dentro de Plaza Oriente 17',
  },
  phone: '2727268422',
  Schedule: [{
    day: 'Sunday',
    closed: true,
  }, {
    day: 'Monday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Tuesday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Wednesday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Thursday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Friday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Saturday',
    closed: true,
  }],
  SpecialSchedule: [{
    day: '03/18/2018', // Only the specific day of specific year
    closed: true,
    reason: 'Trip of the company',
  }, {
    day: '12/24', // Every Dec. 24
    closed: true,
    reason: 'Closed for the holidays, Merry Christmas to all our consumers! :)',
  }, {
    day: '12/25', // Every Dec. 25
    times: [{ in: '14:00', out: '20:00' }],
    reason: 'Is Christmas time :)',
  }, {
    day: '1', // Every 1° of the month
    times: [{ in: '14:00', out: '20:00' }],
    reason: 'We open late for inventory counting',
  }],
}).then((newCommerce) => {
  console.log(`Your commerce is now created. Open it at http://cocoel.io/${newCommerce.publicId}`);
}).catch(error => console.error(error));

The commerces object has the following structure:

// @flow

type Commerces = {
  publicId: string,
  branchOffice: boolean,
  Employees: Array<EmployeeType>,
  Transactions: Array<TransactionType>,
  Address: {
    Assentiment: {
      kind: string,
      name: string
    },
    country: string,
    state: string,
    city: string,
    zipCode: string,
    street: string,
    externalNumber: string,
    internalNumber: string,
    references: string
  },
  Schedule: Array<{ // The array only take first 7 items, each for week day
    day: string,
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean
  }>,
  SpecialSchedule: Array<{
    day: string, // Can set specific day in specific year '03/18/2018', specific day in specific month '12/25' or a day every month '3'
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean,
    reason?: string
  }>,
  created: string,
  active: true,
  deleted: false,
  recycleBin: Array<any>,
  name: string,
  phone: string
}

getCommerce(publicId)

Method for fetch specific commerce info data and return a promise who resolves with and object.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.getCommerce('HJFmtW6vf') // publicId is given in the commerces list
  .then((commerce) => {
    console.log(`You can see now ${commerce.name}:\n\n${JSON.stringify(commerce, undefined, 2)}`);
  });
  .catch(error => console.error(error));

The commerce object has the following structure:

// @flow

type Commerces = {
  publicId: string,
  branchOffice: boolean,
  Employees: Array<EmployeeType>,
  Transactions: Array<TransactionType>,
  Address: {
    Assentiment: {
      kind: string,
      name: string
    },
    country: string,
    state: string,
    city: string,
    zipCode: string,
    street: string,
    externalNumber: string,
    internalNumber: string,
    references: string
  },
  Schedule: Array<{ // The array only take first 7 items, each for week day
    day: string,
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean
  }>,
  SpecialSchedule: Array<{
    day: string, // Can set specific day in specific year '03/18/2018', specific day in specific month '12/25' or a day every month '3'
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean,
    reason?: string
  }>,
  created: string,
  active: true,
  deleted: false,
  recycleBin: Array<any>,
  name: string,
  phone: string
}

suscribeCommerceChanges(publicId [, callback(error, newCommerce, getCommerceMethod)])

Method for create a socket tunnel and execute callback with new commerce object as parameter everytime this specific commerce changes. This method can be executed without callback and if was suscribed before and passed a callback, the same callback still works, this is because if you have unsuscribe and suscribe later don't have to pass the callback again.

When this method is called with a callback, the callback will be executed inmediatly end returning the actual commerces list. But if is called without callback, the callback only will be executed once the socket is dispatched.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.suscribeCommerceChanges('HJFmtW6vf', (error, commerce) => {
  if (error) return new Error(error);

  console.log(`You can see now ${commerce.name}:\n\n${JSON.stringify(commerce, undefined, 2)}`);
});

The commerce object has the following structure:

// @flow

type Commerces = {
  publicId: string,
  branchOffice: boolean,
  Employees: Array<EmployeeType>,
  Transactions: Array<TransactionType>,
  Address: {
    Assentiment: {
      kind: string,
      name: string
    },
    country: string,
    state: string,
    city: string,
    zipCode: string,
    street: string,
    externalNumber: string,
    internalNumber: string,
    references: string
  },
  Schedule: Array<{ // The array only take first 7 items, each for week day
    day: string,
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean
  }>,
  SpecialSchedule: Array<{
    day: string, // Can set specific day in specific year '03/18/2018', specific day in specific month '12/25' or a day every month '3'
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean,
    reason?: string
  }>,
  created: string,
  active: true,
  deleted: false,
  recycleBin: Array<any>,
  name: string,
  phone: string
}

unsuscribeCommerceChanges(publicId)

This method close the socket tunnel oppened only in the suscribeCommerceChanges(callback) method. This is reversible calling again the suscribeCommerceChanges() without a callback to preserve the original callback.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.unsuscribeCommerceChanges(); // Now you won't be able to commerce data changes on real time

updateCommerce(publicId, newCommerceData)

This method update an existing commerce with an object only with the fields to change and return a promise who resolves nothing if everything is ok.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.updateCommerce('HJFmtW6vf', {
  Schedule: [{ // This set the schedule and declare friday is now closed.
    day: 'Sunday',
    closed: true,
  }, {
    day: 'Monday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Tuesday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Wednesday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Thursday',
    times: [{ in: '08:00', out: '14:00' }, { in: '16:00', out: '20:00' }],
  }, {
    day: 'Friday',
    closed: true,
  }, {
    day: 'Saturday',
    closed: true,
  }],
}).then(() => console.log('Commerce updated')).catch(error => console.error(error));

The commerce object with valid updatable fields has the following structure:

// @flow

type Commerces = {
  publicId: string,
  branchOffice: boolean,
  Address: {
    Assentiment: {
      kind: string,
      name: string
    },
    country: string,
    state: string,
    city: string,
    zipCode: string,
    street: string,
    externalNumber: string,
    internalNumber: string,
    references: string
  },
  Schedule: Array<{ // The array only take first 7 items, each for week day
    day: string,
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean
  }>,
  SpecialSchedule: Array<{
    day: string, // Can set specific day in specific year '03/18/2018', specific day in specific month '12/25' or a day every month '3'
    times?: Array<{
      in: string,
      out: string
    }>,
    closed?: boolean,
    reason?: string
  }>,
  name: string,
  phone: string
}

startDeleteCommerce(publicId)

Method for start a commerce deletion process and return a promise who resolves nothing if everything is ok. Deletion process is when user wants to delete the commerece, but the arch gives to him 14 days before irreversible deletion.

¡WARNING! This method can be reversible ONLY INSIDE THE 14 DAYS after that, all info will be lost.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.startDeleteCommerce('HJFmtW6vf').then(() => {
  console.log('This commerce will be permanently deleted in 14 days');
}).catch(error => console.error(error));

stopDeleteCommerce(publicId)

Method for stop a commerce deletion process and return a promise who resolves nothing if everything is ok. Deletion process is when user wants to delete the commerece, but the arch gives to him 14 days before irreversible deletion.

Example
import CocoelSDK from 'cocoel-sdk';

const cocoel = new CocoelSDK();

cocoel.stopDeleteCommerce('HJFmtW6vf').then(() => {
  console.log('This commerce will not delete');
}).catch(error => console.error(error));

Readme

Keywords

none

Package Sidebar

Install

npm i cocoel-sdk

Weekly Downloads

3

Version

0.7.0

License

MIT

Unpacked Size

460 kB

Total Files

29

Last publish

Collaborators

  • edgravill