2
0
forked from Wavyzz/dolibarr

Merge branch 'refactor-rest-api' of

https://github.com/EuskalMoneta/dolibarr into
EuskalMoneta-refactor-rest-api

Conflicts:
	htdocs/api/admin/explorer.php
This commit is contained in:
Laurent Destailleur
2016-07-27 14:06:14 +02:00
21 changed files with 2514 additions and 122 deletions

View File

@@ -104,17 +104,43 @@ foreach ($modulesdir as $dir)
{ {
while (($file_searched = readdir($handle_part))!==false) while (($file_searched = readdir($handle_part))!==false)
{ {
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) // Support of the deprecated API.
if (is_readable($dir_part.$file_searched) && preg_match("/^api_deprecated_(.*)\.class\.php$/i",$file_searched,$reg))
{ {
$classname=$reg[1]; $classname = ucwords($reg[1]).'Api';
$classname = str_replace('Api_','',ucwords($reg[1])).'Api'; require_once $dir_part.$file_searched;
$classname = ucfirst($classname); if (class_exists($classname))
{
dol_syslog("Found deprecated API classname=".$classname);
$api->r->addAPIClass($classname, '');
}
}
elseif (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i",$file_searched,$reg))
{
$classname = ucwords($reg[1]);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname))
{
dol_syslog("Found API classname=".$classname);
$listofapis[] = $classname;
}
}
/*
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg))
{
$classname=$reg[1];
$classname = str_replace('Api_','',ucwords($reg[1])).'Api';
//$classname = str_replace('Api_','',ucwords($reg[1]));
$classname = ucfirst($classname);
require_once $dir_part.$file_searched;
if (class_exists($classname)) if (class_exists($classname))
{ {
dol_syslog("Found API classname=".$classname); dol_syslog("Found API classname=".$classname);
$api->r->addAPIClass($classname,''); $api->r->addAPIClass($classname,'');
/* /*
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php';
$tmpclass = new ReflectionClass($classname); $tmpclass = new ReflectionClass($classname);
@@ -125,8 +151,9 @@ foreach ($modulesdir as $dir)
}*/ }*/
//$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched);
} /* }
}
}*/
} }
} }
} }
@@ -135,8 +162,8 @@ foreach ($modulesdir as $dir)
} }
} }
//var_dump($listofapis);
$listofapis=Routes::toArray(); $listofapis=Routes::toArray(); // TODO api for "status" is lost here
//var_dump($listofapis); //var_dump($listofapis);
@@ -166,6 +193,7 @@ print $langs->trans("ListOfAvailableAPIs").':<br>';
foreach($listofapis['v1'] as $key => $val) foreach($listofapis['v1'] as $key => $val)
{ {
if ($key == 'login') continue; if ($key == 'login') continue;
if ($key == 'index') continue;
if ($key) if ($key)
{ {

View File

@@ -95,9 +95,23 @@ print '</tr>';
print '</table>'; print '</table>';
print '<br><br>'; print '<br><br>';
// Define $urlwithroot
$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
// Show message
$message='';
$url='<a href="'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword" target="_blank">'.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]</a>';
$message.=$langs->trans("UrlToGetKeyToUseAPIs").':<br>';
$message.=img_picto('','object_globe.png').' '.$url;
print $message;
print '<br>';
print '<br>';
// Explorer // Explorer
print '<u>'.$langs->trans("ApiExporerIs").':</u><br>'; print '<u>'.$langs->trans("ApiExporerIs").':</u><br>';
$url=DOL_MAIN_URL_ROOT.'/api/admin/explorer.php'; $url=DOL_MAIN_URL_ROOT.'/api/index.php/explorer';
print img_picto('','object_globe.png').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n"; print img_picto('','object_globe.png').' <a href="'.$url.'" target="_blank">'.$url."</a><br>\n";

View File

@@ -88,6 +88,17 @@ class DolibarrApi
// Remove $db object property for object // Remove $db object property for object
unset($object->db); unset($object->db);
// Remove the $oldcopy property because it is not supported by the JSON
// encoder. The following error is generated when trying to serialize
// it: "Error encoding/decoding JSON: Type is not supported"
// Note: Event if this property was correctly handled by the JSON
// encoder, it should be ignored because keeping it would let the API
// have a very strange behavior: calling PUT and then GET on the same
// resource would give different results:
// PUT /objects/{id} -> returns object with oldcopy = previous version of the object
// GET /objects/{id} -> returns object with oldcopy empty
unset($object->oldcopy);
// If object has lines, remove $db property // If object has lines, remove $db property
if(isset($object->lines) && count($object->lines) > 0) { if(isset($object->lines) && count($object->lines) > 0) {
$nboflines = count($object->lines); $nboflines = count($object->lines);

View File

@@ -18,14 +18,11 @@
use Luracast\Restler\RestException; use Luracast\Restler\RestException;
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
/** /**
* API generic (login, status, ...) * API that allows to log in with an user account.
*
*/ */
class GenericApi extends DolibarrApi class Login
{ {
function __construct() { function __construct() {
@@ -46,7 +43,7 @@ class GenericApi extends DolibarrApi
* *
* @throws RestException * @throws RestException
*/ */
public function login($login, $password, $entity=0, $reset=0) { public function index($login, $password, $entity=0, $reset=0) {
global $conf, $dolibarr_main_authentication, $dolibarr_auto_user; global $conf, $dolibarr_main_authentication, $dolibarr_auto_user;
@@ -103,20 +100,4 @@ class GenericApi extends DolibarrApi
) )
); );
} }
/**
* Get status (Dolibarr version)
*
* @access protected
* @class DolibarrApiAccess {@requires admin}
*/
function status() {
require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
return array(
'success' => array(
'code' => 200,
'dolibarr_version' => DOL_VERSION
)
);
}
} }

View File

@@ -0,0 +1,40 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require_once DOL_DOCUMENT_ROOT . '/core/lib/functions.lib.php';
/**
* API that gives the status of the Dolibarr instance.
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Status
{
/**
* Get status (Dolibarr version)
*/
function index() {
return array(
'success' => array(
'code' => 200,
'dolibarr_version' => DOL_VERSION
)
);
}
}

View File

@@ -58,7 +58,10 @@ if (empty($conf->global->MAIN_MODULE_API))
$api = new DolibarrApi($db); $api = new DolibarrApi($db);
$api->r->addAPIClass('Luracast\\Restler\\Resources'); //this creates resources.json at API Root // Enable the Restler API Explorer.
// See https://github.com/Luracast/Restler-API-Explorer for more info.
$api->r->addAPIClass('Luracast\\Restler\\Explorer');
$api->r->setSupportedFormats('JsonFormat', 'XmlFormat'); $api->r->setSupportedFormats('JsonFormat', 'XmlFormat');
$api->r->addAuthenticationClass('DolibarrApiAccess',''); $api->r->addAuthenticationClass('DolibarrApiAccess','');
@@ -77,25 +80,19 @@ foreach ($modulesdir as $dir)
{ {
while (($file = readdir($handle))!==false) while (($file = readdir($handle))!==false)
{ {
if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i",$file,$reg)) if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i",$file,$reg))
{ {
$modulename=$reg[1]; $module = $part = strtolower($reg[1]);
// Defined if module is enabled
$enabled=true;
$module=$part=$obj=strtolower(preg_replace('/^mod/i','',$modulename));
//if ($part == 'propale') $part='propal';
if ($module == 'societe') {
$obj = 'thirdparty';
}
if ($module == 'categorie') { if ($module == 'categorie') {
$part = 'categories'; $part = 'categories';
$obj = 'category';
} }
if ($module == 'facture') { if ($module == 'facture') {
$part = 'compta/facture'; $part = 'compta/facture';
$obj = 'facture';
} }
// Defined if module is enabled
$enabled=true;
if (empty($conf->$module->enabled)) $enabled=false; if (empty($conf->$module->enabled)) $enabled=false;
if ($enabled) if ($enabled)
@@ -115,17 +112,25 @@ foreach ($modulesdir as $dir)
{ {
while (($file_searched = readdir($handle_part))!==false) while (($file_searched = readdir($handle_part))!==false)
{ {
if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) // Support of the deprecated API.
if (is_readable($dir_part.$file_searched) && preg_match("/^api_deprecated_(.*)\.class\.php$/i",$file_searched,$reg))
{ {
$classname=$reg[1]; $classname = ucwords($reg[1]).'Api';
$classname = str_replace('Api_','',ucwords($reg[1])).'Api'; require_once $dir_part.$file_searched;
$classname = ucfirst($classname); if (class_exists($classname))
{
dol_syslog("Found deprecated API classname=".$classname);
$api->r->addAPIClass($classname, '');
}
}
elseif (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i",$file_searched,$reg))
{
$classname = ucwords($reg[1]);
require_once $dir_part.$file_searched; require_once $dir_part.$file_searched;
if (class_exists($classname)) if (class_exists($classname))
{ {
dol_syslog("Found API classname=".$classname); dol_syslog("Found API classname=".$classname);
$api->r->addAPIClass($classname,''); $listofapis[] = $classname;
$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched);
} }
} }
} }
@@ -136,6 +141,14 @@ foreach ($modulesdir as $dir)
} }
} }
// Sort the classes before adding them to Restler. The Restler API Explorer
// shows the classes in the order they are added and it's a mess if they are
// not sorted.
sort($listofapis);
foreach ($listofapis as $classname)
{
$api->r->addAPIClass($classname);
}
// TODO If not found, redirect to explorer // TODO If not found, redirect to explorer

View File

@@ -0,0 +1,355 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
/**
* API class for categories
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Categories extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'label',
'type'
);
static $TYPES = array(
0 => 'product',
1 => 'supplier',
2 => 'customer',
3 => 'member',
4 => 'contact',
5 => 'account',
);
/**
* @var Categorie $category {@type Categorie}
*/
public $category;
/**
* Constructor
*/
function __construct()
{
global $db, $conf;
$this->db = $db;
$this->category = new Categorie($this->db);
}
/**
* Get properties of a category object
*
* Return an array with category informations
*
* @param int $id ID of category
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id)
{
if(! DolibarrApiAccess::$user->rights->categorie->lire) {
throw new RestException(401);
}
$result = $this->category->fetch($id);
if( ! $result ) {
throw new RestException(404, 'category not found');
}
if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->category);
}
/**
* List categories
*
* Get a list of categories
*
* @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @return array Array of category objects
*
* @throws RestException
*/
function index($type = '', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
global $db, $conf;
$obj_ret = array();
if(! DolibarrApiAccess::$user->rights->categorie->lire) {
throw new RestException(401);
}
$sql = "SELECT s.rowid";
$sql.= " FROM ".MAIN_DB_PREFIX."categorie as s";
$sql.= ' WHERE s.entity IN ('.getEntity('categorie', 1).')';
if (!empty($type))
{
$sql.= ' AND s.type='.array_search($type,Categories::$TYPES);
}
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$i=0;
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$category_static = new Categorie($db);
if($category_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($category_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve category list : '.$category_static->error);
}
if( ! count($obj_ret)) {
throw new RestException(404, 'No category found');
}
return $obj_ret;
}
/**
* List categories of an entity
*
* Note: This method is not directly exposed in the API, it is used
* in the GET /xxx/{id}/categories requests.
*
* @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact')
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param int $item Id of the item to get categories for
* @return array Array of category objects
*
* @access private
*/
function getListForItem($type, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $item = 0) {
global $db, $conf;
$obj_ret = array();
if(! DolibarrApiAccess::$user->rights->categorie->lire) {
throw new RestException(401);
}
//if ($type == "") {
//$type="product";
//}
$sub_type = $type;
$subcol_name = "fk_".$type;
if ($type=="customer" || $type=="supplier") {
$sub_type="societe";
$subcol_name="fk_soc";
}
if ($type=="contact") {
$subcol_name="fk_socpeople";
}
$sql = "SELECT s.rowid";
$sql.= " FROM ".MAIN_DB_PREFIX."categorie as s";
$sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub ";
$sql.= ' WHERE s.entity IN ('.getEntity('categorie', 1).')';
$sql.= ' AND s.type='.array_search($type,Categories::$TYPES);
$sql.= ' AND s.rowid = sub.fk_categorie';
$sql.= ' AND sub.'.$subcol_name.' = '.$item;
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$i=0;
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$category_static = new Categorie($db);
if($category_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($category_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve category list : '.$category_static->error);
}
if( ! count($obj_ret)) {
throw new RestException(404, 'No category found');
}
return $obj_ret;
}
/**
* Create category object
*
* @param array $request_data Request data
* @return int ID of category
*/
function post($request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->categorie->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach($request_data as $field => $value) {
$this->category->$field = $value;
}
if($this->category->create(DolibarrApiAccess::$user) < 0) {
throw new RestException(503, 'Error when create category : '.$this->category->error);
}
return $this->category->id;
}
/**
* Update category
*
* @param int $id Id of category to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->categorie->creer) {
throw new RestException(401);
}
$result = $this->category->fetch($id);
if( ! $result ) {
throw new RestException(404, 'category not found');
}
if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
$this->category->$field = $value;
}
if($this->category->update(DolibarrApiAccess::$user))
return $this->get ($id);
return false;
}
/**
* Delete category
*
* @param int $id Category ID
* @return array
*/
function delete($id)
{
if(! DolibarrApiAccess::$user->rights->categorie->supprimer) {
throw new RestException(401);
}
$result = $this->category->fetch($id);
if( ! $result ) {
throw new RestException(404, 'category not found');
}
if( ! DolibarrApi::_checkAccessToResource('category',$this->category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if (! $this->category->delete(DolibarrApiAccess::$user)) {
throw new RestException(401,'error when delete category');
}
return array(
'success' => array(
'code' => 200,
'message' => 'Category deleted'
)
);
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
*
* @throws RestException
*/
function _validate($data)
{
$category = array();
foreach (Categories::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$category[$field] = $data[$field];
}
return $category;
}
}

View File

@@ -27,7 +27,7 @@
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* *
* * @deprecated Use Categories instead (defined in api_categories.class.php)
*/ */
class CategoryApi extends DolibarrApi class CategoryApi extends DolibarrApi
{ {
@@ -54,7 +54,7 @@ class CategoryApi extends DolibarrApi
public $category; public $category;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url GET category/ * @url GET category/
* *
@@ -68,7 +68,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get properties of a category object * Get properties of a category object <b>Warning: Deprecated</b>
* *
* Return an array with category informations * Return an array with category informations
* *
@@ -97,7 +97,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* List categories * List categories <b>Warning: Deprecated</b>
* *
* Get a list of categories * Get a list of categories
* *
@@ -166,7 +166,7 @@ class CategoryApi extends DolibarrApi
return $obj_ret; return $obj_ret;
} }
/** /**
* List categories of an entity * List categories of an entity <b>Warning: Deprecated</b>
* *
* Get a list of categories * Get a list of categories
* *
@@ -248,7 +248,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get member categories list * Get member categories list <b>Warning: Deprecated</b>
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
@@ -263,7 +263,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get customer categories list * Get customer categories list <b>Warning: Deprecated</b>
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
@@ -278,7 +278,7 @@ class CategoryApi extends DolibarrApi
return $this->getList('customer', $sortfield, $sortorder, $limit, $page); return $this->getList('customer', $sortfield, $sortorder, $limit, $page);
} }
/** /**
* Get categories for a customer * Get categories for a customer <b>Warning: Deprecated</b>
* *
* @param int $cusid Customer id filter * @param int $cusid Customer id filter
* @param string $sortfield Sort field * @param string $sortfield Sort field
@@ -295,7 +295,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Add category to customer * Add category to customer <b>Warning: Deprecated</b>
* *
* @param int $cusid Id of customer * @param int $cusid Id of customer
* @param int $catid Id of category * @param int $catid Id of category
@@ -329,7 +329,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get supplier categories list * Get supplier categories list <b>Warning: Deprecated</b>
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
@@ -345,7 +345,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get product categories list * Get product categories list <b>Warning: Deprecated</b>
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
@@ -361,7 +361,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Get contact categories list * Get contact categories list <b>Warning: Deprecated</b>
* *
* @param string $sortfield Sort field * @param string $sortfield Sort field
* @param string $sortorder Sort order * @param string $sortorder Sort order
@@ -376,7 +376,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Create category object * Create category object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request data * @param array $request_data Request data
* @return int ID of category * @return int ID of category
@@ -401,7 +401,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Update category * Update category <b>Warning: Deprecated</b>
* *
* @param int $id Id of category to update * @param int $id Id of category to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -435,7 +435,7 @@ class CategoryApi extends DolibarrApi
} }
/** /**
* Delete category * Delete category <b>Warning: Deprecated</b>
* *
* @param int $id Category ID * @param int $id Category ID
* @return array * @return array

View File

@@ -29,7 +29,7 @@
* @category Api * @category Api
* @package Api * @package Api
* *
* * @deprecated Use Orders instead (defined in api_orders.class.php)
*/ */
class CommandeApi extends DolibarrApi class CommandeApi extends DolibarrApi
{ {
@@ -47,7 +47,7 @@ class CommandeApi extends DolibarrApi
public $commande; public $commande;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url GET order/ * @url GET order/
* *
@@ -60,7 +60,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* Get properties of a commande object * Get properties of a commande object <b>Warning: Deprecated</b>
* *
* Return an array with commande informations * Return an array with commande informations
* *
@@ -93,7 +93,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* List orders * List orders <b>Warning: Deprecated</b>
* *
* Get a list of orders * Get a list of orders
* *
@@ -181,7 +181,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* List orders for specific thirdparty * List orders for specific thirdparty <b>Warning: Deprecated</b>
* *
* Get a list of orders * Get a list of orders
* *
@@ -197,7 +197,7 @@ class CommandeApi extends DolibarrApi
/** /**
* Create order object * Create order object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* *
@@ -230,7 +230,7 @@ class CommandeApi extends DolibarrApi
return $this->commande->id; return $this->commande->id;
} }
/** /**
* Get lines of an order * Get lines of an order <b>Warning: Deprecated</b>
* *
* *
* @param int $id Id of order * @param int $id Id of order
@@ -260,7 +260,7 @@ class CommandeApi extends DolibarrApi
return $result; return $result;
} }
/** /**
* Add a line to given order * Add a line to given order <b>Warning: Deprecated</b>
* *
* *
* @param int $id Id of commande to update * @param int $id Id of commande to update
@@ -319,7 +319,7 @@ class CommandeApi extends DolibarrApi
return false; return false;
} }
/** /**
* Update a line to given order * Update a line to given order <b>Warning: Deprecated</b>
* *
* *
* @param int $id Id of commande to update * @param int $id Id of commande to update
@@ -376,7 +376,7 @@ class CommandeApi extends DolibarrApi
return false; return false;
} }
/** /**
* Delete a line to given order * Delete a line to given order <b>Warning: Deprecated</b>
* *
* *
* @param int $id Id of commande to update * @param int $id Id of commande to update
@@ -408,7 +408,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* Update order general fields (won't touch lines of order) * Update order general fields (won't touch lines of order) <b>Warning: Deprecated</b>
* *
* @param int $id Id of commande to update * @param int $id Id of commande to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -441,7 +441,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* Delete order * Delete order <b>Warning: Deprecated</b>
* *
* @param int $id Order ID * @param int $id Order ID
* *
@@ -477,7 +477,7 @@ class CommandeApi extends DolibarrApi
} }
/** /**
* Validate an order * Validate an order <b>Warning: Deprecated</b>
* *
* @param int $id Order ID * @param int $id Order ID
* @param int $idwarehouse Warehouse ID * @param int $idwarehouse Warehouse ID

View File

@@ -0,0 +1,498 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
/**
* API class for orders
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Orders extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'socid'
);
/**
* @var Commande $commande {@type Commande}
*/
public $commande;
/**
* Constructor
*/
function __construct()
{
global $db, $conf;
$this->db = $db;
$this->commande = new Commande($this->db);
}
/**
* Get properties of a commande object
*
* Return an array with commande informations
*
* @param int $id ID of order
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id)
{
if(! DolibarrApiAccess::$user->rights->commande->lire) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Order not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->commande->fetchObjectLinked();
return $this->_cleanObjectDatas($this->commande);
}
/**
* List orders
*
* Get a list of orders
*
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @param string $societe Societe filter field
*
* @return array Array of order objects
*/
function index($sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0, $societe = 0) {
global $db, $conf;
$obj_ret = array();
// case of external user, $societe param is ignored and replaced by user's socid
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : $societe;
// If the internal user must only see his customers, force searching by him
if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT s.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql.= " FROM ".MAIN_DB_PREFIX."commande as s";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql.= ' WHERE s.entity IN ('.getEntity('commande', 1).')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc";
if ($socid) $sql.= " AND s.fk_soc = ".$socid;
if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$commande_static = new Commande($db);
if($commande_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($commande_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve commande list');
}
if( ! count($obj_ret)) {
throw new RestException(404, 'No commande found');
}
return $obj_ret;
}
/**
* Create order object
*
* @param array $request_data Request data
* @return int ID of commande
*/
function post($request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401, "Insuffisant rights");
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach($request_data as $field => $value) {
$this->commande->$field = $value;
}
if (isset($request_data["lines"])) {
$lines = array();
foreach ($request_data["lines"] as $line) {
array_push($lines, (object) $line);
}
$this->commande->lines = $lines;
}
if(! $this->commande->create(DolibarrApiAccess::$user) ) {
throw new RestException(500, "Error while creating order");
}
return $this->commande->id;
}
/**
* Get lines of an order
*
* @param int $id Id of order
*
* @url GET {id}/lines
*
* @return int
*/
function getLines($id) {
if(! DolibarrApiAccess::$user->rights->commande->lire) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Commande not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->commande->getLinesArray();
$result = array();
foreach ($this->commande->lines as $line) {
array_push($result,$this->_cleanObjectDatas($line));
}
return $result;
}
/**
* Add a line to given order
*
* @param int $id Id of commande to update
* @param array $request_data Orderline data
*
* @url POST {id}/lines
*
* @return int
*/
function postLine($id, $request_data = NULL) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Commande not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$request_data = (object) $request_data;
$updateRes = $this->commande->addline(
$request_data->desc,
$request_data->subprice,
$request_data->qty,
$request_data->tva_tx,
$request_data->localtax1_tx,
$request_data->localtax2_tx,
$request_data->fk_product,
$request_data->remise_percent,
$request_data->info_bits,
$request_data->fk_remise_except,
'HT',
0,
$request_data->date_start,
$request_data->date_end,
$request_data->product_type,
$request_data->rang,
$request_data->special_code,
$fk_parent_line,
$request_data->fk_fournprice,
$request_data->pa_ht,
$request_data->label,
$request_data->array_options,
$request_data->fk_unit,
$this->element,
$request_data->id
);
if ($updateRes > 0) {
return $this->get($id)->line->rowid;
}
return false;
}
/**
* Update a line to given order
*
* @param int $id Id of commande to update
* @param int $lineid Id of line to update
* @param array $request_data Orderline data
*
* @url PUT {id}/lines/{lineid}
*
* @return object
*/
function putLine($id, $lineid, $request_data = NULL) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Commande not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$request_data = (object) $request_data;
$updateRes = $this->commande->updateline(
$lineid,
$request_data->desc,
$request_data->subprice,
$request_data->qty,
$request_data->remise_percent,
$request_data->tva_tx,
$request_data->localtax1_tx,
$request_data->localtax2_tx,
'HT',
$request_data->info_bits,
$request_data->date_start,
$request_data->date_end,
$request_data->product_type,
$request_data->fk_parent_line,
0,
$request_data->fk_fournprice,
$request_data->pa_ht,
$request_data->label,
$request_data->special_code,
$request_data->array_options,
$request_data->fk_unit
);
if ($updateRes > 0) {
$result = $this->get($id);
unset($result->line);
return $this->_cleanObjectDatas($result);
}
return false;
}
/**
* Delete a line to given order
*
*
* @param int $id Id of commande to update
* @param int $lineid Id of line to delete
*
* @url DELETE {id}/lines/{lineid}
*
* @return int
*/
function delLine($id, $lineid) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Commande not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$request_data = (object) $request_data;
$updateRes = $this->commande->deleteline($lineid);
if ($updateRes == 1) {
return $this->get($id);
}
return false;
}
/**
* Update order general fields (won't touch lines of order)
*
* @param int $id Id of commande to update
* @param array $request_data Datas
*
* @return int
*/
function put($id, $request_data = NULL) {
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Commande not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
$this->commande->$field = $value;
}
if($this->commande->update($id, DolibarrApiAccess::$user,1,'','','update'))
return $this->get($id);
return false;
}
/**
* Delete order
*
* @param int $id Order ID
*
* @return array
*/
function delete($id)
{
if(! DolibarrApiAccess::$user->rights->commande->supprimer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Order not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if( ! $this->commande->delete(DolibarrApiAccess::$user)) {
throw new RestException(500, 'Error when delete order : '.$this->commande->error);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Order deleted'
)
);
}
/**
* Validate an order
*
* @param int $id Order ID
* @param int $idwarehouse Warehouse ID
*
* @url POST {id}/validate
*
* @return array
* FIXME An error 403 is returned if the request has an empty body.
* Error message: "Forbidden: Content type `text/plain` is not supported."
* Workaround: send this in the body
* {
* "idwarehouse": 0
* }
*/
function validate($id, $idwarehouse=0)
{
if(! DolibarrApiAccess::$user->rights->commande->creer) {
throw new RestException(401);
}
$result = $this->commande->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Order not found');
}
if( ! DolibarrApi::_checkAccessToResource('commande',$this->commande->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if( ! $this->commande->valid(DolibarrApiAccess::$user, $idwarehouse)) {
throw new RestException(500, 'Error when validate order');
}
return array(
'success' => array(
'code' => 200,
'message' => 'Order validated'
)
);
}
/**
* Validate fields before create or update object
*
* @param array $data Array with data to verify
* @return array
* @throws RestException
*/
function _validate($data)
{
$commande = array();
foreach (Orders::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$commande[$field] = $data[$field];
}
return $commande;
}
}

View File

@@ -25,7 +25,7 @@
* @smart-auto-routing false * @smart-auto-routing false
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* * @deprecated Use Invoices instead (defined in api_invoices.class.php)
*/ */
class InvoiceApi extends DolibarrApi class InvoiceApi extends DolibarrApi
{ {
@@ -43,7 +43,7 @@ class InvoiceApi extends DolibarrApi
public $invoice; public $invoice;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url GET invoice/ * @url GET invoice/
* *
@@ -56,7 +56,7 @@ class InvoiceApi extends DolibarrApi
} }
/** /**
* Get properties of a invoice object * Get properties of a invoice object <b>Warning: Deprecated</b>
* *
* Return an array with invoice informations * Return an array with invoice informations
* *
@@ -85,7 +85,7 @@ class InvoiceApi extends DolibarrApi
} }
/** /**
* List invoices * List invoices <b>Warning: Deprecated</b>
* *
* Get a list of invoices * Get a list of invoices
* *
@@ -179,7 +179,7 @@ class InvoiceApi extends DolibarrApi
} }
/** /**
* Create invoice object * Create invoice object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* @return int ID of invoice * @return int ID of invoice
@@ -207,7 +207,7 @@ class InvoiceApi extends DolibarrApi
} }
/** /**
* Update invoice * Update invoice <b>Warning: Deprecated</b>
* *
* @param int $id Id of invoice to update * @param int $id Id of invoice to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -241,7 +241,7 @@ class InvoiceApi extends DolibarrApi
} }
/** /**
* Delete invoice * Delete invoice <b>Warning: Deprecated</b>
* *
* @param int $id Invoice ID * @param int $id Invoice ID
* @return type * @return type

View File

@@ -0,0 +1,281 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
/**
* API class for invoices
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Invoices extends DolibarrApi
{
/**
*
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'socid'
);
/**
* @var Facture $invoice {@type Facture}
*/
public $invoice;
/**
* Constructor
*/
function __construct()
{
global $db, $conf;
$this->db = $db;
$this->invoice = new Facture($this->db);
}
/**
* Get properties of a invoice object
*
* Return an array with invoice informations
*
* @param int $id ID of invoice
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id)
{
if(! DolibarrApiAccess::$user->rights->facture->lire) {
throw new RestException(401);
}
$result = $this->invoice->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Facture not found');
}
if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->invoice);
}
/**
* List invoices
*
* Get a list of invoices
*
* FIXME this parameter is overwritten in the code and thus ignored
* @param int $socid Filter list with thirdparty ID
* @param string $status Filter by invoice status : draft | unpaid | paid | cancelled
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @return array Array of invoice objects
*
* @throws RestException
*/
function index($socid=0, $status='', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
global $db, $conf;
$obj_ret = array();
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
// If the internal user must only see his customers, force searching by him
if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT s.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql.= " FROM ".MAIN_DB_PREFIX."facture as s";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql.= ' WHERE s.entity IN ('.getEntity('facture', 1).')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc";
if ($socid) $sql.= " AND s.fk_soc = ".$socid;
if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Filter by status
if ($status == 'draft') $sql.= " AND s.fk_statut IN (0)";
if ($status == 'unpaid') $sql.= " AND s.fk_statut IN (1)";
if ($status == 'paid') $sql.= " AND s.fk_statut IN (2)";
if ($status == 'cancelled') $sql.= " AND s.fk_statut IN (3)";
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$invoice_static = new Facture($db);
if($invoice_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($invoice_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve invoice list');
}
if( ! count($obj_ret)) {
throw new RestException(404, 'No invoice found');
}
return $obj_ret;
}
/**
* Create invoice object
*
* @param array $request_data Request datas
* @return int ID of invoice
*/
function post($request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach($request_data as $field => $value) {
$this->invoice->$field = $value;
}
if(! array_keys($request_data,'date')) {
$this->invoice->date = dol_now();
}
if( ! $this->invoice->create(DolibarrApiAccess::$user)) {
throw new RestException(500);
}
return $this->invoice->id;
}
/**
* Update invoice
*
* @param int $id Id of invoice to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->facture->creer) {
throw new RestException(401);
}
$result = $this->invoice->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Facture not found');
}
if( ! DolibarrApi::_checkAccessToResource('facture',$this->invoice->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
$this->invoice->$field = $value;
}
if($this->invoice->update($id, DolibarrApiAccess::$user))
return $this->get ($id);
return false;
}
/**
* Delete invoice
*
* @param int $id Invoice ID
* @return type
*/
function delete($id)
{
if(! DolibarrApiAccess::$user->rights->facture->supprimer) {
throw new RestException(401);
}
$result = $this->invoice->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Facture not found');
}
if( ! DolibarrApi::_checkAccessToResource('facture',$this->facture->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if( $this->invoice->delete($id) < 0)
{
throw new RestException(500);
}
return array(
'success' => array(
'code' => 200,
'message' => 'Facture deleted'
)
);
}
/**
* Validate fields before create or update object
*
* @param array $data Datas to validate
* @return array
*
* @throws RestException
*/
function _validate($data)
{
$invoice = array();
foreach (Invoices::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$invoice[$field] = $data[$field];
}
return $invoice;
}
}

View File

@@ -26,7 +26,7 @@
* @smart-auto-routing false * @smart-auto-routing false
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* * @deprecated Use Products instead (defined in api_products.class.php)
*/ */
class ProductApi extends DolibarrApi class ProductApi extends DolibarrApi
{ {
@@ -44,7 +44,7 @@ class ProductApi extends DolibarrApi
public $product; public $product;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url product/ * @url product/
* *
@@ -57,7 +57,7 @@ class ProductApi extends DolibarrApi
} }
/** /**
* Get properties of a product object * Get properties of a product object <b>Warning: Deprecated</b>
* *
* Return an array with product informations * Return an array with product informations
* *
@@ -90,7 +90,7 @@ class ProductApi extends DolibarrApi
} }
/** /**
* List products * List products <b>Warning: Deprecated</b>
* *
* Get a list of products * Get a list of products
* *
@@ -169,7 +169,7 @@ class ProductApi extends DolibarrApi
/** /**
* List products in a category * List products in a category <b>Warning: Deprecated</b>
* *
* Get a list of products * Get a list of products
* *
@@ -253,7 +253,7 @@ class ProductApi extends DolibarrApi
} }
/** /**
* Create product object * Create product object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request data * @param array $request_data Request data
* @return int ID of product * @return int ID of product
@@ -281,7 +281,7 @@ class ProductApi extends DolibarrApi
} }
/** /**
* Update product * Update product <b>Warning: Deprecated</b>
* *
* @param int $id Id of product to update * @param int $id Id of product to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -315,7 +315,7 @@ class ProductApi extends DolibarrApi
} }
/** /**
* Delete product * Delete product <b>Warning: Deprecated</b>
* *
* @param int $id Product ID * @param int $id Product ID
* @return array * @return array

View File

@@ -0,0 +1,292 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
/**
* API class for products
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Products extends DolibarrApi
{
/**
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'ref',
'label'
);
/**
* @var Product $product {@type Product}
*/
public $product;
/**
* Constructor
*/
function __construct()
{
global $db, $conf;
$this->db = $db;
$this->product = new Product($this->db);
}
/**
* Get properties of a product object
*
* Return an array with product informations
*
* @param int $id ID of product
* @return array|mixed data without useless information
*
* @throws RestException
* TODO implement getting a product by ref or by $ref_ext
*/
function get($id)
{
if(! DolibarrApiAccess::$user->rights->produit->lire) {
throw new RestException(401);
}
$result = $this->product->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Product not found');
}
if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$this->product->load_stock();
return $this->_cleanObjectDatas($this->product);
}
/**
* List products
*
* Get a list of products
*
* @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service)
* @param int $category Use this param to filter list by category
* @param mixed $to_sell Filter products to sell (1) or not to sell (0)
* @param mixed $to_buy Filter products to buy (1) or not to buy (0)
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return array Array of product objects
*/
function index($mode=0, $category=0, $to_sell='', $to_buy='', $sortfield = "p.ref", $sortorder = 'ASC', $limit = 0, $page = 0) {
global $db, $conf;
$obj_ret = array();
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
$sql = "SELECT rowid, ref, ref_ext";
$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
if ($category > 0)
{
$sql.= ", ".MAIN_DB_PREFIX."categorie_product as c";
}
$sql.= ' WHERE p.entity IN ('.getEntity('product', 1).')';
// Select products of given category
if ($category > 0)
{
$sql.= " AND c.fk_categorie = ".$db->escape($category);
$sql.= " AND c.fk_product = p.rowid ";
}
// Show products
if ($mode == 1) $sql.= " AND p.fk_product_type = 0";
// Show services
if ($mode == 2) $sql.= " AND p.fk_product_type = 1";
// Show product on sell
if ($to_sell !== '') $sql.= " AND p.tosell = ".$db->escape($to_sell);
// Show product on buy
if ($to_buy !== '') $sql.= " AND p.tobuy = ".$db->escape($to_buy);
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$product_static = new Product($db);
if($product_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($product_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve product list');
}
if( ! count($obj_ret)) {
throw new RestException(404, 'No product found');
}
return $obj_ret;
}
/**
* Create product object
*
* @param array $request_data Request data
* @return int ID of product
*/
function post($request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->produit->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach($request_data as $field => $value) {
$this->product->$field = $value;
}
$result = $this->product->create(DolibarrApiAccess::$user);
if($result < 0) {
throw new RestException(503,'Error when creating product : '.$this->product->error);
}
return $this->product->id;
}
/**
* Update product
*
* @param int $id Id of product to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->produit->creer) {
throw new RestException(401);
}
$result = $this->product->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Product not found');
}
if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
$this->product->$field = $value;
}
if($this->product->update($id, DolibarrApiAccess::$user,1,'update'))
return $this->get ($id);
return false;
}
/**
* Delete product
*
* @param int $id Product ID
* @return array
*/
function delete($id)
{
if(! DolibarrApiAccess::$user->rights->produit->supprimer) {
throw new RestException(401);
}
$result = $this->product->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Product not found');
}
if( ! DolibarrApi::_checkAccessToResource('product',$this->product->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
// The Product::delete() method uses the global variable $user.
global $user;
$user = DolibarrApiAccess::$user;
return $this->product->delete($id);
}
/**
* Get categories for a product
*
* @param int $id ID of product
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return mixed
*
* @url GET {id}/categories
*/
function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
$categories = new Categories();
return $categories->getListForItem('product', $sortfield, $sortorder, $limit, $page, $id);
}
/**
* Validate fields before create or update object
*
* @param array $data Datas to validate
* @return array
* @throws RestException
*/
function _validate($data)
{
$product = array();
foreach (Products::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$product[$field] = $data[$field];
}
return $product;
}
}

View File

@@ -0,0 +1,338 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
//require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
/**
* API class for contacts
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Contacts extends DolibarrApi
{
/**
*
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'lastname'
);
/**
* @var Contact $contact {@type Contact}
*/
public $contact;
/**
* Constructor
*/
function __construct() {
global $db, $conf;
$this->db = $db;
$this->contact = new Contact($this->db);
}
/**
* Get properties of a contact object
*
* Return an array with contact informations
*
* @param int $id ID of contact
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id) {
if (!DolibarrApiAccess::$user->rights->societe->contact->lire)
{
throw new RestException(401);
}
$result = $this->contact->fetch($id);
if (!$result)
{
throw new RestException(404, 'Contact not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->contact);
}
/**
* List contacts
*
* Get a list of contacts
*
* @param int $socid ID of thirdparty to filter list
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @return array Array of contact objects
*
* @throws RestException
*/
function index($socid = 0, $sortfield = "c.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
global $db, $conf;
$obj_ret = array();
if (!$socid)
{
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
}
// If the internal user must only see his customers, force searching by him
if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid)
$search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT c.rowid";
$sql.= " FROM " . MAIN_DB_PREFIX . "socpeople as c";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) {
// We need this table joined to the select in order to filter by sale
$sql.= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc";
}
$sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON c.fk_soc = s.rowid";
$sql.= ' WHERE c.entity IN (' . getEntity('contact', 1) . ')';
if ($socid)
$sql.= " AND c.fk_soc = " . $socid;
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0)
$sql.= " AND c.fk_soc = sc.fk_soc";
if ($search_sale > 0)
$sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = " . $search_sale;
}
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit)
{
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$contact_static = new Contact($db);
if ($contact_static->fetch($obj->rowid))
{
$obj_ret[] = parent::_cleanObjectDatas($contact_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retreive contacts : ' . $sql);
}
if (!count($obj_ret))
{
throw new RestException(404, 'Contacts not found');
}
return $obj_ret;
}
/**
* Create contact object
*
* @param array $request_data Request datas
* @return int ID of contact
*/
function post($request_data = NULL) {
if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
{
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach ($request_data as $field => $value)
{
$this->contact->$field = $value;
}
return $this->contact->create(DolibarrApiAccess::$user);
}
/**
* Update contact
*
* @param int $id Id of contact to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL) {
if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
{
throw new RestException(401);
}
$result = $this->contact->fetch($id);
if (!$result)
{
throw new RestException(404, 'Contact not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value)
{
$this->contact->$field = $value;
}
if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
return $this->get($id);
return false;
}
/**
* Delete contact
*
* @param int $id Contact ID
* @return integer
*/
function delete($id) {
if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer)
{
throw new RestException(401);
}
$result = $this->contact->fetch($id);
if (!$result)
{
throw new RestException(404, 'Contact not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
return $this->contact->delete($id);
}
/**
* Create useraccount object from contact
*
* @param int $id Id of contact
* @param array $request_data Request datas
* @return int ID of user
*
* @url POST {id}/createUser
*/
function createUser($id, $request_data = NULL) {
//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
//throw new RestException(401);
//}
if (!isset($request_data["login"]))
throw new RestException(400, "login field missing");
if (!isset($request_data["password"]))
throw new RestException(400, "password field missing");
if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
throw new RestException(401);
}
$contact = new Contact($this->db);
$contact->fetch($id);
if ($contact->id <= 0) {
throw new RestException(404, 'Contact not found');
}
if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
// Check mandatory fields
$login = $request_data["login"];
$password = $request_data["password"];
$useraccount = new User($this->db);
$result = $useraccount->create_from_contact($contact,$login,$password);
if ($result <= 0) {
throw new RestException(500, "User not created");
}
// password parameter not used in create_from_contact
$useraccount->setPassword($useraccount,$password);
return $result;
}
/**
* Get categories for a contact
*
* @param int $id ID of contact
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return mixed
*
* @url GET {id}/categories
*/
function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
$categories = new Categories();
return $categories->getListForItem('contact', $sortfield, $sortorder, $limit, $page, $id);
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
* @throws RestException
*/
function _validate($data) {
$contact = array();
foreach (Contacts::$FIELDS as $field)
{
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$contact[$field] = $data[$field];
}
return $contact;
}
}

View File

@@ -25,7 +25,7 @@ use Luracast\Restler\RestException;
* @smart-auto-routing false * @smart-auto-routing false
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* * @deprecated Use Contacts instead (defined in api_contacts.class.php)
*/ */
class ContactApi extends DolibarrApi class ContactApi extends DolibarrApi
{ {
@@ -43,7 +43,7 @@ class ContactApi extends DolibarrApi
public $contact; public $contact;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url contact/ * @url contact/
* *
@@ -55,7 +55,7 @@ class ContactApi extends DolibarrApi
} }
/** /**
* Get properties of a contact object * Get properties of a contact object <b>Warning: Deprecated</b>
* *
* Return an array with contact informations * Return an array with contact informations
* *
@@ -86,7 +86,7 @@ class ContactApi extends DolibarrApi
} }
/** /**
* List contacts * List contacts <b>Warning: Deprecated</b>
* *
* Get a list of contacts * Get a list of contacts
* *
@@ -187,7 +187,7 @@ class ContactApi extends DolibarrApi
} }
/** /**
* Create contact object * Create contact object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* @return int ID of contact * @return int ID of contact
@@ -210,7 +210,7 @@ class ContactApi extends DolibarrApi
} }
/** /**
* Update contact * Update contact <b>Warning: Deprecated</b>
* *
* @param int $id Id of contact to update * @param int $id Id of contact to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -247,7 +247,7 @@ class ContactApi extends DolibarrApi
} }
/** /**
* Delete contact * Delete contact <b>Warning: Deprecated</b>
* *
* @param int $id Contact ID * @param int $id Contact ID
* @return integer * @return integer

View File

@@ -24,7 +24,7 @@
* @smart-auto-routing false * @smart-auto-routing false
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* * @deprecated Use Thirdparties instead (defined in api_thirdparties.class.php)
*/ */
class ThirdpartyApi extends DolibarrApi class ThirdpartyApi extends DolibarrApi
{ {
@@ -46,7 +46,7 @@ class ThirdpartyApi extends DolibarrApi
public $customer; public $customer;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url thirdparty/ * @url thirdparty/
* *
@@ -64,7 +64,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Get properties of a customer object * Get properties of a customer object <b>Warning: Deprecated</b>
* *
* Return an array with customer informations * Return an array with customer informations
* *
@@ -93,7 +93,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Search customer by email * Search customer by email <b>Warning: Deprecated</b>
* *
* @param string $email email id * @param string $email email id
* *
@@ -111,7 +111,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Get properties of a thirdparty object * Get properties of a thirdparty object <b>Warning: Deprecated</b>
* *
* Return an array with thirdparty informations * Return an array with thirdparty informations
* *
@@ -140,7 +140,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* List thirdparties * List thirdparties <b>Warning: Deprecated</b>
* *
* Get a list of thirdparties * Get a list of thirdparties
* *
@@ -232,7 +232,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Show customers * Show customers <b>Warning: Deprecated</b>
* *
* @return array List of customers * @return array List of customers
* *
@@ -244,7 +244,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Show prospects * Show prospects <b>Warning: Deprecated</b>
* *
* @return array List of prospects * @return array List of prospects
* *
@@ -255,7 +255,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Show other * Show other <b>Warning: Deprecated</b>
* *
* @return array List of thirpdparties who are not customer neither prospect * @return array List of thirpdparties who are not customer neither prospect
* *
@@ -266,7 +266,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Create thirdparty object * Create thirdparty object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* @return int ID of thirdparty * @return int ID of thirdparty
@@ -289,7 +289,7 @@ class ThirdpartyApi extends DolibarrApi
/** /**
* Create customer object * Create customer object <b>Warning: Deprecated</b>
* *
* @param array $request_data Request datas * @param array $request_data Request datas
* @return int ID of thirdparty * @return int ID of thirdparty
@@ -303,7 +303,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Update thirdparty * Update thirdparty <b>Warning: Deprecated</b>
* *
* @param int $id Id of thirdparty to update * @param int $id Id of thirdparty to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -336,7 +336,7 @@ class ThirdpartyApi extends DolibarrApi
return false; return false;
} }
/** /**
* Update customer * Update customer <b>Warning: Deprecated</b>
* *
* @param int $id Id of thirdparty to update * @param int $id Id of thirdparty to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -367,7 +367,7 @@ class ThirdpartyApi extends DolibarrApi
} }
/** /**
* Delete thirdparty * Delete thirdparty <b>Warning: Deprecated</b>
* *
* @param int $id Thirparty ID * @param int $id Thirparty ID
* @return integer * @return integer

View File

@@ -0,0 +1,323 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
/**
* API class for thirdparties
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*
*/
class Thirdparties extends DolibarrApi
{
/**
*
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'name'
);
/**
* @var Societe $company {@type Societe}
*/
public $company;
/**
* Constructor
*/
function __construct()
{
global $db, $conf;
$this->db = $db;
$this->company = new Societe($this->db);
if (! empty($conf->global->SOCIETE_MAIL_REQUIRED)) {
static::$FIELDS[] = 'email';
}
}
/**
* Get properties of a thirdparty object
*
* Return an array with thirdparty informations
*
* @param int $id ID of thirdparty
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id)
{
if(! DolibarrApiAccess::$user->rights->societe->lire) {
throw new RestException(401);
}
$result = $this->company->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Thirdparty not found');
}
if( ! DolibarrApi::_checkAccessToResource('societe',$this->company->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->company);
}
/**
* List thirdparties
*
* Get a list of thirdparties
*
* @param int $mode Set to 1 to show only customers
* Set to 2 to show only prospects
* Set to 3 to show only those are not customer neither prospect
* @param string $email Search by email filter
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
* @return array Array of thirdparty objects
*/
function index($mode=0, $email=NULL, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
global $db, $conf;
$obj_ret = array();
$socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
// If the internal user must only see his customers, force searching by him
if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
$sql = "SELECT s.rowid";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
$sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st";
$sql.= " WHERE s.fk_stcomm = st.id";
if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
if ($mode == 3) $sql.= " AND s.client IN (0)";
$sql.= ' AND s.entity IN ('.getEntity('societe', 1).')';
if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc";
if ($email != NULL) $sql.= " AND s.email = \"".$email."\"";
if ($socid) $sql.= " AND s.rowid = ".$socid;
if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
// Insert sale filter
if ($search_sale > 0)
{
$sql .= " AND sc.fk_user = ".$search_sale;
}
$nbtotalofrecords = 0;
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
{
$result = $db->query($sql);
$nbtotalofrecords = $db->num_rows($result);
}
$sql.= $db->order($sortfield, $sortorder);
if ($limit) {
if ($page < 0)
{
$page = 0;
}
$offset = $limit * $page;
$sql.= $db->plimit($limit + 1, $offset);
}
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
while ($i < $num)
{
$obj = $db->fetch_object($result);
$soc_static = new Societe($db);
if($soc_static->fetch($obj->rowid)) {
$obj_ret[] = parent::_cleanObjectDatas($soc_static);
}
$i++;
}
}
else {
throw new RestException(503, 'Error when retrieve thirdparties : ' . $sql);
}
if( ! count($obj_ret)) {
throw new RestException(404, 'Thirdparties not found');
}
return $obj_ret;
}
/**
* Create thirdparty object
*
* @param array $request_data Request datas
* @return int ID of thirdparty
*/
function post($request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->societe->creer) {
throw new RestException(401);
}
// Check mandatory fields
$result = $this->_validate($request_data);
foreach($request_data as $field => $value) {
$this->company->$field = $value;
}
return $this->company->create(DolibarrApiAccess::$user);
}
/**
* Update thirdparty
*
* @param int $id Id of thirdparty to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL)
{
if(! DolibarrApiAccess::$user->rights->societe->creer) {
throw new RestException(401);
}
$result = $this->company->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Thirdparty not found');
}
if( ! DolibarrApi::_checkAccessToResource('societe',$this->company->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
foreach($request_data as $field => $value) {
$this->company->$field = $value;
}
if($this->company->update($id, DolibarrApiAccess::$user,1,'','','update'))
return $this->get ($id);
return false;
}
/**
* Delete thirdparty
*
* @param int $id Thirparty ID
* @return integer
*/
function delete($id)
{
if(! DolibarrApiAccess::$user->rights->societe->supprimer) {
throw new RestException(401);
}
$result = $this->company->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Thirdparty not found');
}
if( ! DolibarrApi::_checkAccessToResource('societe',$this->company->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
return $this->company->delete($id);
}
/**
* Get categories for a thirdparty
*
* @param int $id ID of thirdparty
* @param string $sortfield Sort field
* @param string $sortorder Sort order
* @param int $limit Limit for list
* @param int $page Page number
*
* @return mixed
*
* @url GET {id}/categories
*/
function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) {
$categories = new Categories();
return $categories->getListForItem('customer', $sortfield, $sortorder, $limit, $page, $id);
}
/**
* Add category to a thirdparty
*
* @param int $id Id of thirdparty
* @param array $request_data Request datas
*
* @return mixed
*
* @url POST {id}/addCategory
*/
function addCategory($id, $request_data = NULL) {
if (!isset($request_data["category_id"]))
throw new RestException(400, "category_id field missing");
$category_id = $request_data["category_id"];
if(! DolibarrApiAccess::$user->rights->societe->creer) {
throw new RestException(401);
}
$result = $this->company->fetch($id);
if( ! $result ) {
throw new RestException(404, 'Thirdparty not found');
}
$category = new Categorie($this->db);
$result = $category->fetch($category_id);
if( ! $result ) {
throw new RestException(404, 'category not found');
}
if( ! DolibarrApi::_checkAccessToResource('societe',$this->company->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
if( ! DolibarrApi::_checkAccessToResource('category',$category->id)) {
throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
}
$category->add_type($this->company,'customer');
return $this->company;
}
/**
* Validate fields before create or update object
*
* @param array $data Datas to validate
* @return array
*
* @throws RestException
*/
function _validate($data)
{
$thirdparty = array();
foreach (Thirdparties::$FIELDS as $field) {
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$thirdparty[$field] = $data[$field];
}
return $thirdparty;
}
}

View File

@@ -25,7 +25,7 @@ use Luracast\Restler\RestException;
* @smart-auto-routing false * @smart-auto-routing false
* @access protected * @access protected
* @class DolibarrApiAccess {@requires user,external} * @class DolibarrApiAccess {@requires user,external}
* * @deprecated Use Users instead (defined in api_users.class.php)
*/ */
class UserApi extends DolibarrApi class UserApi extends DolibarrApi
{ {
@@ -43,7 +43,7 @@ class UserApi extends DolibarrApi
public $useraccount; public $useraccount;
/** /**
* Constructor * Constructor <b>Warning: Deprecated</b>
* *
* @url user/ * @url user/
* *
@@ -55,7 +55,7 @@ class UserApi extends DolibarrApi
} }
/** /**
* Get properties of an user object * Get properties of an user object <b>Warning: Deprecated</b>
* *
* Return an array with user informations * Return an array with user informations
* *
@@ -85,7 +85,7 @@ class UserApi extends DolibarrApi
} }
/** /**
* Create useraccount object from contact * Create useraccount object from contact <b>Warning: Deprecated</b>
* *
* @param int $contactid Id of contact * @param int $contactid Id of contact
* @param array $request_data Request datas * @param array $request_data Request datas
@@ -129,7 +129,7 @@ class UserApi extends DolibarrApi
/** /**
* Create user account * Create user account <b>Warning: Deprecated</b>
* *
* @param array $request_data New user data * @param array $request_data New user data
* @return int * @return int
@@ -165,7 +165,7 @@ class UserApi extends DolibarrApi
/** /**
* Update account * Update account <b>Warning: Deprecated</b>
* *
* @param int $id Id of account to update * @param int $id Id of account to update
* @param array $request_data Datas * @param array $request_data Datas
@@ -201,7 +201,7 @@ class UserApi extends DolibarrApi
} }
/** /**
* add user to group * add user to group <b>Warning: Deprecated</b>
* *
* @param int $id User ID * @param int $id User ID
* @param int $group Group ID * @param int $group Group ID
@@ -228,7 +228,7 @@ class UserApi extends DolibarrApi
} }
/** /**
* Delete account * Delete account <b>Warning: Deprecated</b>
* *
* @param int $id Account ID * @param int $id Account ID
* @return array * @return array

View File

@@ -0,0 +1,218 @@
<?php
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use Luracast\Restler\RestException;
//require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
/**
* API class for users
*
* @access protected
* @class DolibarrApiAccess {@requires user,external}
*/
class Users extends DolibarrApi
{
/**
*
* @var array $FIELDS Mandatory fields, checked when create and update object
*/
static $FIELDS = array(
'login'
);
/**
* @var User $user {@type User}
*/
public $useraccount;
/**
* Constructor
*/
function __construct() {
global $db, $conf;
$this->db = $db;
$this->useraccount = new User($this->db);
}
/**
* Get properties of an user object
*
* Return an array with user informations
*
* @param int $id ID of user
* @return array|mixed data without useless information
*
* @throws RestException
*/
function get($id) {
//if (!DolibarrApiAccess::$user->rights->user->user->lire) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
return $this->_cleanObjectDatas($this->useraccount);
}
/**
* Create user account
*
* @param array $request_data New user data
* @return int
*/
function post($request_data = NULL) {
// check user authorization
//if(! DolibarrApiAccess::$user->rights->user->creer) {
// throw new RestException(401, "User creation not allowed");
//}
// check mandatory fields
/*if (!isset($request_data["login"]))
throw new RestException(400, "login field missing");
if (!isset($request_data["password"]))
throw new RestException(400, "password field missing");
if (!isset($request_data["lastname"]))
throw new RestException(400, "lastname field missing");*/
//assign field values
$xxx=var_export($request_data, true);
dol_syslog("xxx=".$xxx);
foreach ($request_data as $field => $value)
{
$this->useraccount->$field = $value;
}
$result = $this->useraccount->create(DolibarrApiAccess::$user);
if ($result <=0) {
throw new RestException(500, "User not created : ".$this->useraccount->error);
}
return array('id'=>$result);
}
/**
* Update account
*
* @param int $id Id of account to update
* @param array $request_data Datas
* @return int
*/
function put($id, $request_data = NULL) {
//if (!DolibarrApiAccess::$user->rights->user->user->creer) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
throw new RestException(404, 'Account not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
foreach ($request_data as $field => $value)
{
$this->useraccount->$field = $value;
}
if ($this->useraccount->update(DolibarrApiAccess::$user, 1))
return $this->get($id);
return false;
}
/**
* add user to group
*
* @param int $id User ID
* @param int $group Group ID
* @return int
*
* @url GET {id}/setGroup/{group}
*/
function setGroup($id, $group) {
//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
return $this->useraccount->SetInGroup($group,1);
}
/**
* Delete account
*
* @param int $id Account ID
* @return array
*/
function delete($id) {
//if (!DolibarrApiAccess::$user->rights->user->user->supprimer) {
//throw new RestException(401);
//}
$result = $this->useraccount->fetch($id);
if (!$result)
{
throw new RestException(404, 'User not found');
}
if (!DolibarrApi::_checkAccessToResource('user', $this->useraccount->id, 'user'))
{
throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
}
return $this->useraccount->delete($id);
}
/**
* Validate fields before create or update object
*
* @param array $data Data to validate
* @return array
* @throws RestException
*/
function _validate($data) {
$account = array();
foreach (Users::$FIELDS as $field)
{
if (!isset($data[$field]))
throw new RestException(400, "$field field missing");
$account[$field] = $data[$field];
}
return $account;
}
}

View File

@@ -147,7 +147,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase
{ {
global $conf,$user,$langs,$db; global $conf,$user,$langs,$db;
$url = $this->api_url.'/user/123456789?api_key='.$this->api_key; $url = $this->api_url.'/users/123456789?api_key='.$this->api_key;
//$addheaders=array('Content-Type: application/json'); //$addheaders=array('Content-Type: application/json');
print __METHOD__." Request url=".$url."\n"; print __METHOD__." Request url=".$url."\n";
@@ -159,7 +159,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase
$this->assertNotNull($object, "Parsing of json result must no be null"); $this->assertNotNull($object, "Parsing of json result must no be null");
$this->assertEquals(404, $object['error']['code']); $this->assertEquals(404, $object['error']['code']);
$url = $this->api_url.'/user/1?api_key='.$this->api_key; $url = $this->api_url.'/users/1?api_key='.$this->api_key;
print __METHOD__." Request url=".$url."\n"; print __METHOD__." Request url=".$url."\n";
$result=getURLContent($url, 'GET', '', 1, array()); $result=getURLContent($url, 'GET', '', 1, array());
@@ -174,7 +174,7 @@ class RestAPIUserTest extends PHPUnit_Framework_TestCase
public function testRestCreateUser() { public function testRestCreateUser() {
// attemp to create without mandatory fields : // attemp to create without mandatory fields :
$url = $this->api_url.'/user?api_key='.$this->api_key; $url = $this->api_url.'/users?api_key='.$this->api_key;
$addheaders=array('Content-Type: application/json'); $addheaders=array('Content-Type: application/json');
$bodyobj = array( $bodyobj = array(