diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index fd5204b..286685f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,14 @@ # User-specific files *.suo *.user +*.userosscache *.sln.docstates +**/App.config + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + # Build results [Dd]ebug/ [Dd]ebugPublic/ @@ -13,19 +19,21 @@ [Rr]eleases/ x64/ x86/ -build/ bld/ [Bb]in/ [Oo]bj/ +[Ll]og/ -# Roslyn cache directories -*.ide/ +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* -#NUNIT +# NUNIT *.VisualState.xml TestResult.xml @@ -34,6 +42,11 @@ TestResult.xml [Rr]eleasePS/ dlldata.c +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + *_i.c *_p.c *_i.h @@ -66,14 +79,18 @@ _Chutzpah* ipch/ *.aps *.ncb +*.opendb *.opensdf *.sdf *.cachefile +*.VC.db +*.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx +*.sap # TFS 2012 Local Workspace $tf/ @@ -86,7 +103,7 @@ _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user -# JustCode is a .NET coding addin-in +# JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in @@ -98,6 +115,7 @@ _TeamCity* # NCrunch _NCrunch_* .*crunch*.local.xml +nCrunchTemp_* # MightyMoose *.mm.* @@ -125,39 +143,63 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# TODO: Comment the next line if you want to checkin your web deploy settings +# TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted -*.pubxml +#*.pubxml *.publishproj +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/packages/* # except build/, which is used as an MSBuild target. !**/packages/build/ -# If using the old MSBuild-Integrated Package Restore, uncomment this: +# Uncomment if necessary however generally it will be regenerated when needed #!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets -# Windows Azure Build Output +# Microsoft Azure Build Output csx/ *.build.csdef -# Windows Store app package directory +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ # Others -sql/ -*.Cache ClientBin/ -[Ss]tyle[Cc]op.* ~$* *~ *.dbmdl *.dbproj.schemaview +*.jfm *.pfx *.publishsettings node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ # RIA/Silverlight projects Generated_Code/ @@ -181,3 +223,43 @@ UpgradeLog*.htm # Microsoft Fakes FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc +*.nuspec +*.nupkg \ No newline at end of file diff --git a/LICENSE b/LICENSE index 7942739..05c7df6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 RetailDriver LLC +Copyright (c) 2015-2017 RetailDriver LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 9ef9ec2..c36cc55 100644 --- a/README.md +++ b/README.md @@ -1,142 +1,73 @@ -.NET client for retailCRM API -============================= +.NET-клиент RetailCRM API +========================= -.NET client for [RetailCRM API](http://www.retailcrm.pro/docs/Developers/ApiVersion3). +.NET-клиент для работы с [RetailCRM API](http://www.retailcrm.ru/docs/Developers/Index). Клиент поддерживает все доступные на текущий момент версии API (v3-v5). -Requirements ------------------------ -* [Newtonsoft.Json](http://james.newtonking.com/json) - -Install with NuGet +Установка через NuGet --------------------- -Install [NuGet](http://docs.nuget.org/consume/installing-nuget). - -Run this command into [Package Manager Console](http://docs.nuget.org/docs/start-here/using-the-package-manager-console) ``` bash -PM> Install-Package RetailCRM.ApiClient +PM> Install-Package Retailcrm.SDK ``` -Usage +Примеры использования --------------------- -### Get order +### Получение информации о заказе ``` csharp -using RetailCrm; -using RetailCrm.Response; +using System.Diagnostics; +using Retailcrm; +using Retailcrm.Versions.V5; ... -ApiClient api; -try -{ - api = new ApiClient( - "https://demo.retailcrm.pro", - "T9DMPvuNt7FQJMszHUdG8Fkt6xHsqngH" - ); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} -ApiResponse response = null; -try -{ - response = api.ordersGet("M-2342"); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} +Client api = new Client("https://demo.retailcrm.ru", "T9DMPvuNt7FQJMszHUdG8Fkt6xHsqngH"); +Response response = api.OrdersGet("12345", "externalId"); if (response.isSuccessful()) { - System.Console.WriteLine(response["totalSumm"]); + Debug.WriteLine(Response.GetRawResponse()); } else { - System.Console.WriteLine( - "Error: [HTTP-code " + - response["statusCode"] + "] " + - response["errorMsg"] - ); + Debug.WriteLine($"Ошибка: [Статус HTTP-ответа {response.GetStatusCode().ToString()}]"); } ``` -### Create order +### Создание заказа ``` csharp -using RetailCrm; -using RetailCrm.Response; +using System.Diagnostics; +using Retailcrm; +using Retailcrm.Versions.V4; ... -ApiClient api; -string url, key; -try -{ - api = new ApiClient(url, key); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} -Dictionary tmpOrder = new Dictionary(){ - {"number", "example"}, - {"externalId", "example"}, - {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, - {"discount", 50}, - {"phone", "89263832233"}, - {"email", "example@gmail.com"}, - {"customerComment", "example"}, - {"customFields", new Dictionary(){ - {"reciever_phone", "example"}, - {"reciever_name", "example"}, - {"ext_number", "example"} - } - }, - {"contragentType", "individual"}, - {"orderType", "eshop-individual"}, - {"orderMethod", "app"}, - {"customerId", "555"}, - {"managerId", 8}, - {"items", new Dictionary(){ - {"0", new Dictionary(){ - {"initialPrice", 100}, - {"quantity", 1}, - {"productId", 55}, - {"productName", "example"} - } - } - } - }, - {"delivery", new Dictionary(){ - {"code", "courier"}, - {"date", DateTime.Now.ToString("Y-m-d")}, - {"address", new Dictionary(){ - {"text", "example"} - } - } - } - } - }; - -ApiResponse response = null; -try +Client api = new Client("https://demo.retailcrm.ru", "T9DMPvuNt7FQJMszHUdG8Fkt6xHsqngH"); +Response response = api.OrdersCreate(new Dictionary { - response = api.ordersEdit(order); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} + {"externalId", "12345"}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", "john@example.com"}, + {"phone", "+79999999999"}, + {"items", new List { + new Dictionary { + {"initialPrice", 100}, + {"quantity", 1}, + {"productId", 55}, + {"productName", "example"} + }, + new Dictionary { + {"initialPrice", 200}, + {"quantity", 2}, + {"productId", 14}, + {"productName", "example too"} + } + }} +}); -if (response.isSuccessful() && 201 == response["statusCode"]) { - System.Console.WriteLine( - "Order created. Order ID is " + response["id"] - ); +if (response.isSuccessful()) { + Debug.WriteLine(Response.GetResponse()["externalId"].ToString()); } else { - System.Console.WriteLine( - "Error: [HTTP-code " + - response["statusCode"] + "] " + - response["errorMsg"] - ); + Debug.WriteLine($"Ошибка: [Статус HTTP-ответа {response.GetStatusCode().ToString()}]"); } ``` diff --git a/README.ru.md b/README.ru.md deleted file mode 100644 index a4e58f1..0000000 --- a/README.ru.md +++ /dev/null @@ -1,142 +0,0 @@ -.NET-клиент для retailCRM API -============================= - -.NET-клиент для работы с [RetailCRM API](http://www.retailcrm.ru/docs/rest-api/index.html). - -Обязательные требования ------------------------ -* [Newtonsoft.Json](http://james.newtonking.com/json) - -Установка через NuGet ---------------------- - -Для начала требуется скачать и установить сам [NuGet](http://docs.nuget.org/consume/installing-nuget). - -После этого для установки клиента требуется запустить комманду в [Package Manager Console](http://docs.nuget.org/docs/start-here/using-the-package-manager-console) -``` bash -PM> Install-Package RetailCRM.ApiClient -``` - -Примеры использования ---------------------- - -### Получение информации о заказе - -``` csharp -using RetailCrm; -using RetailCrm.Response; -... -ApiClient api; -try -{ - api = new ApiClient( - "https://demo.retailcrm.ru", - "T9DMPvuNt7FQJMszHUdG8Fkt6xHsqngH" - ); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} - -ApiResponse response = null; -try -{ - response = api.ordersGet("M-2342"); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} - -if (response.isSuccessful()) { - System.Console.WriteLine(response["totalSumm"]); -} else { - System.Console.WriteLine( - "Ошибка получения информации о заказа: [Статус HTTP-ответа " + - response["statusCode"] + "] " + - response["errorMsg"] - ); -} - -``` -### Создание заказа - -``` csharp -using RetailCrm; -using RetailCrm.Response; -... -ApiClient api; -string url, key; -try -{ - api = new ApiClient(url, key); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} - -Dictionary tmpOrder = new Dictionary(){ - {"number", "example"}, - {"externalId", "example"}, - {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, - {"discount", 50}, - {"phone", "89263832233"}, - {"email", "example@gmail.com"}, - {"customerComment", "example"}, - {"customFields", new Dictionary(){ - {"reciever_phone", "example"}, - {"reciever_name", "example"}, - {"ext_number", "example"} - } - }, - {"contragentType", "individual"}, - {"orderType", "eshop-individual"}, - {"orderMethod", "app"}, - {"customerId", "555"}, - {"managerId", 8}, - {"items", new Dictionary(){ - {"0", new Dictionary(){ - {"initialPrice", 100}, - {"quantity", 1}, - {"productId", 55}, - {"productName", "example"} - } - } - } - }, - {"delivery", new Dictionary(){ - {"code", "courier"}, - {"date", DateTime.Now.ToString("Y-m-d")}, - {"address", new Dictionary(){ - {"text", "example"} - } - } - } - } - }; - -ApiResponse response = null; -try -{ - response = api.ordersEdit(order); -} -catch (WebException e) -{ - System.Console.WriteLine(e.ToString()); -} - -if (response.isSuccessful() && 201 == response["statusCode"]) { - System.Console.WriteLine( - "Заказ успешно создан. ID заказа в retailCRM = " + response["id"] - ); -} else { - System.Console.WriteLine( - "Ошибка создания заказа: [Статус HTTP-ответа " + - response["statusCode"] + "] " + - response["errorMsg"] - ); -} - -``` diff --git a/RetailCrm/ApiClient.cs b/RetailCrm/ApiClient.cs deleted file mode 100644 index 20fd743..0000000 --- a/RetailCrm/ApiClient.cs +++ /dev/null @@ -1,1073 +0,0 @@ -using Newtonsoft.Json; -using RetailCrm.Http; -using RetailCrm.Response; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace RetailCrm -{ - public class ApiClient - { - private const string apiVersion = "v3"; - protected Client client; - - /// - /// Site code - /// - protected string siteCode; - - /// - /// ApiClient creating - /// - /// - /// - /// - public ApiClient(string url, string apiKey, string site = "") - { - if ("/" != url.Substring(url.Length - 1, 1)) - { - url += "/"; - } - - url += "api/" + apiVersion; - - client = new Client(url, new Dictionary() { { "apiKey", apiKey } }); - siteCode = site; - } - - /// - /// Create a order - /// - /// - /// - /// ApiResponse - public ApiResponse ordersCreate(Dictionary order, string site = "") - { - if (order.Count < 1) - { - throw new ArgumentException("Parameter `order` must contains a data"); - } - - return client.makeRequest( - "/orders/create", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "order", JsonConvert.SerializeObject(order) } - } - ) - ); - } - - /// - /// Edit a order - /// - /// - /// - /// - /// ApiResponse - public ApiResponse ordersEdit(Dictionary order, string by = "externalId", string site = "") - { - if (order.Count < 1) - { - throw new ArgumentException("Parameter `order` must contains a data"); - } - - checkIdParameter(by); - - if (order.ContainsKey(by) == false) - { - throw new ArgumentException("Order array must contain the \"" + by + "\" parameter"); - } - - - return client.makeRequest( - "/orders/" + order[by] + "/edit", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "order", JsonConvert.SerializeObject(order) }, - { "by", by } - } - ) - ); - } - - /// - /// Upload array of the orders - /// - /// - /// - /// ApiResponse - public ApiResponse ordersUpload(Dictionary orders, string site = "") - { - if (orders.Count < 1) - { - throw new ArgumentException("Parameter `order` must contains a data"); - } - - return client.makeRequest( - "/orders/upload", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "orders", JsonConvert.SerializeObject(orders) } - } - ) - ); - } - - /// - /// Get order by id or externalId - /// - /// - /// - /// - /// ApiResponse - public ApiResponse ordersGet(string id, string by = "externalId", string site = "") - { - checkIdParameter(by); - - return client.makeRequest( - "/orders/" + id, - Client.METHOD_GET, - this.fillSite( - site, - new Dictionary() { - { "by", by } - } - ) - ); - } - - /// - /// Returns a orders history - /// - /// - /// - /// - /// - /// - /// ApiResponse - public ApiResponse ordersHistory( - DateTime? startDate = null, - DateTime? endDate = null, - int limit = 100, - int offset = 0, - bool skipMyChanges = true - ) - { - Dictionary parameters = new Dictionary(); - - if (startDate != null) - { - parameters.Add("startDate", startDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); - } - if (endDate != null) - { - parameters.Add("endDate", endDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - if (offset > 0) - { - parameters.Add("offset", offset); - } - if (skipMyChanges == true) - { - parameters.Add("skipMyChanges", skipMyChanges); - } - - return client.makeRequest("/orders/history", Client.METHOD_GET, parameters); - } - - /// - /// Returns filtered orders list - /// - /// - /// - /// - /// ApiResponse - public ApiResponse ordersList(Dictionary filter = null, int page = 0, int limit = 0) - { - Dictionary parameters = new Dictionary(); - - if (filter.Count > 0) - { - parameters.Add("filter", filter); - } - if (page > 0) - { - parameters.Add("page", page); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - - return client.makeRequest("/orders", Client.METHOD_GET, parameters); - } - - /// - /// Returns statuses of the orders - /// - /// - /// - /// ApiResponse - public ApiResponse ordersStatuses(Dictionary ids = null, Dictionary externalIds = null) - { - Dictionary parameters = new Dictionary(); - - if (ids.Count > 0) - { - parameters.Add("ids", ids); - } - if (externalIds.Count > 0) - { - parameters.Add("externalIds", externalIds); - } - - return client.makeRequest("/orders/statuses", Client.METHOD_GET, parameters); - } - - /// - /// Save order IDs' (id and externalId) association in the CRM - /// - /// - /// ApiResponse - public ApiResponse ordersFixExternalId(Dictionary ids) - { - if (ids.Count < 1) - { - throw new ArgumentException("Method parameter must contains at least one IDs pair"); - } - - return client.makeRequest( - "/orders/fix-external-ids", - Client.METHOD_POST, - new Dictionary() { - { "orders", JsonConvert.SerializeObject(ids) } - } - ); - } - - /// - /// Create a customer - /// - /// - /// - /// ApiResponse - public ApiResponse customersCreate(Dictionary customer, string site = "") - { - if (customer.Count < 1) - { - throw new ArgumentException("Parameter `customer` must contains a data"); - } - - return client.makeRequest( - "/customers/create", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "customer", JsonConvert.SerializeObject(customer) } - } - ) - ); - } - - /// - /// Edit a customer - /// - /// - /// - /// - /// ApiResponse - public ApiResponse customersEdit(Dictionary customer, string by = "externalId", string site = "") - { - if (customer.Count < 1) - { - throw new ArgumentException("Parameter `customer` must contains a data"); - } - - checkIdParameter(by); - - if (customer.ContainsKey(by) == false) - { - throw new ArgumentException("Customer array must contain the \"" + by + "\" parameter"); - } - - - return client.makeRequest( - "/customers/" + customer[by] + "/edit", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "customer", JsonConvert.SerializeObject(customer) }, - { "by", by } - } - ) - ); - } - - /// - /// Upload array of the customers - /// - /// - /// - /// ApiResponse - public ApiResponse customersUpload(Dictionary customers, string site = "") - { - if (customers.Count < 1) - { - throw new ArgumentException("Parameter `customers` must contains a data"); - } - - return client.makeRequest( - "/customers/upload", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "customers", JsonConvert.SerializeObject(customers) } - } - ) - ); - } - - /// - /// Get customer by id or externalId - /// - /// - /// - /// - /// ApiResponse - public ApiResponse customersGet(string id, string by = "externalId", string site = "") - { - checkIdParameter(by); - - return client.makeRequest( - "/customers/" + id, - Client.METHOD_GET, - this.fillSite( - site, - new Dictionary() { - { "by", by } - } - ) - ); - } - - /// - /// Returns filtered customers list - /// - /// - /// - /// - /// ApiResponse - public ApiResponse customersList(Dictionary filter = null, int page = 0, int limit = 0) - { - Dictionary parameters = new Dictionary(); - if (filter.Count > 0) - { - parameters.Add("filter", filter); - } - if (page > 0) - { - parameters.Add("page", page); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - - return client.makeRequest("/customers", Client.METHOD_GET, parameters); - } - - /// - /// Save customer IDs' (id and externalId) association in the CRM - /// - /// - /// ApiResponse - public ApiResponse customersFixExternalIds(Dictionary ids) - { - if (ids.Count < 1) - { - throw new ArgumentException("Method parameter must contains at least one IDs pair"); - } - - return client.makeRequest( - "/customers/fix-external-ids", - Client.METHOD_POST, - new Dictionary() { - { "customers", JsonConvert.SerializeObject(ids) } - } - ); - } - - /// - /// Returns filtered orders packs list - /// - /// - /// - /// - /// ApiResponse - public ApiResponse packsList(Dictionary filter = null, int page = 0, int limit = 0) - { - Dictionary parameters = new Dictionary(); - - if (filter.Count > 0) - { - parameters.Add("filter", filter); - } - if (page > 0) - { - parameters.Add("page", page); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - - return client.makeRequest("/orders/packs", Client.METHOD_GET, parameters); - } - - /// - /// Create a order pack - /// - /// - /// ApiResponse - public ApiResponse packsCreate(Dictionary pack) - { - if (pack.Count < 1) - { - throw new ArgumentException("Parameter `pack` must contains a data"); - } - - return client.makeRequest( - "/orders/packs/create", - Client.METHOD_POST, - new Dictionary() { - { "pack", JsonConvert.SerializeObject(pack) } - } - ); - } - - /// - /// Returns a orders history - /// - /// - /// - /// - /// ApiResponse - public ApiResponse packsHistory(Dictionary filter = null, int page = 0, int limit = 0) - { - Dictionary parameters = new Dictionary(); - - if (filter.Count > 0) - { - parameters.Add("filter", filter); - } - if (page > 0) - { - parameters.Add("page", page); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - - return client.makeRequest("/orders/packs/history", Client.METHOD_GET, parameters); - } - - /// - /// Get order packs by id - /// - /// - /// ApiResponse - public ApiResponse packsGet(string id) - { - return client.makeRequest("/orders/packs/" + id, Client.METHOD_GET); - } - - /// - /// Delete order packs by id - /// - /// - /// ApiResponse - public ApiResponse packsDelete(string id) - { - return client.makeRequest("/orders/packs/" + id + "/delete", Client.METHOD_POST); - } - - /// - /// Edit a order packs - /// - /// - /// - /// ApiResponse - public ApiResponse packsEdit(string id, Dictionary pack) - { - if (pack.Count < 1) - { - throw new ArgumentException("Parameter `pack` must contains a data"); - } - - return client.makeRequest( - "/orders/packs/" + id + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "pack", JsonConvert.SerializeObject(pack) } - } - ); - } - - /// - /// Returns filtered store inventories list - /// - /// - /// - /// - /// ApiResponse - public ApiResponse inventoriesList(Dictionary filter = null, int page = 0, int limit = 0) - { - Dictionary parameters = new Dictionary(); - - if (filter.Count > 0) - { - parameters.Add("filter", filter); - } - if (page > 0) - { - parameters.Add("page", page); - } - if (limit > 0) - { - parameters.Add("limit", limit); - } - - return client.makeRequest("/store/inventories", Client.METHOD_GET, parameters); - } - - /// - /// Upload array of the store inventories - /// - /// - /// - /// ApiResponse - public ApiResponse inventoriesUpload(Dictionary offers, string site = "") - { - if (offers.Count < 1) - { - throw new ArgumentException("Parameter `offers` must contains a data"); - } - - return client.makeRequest( - "/store/inventories/upload", - Client.METHOD_POST, - this.fillSite( - site, - new Dictionary() { - { "offers", JsonConvert.SerializeObject(offers) } - } - ) - ); - } - - /// - /// Returns deliveryServices list - /// - /// ApiResponse - public ApiResponse deliveryServicesList() - { - return client.makeRequest("/reference/delivery-services", Client.METHOD_GET); - } - - /// - /// Returns deliveryTypes list - /// - /// ApiResponse - public ApiResponse deliveryTypesList() - { - return client.makeRequest("/reference/delivery-types", Client.METHOD_GET); - } - - /// - /// Returns orderMethods list - /// - /// ApiResponse - public ApiResponse orderMethodsList() - { - return client.makeRequest("/reference/order-methods", Client.METHOD_GET); - } - - /// - /// Returns orderTypes list - /// - /// ApiResponse - public ApiResponse orderTypesList() - { - return client.makeRequest("/reference/order-types", Client.METHOD_GET); - } - - /// - /// Returns paymentStatuses list - /// - /// ApiResponse - public ApiResponse paymentStatusesList() - { - return client.makeRequest("/reference/payment-statuses", Client.METHOD_GET); - } - - /// - /// Returns paymentTypes list - /// - /// ApiResponse - public ApiResponse paymentTypesList() - { - return client.makeRequest("/reference/payment-types", Client.METHOD_GET); - } - - /// - /// Returns productStatuses list - /// - /// ApiResponse - public ApiResponse productStatusesList() - { - return client.makeRequest("/reference/product-statuses", Client.METHOD_GET); - } - - /// - /// Returns statusGroups list - /// - /// ApiResponse - public ApiResponse statusGroupsList() - { - return client.makeRequest("/reference/status-groups", Client.METHOD_GET); - } - - /// - /// Returns statuses list - /// - /// ApiResponse - public ApiResponse statusesList() - { - return client.makeRequest("/reference/statuses", Client.METHOD_GET); - } - - /// - /// Returns sites list - /// - /// ApiResponse - public ApiResponse sitesList() - { - return client.makeRequest("/reference/sites", Client.METHOD_GET); - } - - /// - /// Returns stores list - /// - /// ApiResponse - public ApiResponse storesList() - { - return client.makeRequest("/reference/stores", Client.METHOD_GET); - } - - /// - /// Returns countries list - /// - /// ApiResponse - public ApiResponse countriesList() - { - return client.makeRequest("/reference/countries", Client.METHOD_GET); - } - - /// - /// Edit deliveryService - /// - /// - /// ApiResponse - public ApiResponse deliveryServicesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/delivery-services/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "deliveryService", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit deliveryType - /// - /// - /// ApiResponse - public ApiResponse deliveryTypesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/delivery-types/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "deliveryType", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit orderMethod - /// - /// - /// ApiResponse - public ApiResponse orderMethodsEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/order-methods/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "orderMethod", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit orderType - /// - /// - /// ApiResponse - public ApiResponse orderTypesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/order-types/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "orderType", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit paymentStatus - /// - /// - /// ApiResponse - public ApiResponse paymentStatusesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/payment-statuses/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "paymentStatus", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit paymentType - /// - /// - /// ApiResponse - public ApiResponse paymentTypesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/payment-types/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "paymentType", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit productStatus - /// - /// - /// ApiResponse - public ApiResponse productStatusesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/product-statuses/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "productStatus", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit order status - /// - /// - /// ApiResponse - public ApiResponse statusesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/statuses/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "status", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit site - /// - /// - /// ApiResponse - public ApiResponse sitesEdit(Dictionary data) - { - if (data.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/sites/" + data["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "site", JsonConvert.SerializeObject(data) } - } - ); - } - - /// - /// Edit stores - /// - /// - /// ApiResponse - public ApiResponse storesEdit(Dictionary store) - { - if (store.ContainsKey("code") == false) - { - throw new ArgumentException("Data must contain \"code\" parameter"); - } - - return client.makeRequest( - "/reference/stores/" + store["code"] + "/edit", - Client.METHOD_POST, - new Dictionary() { - { "store", JsonConvert.SerializeObject(store) } - } - ); - } - - /// - /// Captures events call for the user - /// - /// - /// - /// - /// - /// ApiResponse - public ApiResponse telephonyСallEventCreate(string phone, string type, string code, string hangupStatus) - { - Dictionary parameters = new Dictionary(); - - if (string.IsNullOrEmpty(phone)) - { - throw new ArgumentException("Parameter \"phone\" can not be empty"); - } - - if (string.IsNullOrEmpty(type)) - { - throw new ArgumentException("Option \"type\" can not be empty. Valid values: in, out, hangup."); - } - - if (string.IsNullOrEmpty(code)) - { - throw new ArgumentException("Option \"code\" can not be empty."); - } - - parameters.Add("phone", phone); - parameters.Add("type", type); - parameters.Add("code", code); - - if (!string.IsNullOrEmpty(hangupStatus)) - { - parameters.Add("hangupStatus", hangupStatus); - } - - return client.makeRequest("/telephony/call/event", Client.METHOD_POST, parameters); - } - - /// - /// It allows you to save your call history - /// - /// - /// ApiResponse - public ApiResponse telephonyСallsUpload(Dictionary calls) - { - return client.makeRequest( - "/telephony/calls/upload", - Client.METHOD_POST, - new Dictionary() { - { "calls", JsonConvert.SerializeObject(calls) } - } - ); - } - - /// - /// Returns the responsible manager for the client with the phone - /// - /// - /// - /// ApiResponse - public ApiResponse telephonyManagerGet(string phone, bool details = false) - { - if (string.IsNullOrEmpty(phone)) - { - throw new ArgumentException("Parameter \"phone\" can not be empty"); - } - - return client.makeRequest( - "/telephony/manager", - Client.METHOD_GET, - new Dictionary() { - { "phone", phone }, - { "details", details } - } - ); - } - - /// - /// Allows you to create/activate/deactivate the phone in the system and specify the necessary settings for the job - /// - /// - /// - /// - /// - /// ApiResponse - public ApiResponse telephonySettingEdit(string code, string clientId, string makeCallUrl, bool active = true) - { - Dictionary parameters = new Dictionary(); - - if (string.IsNullOrEmpty(code)) - { - throw new ArgumentException("Parameter \"code\" can not be empty"); - } - - if (string.IsNullOrEmpty(clientId)) - { - throw new ArgumentException("Option \"clientId\" can not be empty."); - } - - parameters.Add("code", code); - parameters.Add("clientId", clientId); - parameters.Add("active", active); - - if (!string.IsNullOrEmpty(makeCallUrl)) - { - parameters.Add("makeCallUrl", makeCallUrl); - } - - return client.makeRequest("/telephony/setting/" + code, Client.METHOD_POST, parameters); - } - - /// - /// Update CRM basic statistic - /// - /// ApiResponse - public ApiResponse statisticUpdate() - { - return client.makeRequest("/statistic/update", Client.METHOD_GET); - } - - /// - /// Return current site - /// - /// string - public string getSite() - { - return this.siteCode; - } - - /// - /// Return current site - /// - public void setSite(string site) - { - this.siteCode = site; - } - - /// - /// Check ID parameter - /// - /// - protected void checkIdParameter(string by) - { - string[] allowedForBy = new string[] { "externalId", "id" }; - if (allowedForBy.Contains(by) == false) - { - throw new ArgumentException("Value \"" + by + "\" for parameter \"by\" is not valid. Allowed values are " + String.Join(", ", allowedForBy)); - } - } - - /// - /// Fill params by site value - /// - /// - /// - /// Dictionary - protected Dictionary fillSite(string site, Dictionary param) - { - if (site.Length > 1) - { - param.Add("site", site); - } - else if (siteCode.Length > 1) - { - param.Add("site", siteCode); - } - - return param; - } - } -} diff --git a/RetailCrm/Exceptions/InvalidJsonException.cs b/RetailCrm/Exceptions/InvalidJsonException.cs deleted file mode 100644 index 12f19d0..0000000 --- a/RetailCrm/Exceptions/InvalidJsonException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace RetailCrm.Exceptions -{ - public class InvalidJsonException : Exception - { - public InvalidJsonException() - { - } - - public InvalidJsonException(string message) - : base(message) - { - } - - public InvalidJsonException(string message, Exception inner) - : base(message, inner) - { - } - } -} diff --git a/RetailCrm/Extra/Tools.cs b/RetailCrm/Extra/Tools.cs deleted file mode 100644 index a0f8c0e..0000000 --- a/RetailCrm/Extra/Tools.cs +++ /dev/null @@ -1,97 +0,0 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; - -namespace RetailCrm.Extra -{ - class Tools - { - public static string httpBuildQuery(Dictionary data) - { - if (data is Dictionary == false) - { - return String.Empty; - } - - var parts = new List(); - HandleItem(data, parts); - return String.Join("&", parts); - } - - private static void HandleItem(object data, List parts, string prefix = "") - { - if (data == null) return; - - if (data is Dictionary) - { - parts.Add(FormatDictionary((Dictionary)data, prefix)); - } - else - { - parts.Add(String.IsNullOrEmpty(data.ToString()) ? String.Empty : String.Format("{0}={1}", prefix, data.ToString())); - } - } - - private static string FormatDictionary(Dictionary obj, string prefix = "") - { - var parts = new List(); - foreach (KeyValuePair kvp in obj) - { - string newPrefix = string.IsNullOrEmpty(prefix) ? - String.Format("{0}{1}", prefix, kvp.Key) : - String.Format("{0}[{1}]", prefix, kvp.Key); - HandleItem(kvp.Value, parts, newPrefix); - } - - return String.Join("&", parts); - } - - public static Dictionary jsonDecode(string json) - { - return jsonObjectToDictionary((Dictionary)JsonConvert.DeserializeObject>(json)); - } - - private static Dictionary jsonObjectToDictionary(Dictionary data) - { - Dictionary result = new Dictionary(); - foreach (KeyValuePair kvp in data) - { - object valueObj = kvp.Value; - string value = String.Empty; - - value = valueObj.ToString(); - - if (value != "") - { - if (valueObj.GetType() == typeof(JObject)) - { - valueObj = jsonObjectToDictionary((Dictionary)JsonConvert.DeserializeObject>(value)); - result.Add(kvp.Key.ToString(), valueObj); - } - else if (valueObj.GetType() == typeof(JArray)) - { - var items = new List(); - - dynamic dynamicObject = JsonConvert.DeserializeObject(value); - Dictionary newObject = new Dictionary(); - - int j = 0; - foreach (var item in dynamicObject) - { - newObject.Add(j.ToString(), jsonObjectToDictionary(item.ToObject>())); - j++; - } - - result.Add(kvp.Key.ToString(), newObject); - } - else - { - result.Add(kvp.Key.ToString(), valueObj); - } - } - } - return result; - } - } -} diff --git a/RetailCrm/Http/Client.cs b/RetailCrm/Http/Client.cs deleted file mode 100644 index 9cb9810..0000000 --- a/RetailCrm/Http/Client.cs +++ /dev/null @@ -1,111 +0,0 @@ -using RetailCrm.Extra; -using RetailCrm.Response; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; - -namespace RetailCrm.Http -{ - /// - /// HTTP client - /// - public class Client - { - public const string METHOD_GET = "GET"; - public const string METHOD_POST = "POST"; - private const string USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; - private const string CONTENT_TYPE = "application/x-www-form-urlencoded"; - - protected string url; - protected Dictionary defaultParameter; - - /// - /// Creating HTTP client - /// - /// - /// - public Client(string apiUrl, Dictionary parameters = null) - { - if (apiUrl.IndexOf("https://") == -1) - { - throw new ArgumentException("API schema requires HTTPS protocol"); - } - - url = apiUrl; - defaultParameter = parameters; - } - - /// - /// Make HTTP request - /// - /// - /// - /// - /// - /// - public ApiResponse makeRequest(string path, string method, Dictionary parameters = null, int timeout = 30) - { - string[] allowedMethods = new string[] { METHOD_GET, METHOD_POST }; - if (allowedMethods.Contains(method) == false) - { - throw new ArgumentException("Method \"" + method + "\" is not valid. Allowed methods are " + String.Join(", ", allowedMethods)); - } - if (parameters == null) { - parameters = new Dictionary(); - } - parameters = defaultParameter.Union(parameters).ToDictionary(k => k.Key, v => v.Value); - path = url + path; - string httpQuery = Tools.httpBuildQuery(parameters); - - if (method.Equals(METHOD_GET) && parameters.Count > 0) - { - path += "?" + httpQuery; - } - - Exception exception = null; - - HttpWebRequest request = (HttpWebRequest) WebRequest.Create(path); - request.Method = method; - - if (method.Equals(METHOD_POST)) - { - UTF8Encoding encoding = new UTF8Encoding(); - byte[] bytes = encoding.GetBytes(httpQuery); - request.ContentLength = bytes.Length; - request.ContentType = CONTENT_TYPE; - request.UserAgent = USER_AGENT; - - Stream post = request.GetRequestStream(); - post.Write(bytes, 0, bytes.Length); - post.Flush(); - post.Close(); - } - - HttpWebResponse response = null; - try - { - response = (HttpWebResponse)request.GetResponse(); - } - catch (WebException ex) - { - response = (HttpWebResponse)ex.Response; - exception = ex; - } - - if (request == null || response == null) - { - throw new WebException(exception.ToString(), exception); - } - - StreamReader reader = new StreamReader((Stream) response.GetResponseStream()); - string responseBody = reader.ReadToEnd(); - int statusCode = (int) response.StatusCode; - - return new ApiResponse(statusCode, responseBody); - } - } -} diff --git a/RetailCrm/Response/ApiResponse.cs b/RetailCrm/Response/ApiResponse.cs deleted file mode 100644 index 6344f18..0000000 --- a/RetailCrm/Response/ApiResponse.cs +++ /dev/null @@ -1,94 +0,0 @@ -using Newtonsoft.Json; -using RetailCrm.Exceptions; -using RetailCrm.Extra; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace RetailCrm.Response -{ - /// - /// Response from retailCRM API - /// - public class ApiResponse - { - /// - /// HTTP response status code - /// - protected int statusCode; - - /// - /// Response - /// - protected Dictionary response; - - /// - /// Creating ApiResponse - /// - /// - /// - public ApiResponse(int statusCode, string responseBody = null) - { - this.statusCode = statusCode; - - if (responseBody != null && responseBody.Length > 0) - { - Dictionary response = new Dictionary(); - try - { - response = Tools.jsonDecode(responseBody); - } - catch (JsonReaderException e) - { - throw new InvalidJsonException("Invalid JSON in the API response body. " + e.ToString()); - } - - this.response = response; - } - } - - /// - /// Return HTTP response status code - /// - /// int - public int getStatusCode() - { - return this.statusCode; - } - - /// - /// HTTP request was successful - /// - /// boolean - public bool isSuccessful() - { - return this.statusCode < 400; - } - - /// - /// Return response - /// - /// Dictionary - public object this[string code] - { - get { - if (this.response.ContainsKey(code)) - { - return this.response[code]; - } - else - { - return new Dictionary(); - } - } - set - { - throw new ArgumentException("Property \"" + code + "\" is not writable"); - } - } - - - } -} diff --git a/Retailcrm.sln b/Retailcrm.sln new file mode 100644 index 0000000..6f3e5bf --- /dev/null +++ b/Retailcrm.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.16 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Retailcrm", "Retailcrm\Retailcrm.csproj", "{9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RetailcrmUnitTest", "RetailcrmUnitTest\RetailcrmUnitTest.csproj", "{4069C2BC-C277-48A3-96AE-DA5934A75F4D}" + ProjectSection(ProjectDependencies) = postProject + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41} = {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41}.Release|Any CPU.Build.0 = Release|Any CPU + {4069C2BC-C277-48A3-96AE-DA5934A75F4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4069C2BC-C277-48A3-96AE-DA5934A75F4D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4069C2BC-C277-48A3-96AE-DA5934A75F4D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4069C2BC-C277-48A3-96AE-DA5934A75F4D}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7EB29423-9A10-4953-B3E8-563908B2D206} + EndGlobalSection +EndGlobal diff --git a/Retailcrm/Connection.cs b/Retailcrm/Connection.cs new file mode 100644 index 0000000..db3540b --- /dev/null +++ b/Retailcrm/Connection.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; + +namespace Retailcrm +{ + /// + /// Unversioned API Client + /// + public class Connection + { + private readonly Request _request; + + /// + /// Unversioned API Client Constructor + /// + /// + /// + public Connection(string url, string key) + { + if ("/" != url.Substring(url.Length - 1, 1)) + { + url += "/"; + } + + url += "api/"; + + _request = new Request(url, new Dictionary { { "apiKey", key } }); + } + + /// + /// Get available API versions + /// + /// + public Response Versions() + { + return _request.MakeRequest( + "api-versions", + Request.MethodGet + ); + } + + /// + /// Get available API methods + /// + /// + public Response Credentials() + { + return _request.MakeRequest( + "credentials", + Request.MethodGet + ); + } + } +} diff --git a/Retailcrm/Properties/AssemblyInfo.cs b/Retailcrm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..30a418d --- /dev/null +++ b/Retailcrm/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, +// связанные со сборкой. +[assembly: AssemblyTitle("Retailcrm.SDK")] +[assembly: AssemblyDescription("Multiversion API client for RetailCRM")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("RetailDriver LLC")] +[assembly: AssemblyProduct("Retailcrm.SDK")] +[assembly: AssemblyCopyright("Copyright © RetailDriver LLC 2017")] +[assembly: AssemblyTrademark("RetailDriver LLC")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(true)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("9c378ef4-9f9b-4214-a9aa-1fc3c44edb41")] + +// Сведения о версии сборки состоят из следующих четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номер сборки и номер редакции по умолчанию. +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("5.0.0.0")] +[assembly: AssemblyFileVersion("5.0.0.0")] diff --git a/Retailcrm/QueryBuilder.cs b/Retailcrm/QueryBuilder.cs new file mode 100644 index 0000000..0f8fa0e --- /dev/null +++ b/Retailcrm/QueryBuilder.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Retailcrm +{ + /// + /// QueryBuilder + /// + public class QueryBuilder + { + private readonly List> _keyValuePairs + = new List>(); + + /// + /// Build PHP like query string + /// + /// + /// + /// + public static string BuildQueryString(object queryData, string argSeperator = "&") + { + var encoder = new QueryBuilder(); + encoder.AddEntry(null, queryData, allowObjects: true); + + return encoder.GetUriString(argSeperator); + } + + /// + /// GetUriString + /// + /// + /// + private string GetUriString(string argSeperator) + { + return String.Join(argSeperator, + _keyValuePairs.Select(kvp => + { + var key = Uri.EscapeDataString(kvp.Key); + var value = Uri.EscapeDataString(kvp.Value.ToString()); + return $"{key}={value}"; + })); + } + + /// + /// AddEntry + /// + /// + /// + /// + private void AddEntry(string prefix, object instance, bool allowObjects) + { + var dictionary = instance as IDictionary; + var collection = instance as ICollection; + + if (dictionary != null) + { + Add(prefix, GetDictionaryAdapter(dictionary)); + } + else if (collection != null) + { + Add(prefix, GetArrayAdapter(collection)); + } + else if (allowObjects) + { + Add(prefix, GetObjectAdapter(instance)); + } + else + { + _keyValuePairs.Add(new KeyValuePair(prefix, instance)); + } + } + + /// + /// Add + /// + /// + /// + private void Add(string prefix, IEnumerable datas) + { + foreach (var item in datas) + { + var newPrefix = String.IsNullOrEmpty(prefix) + ? item.Key + : $"{prefix}[{item.Key}]"; + + AddEntry(newPrefix, item.Value, allowObjects: false); + } + } + + /// + /// Entry + /// + private struct Entry + { + public string Key; + public object Value; + } + + /// + /// GetObjectAdapter + /// + /// + /// + private IEnumerable GetObjectAdapter(object data) + { + var properties = data.GetType().GetProperties(); + + foreach (var property in properties) + { + yield return new Entry + { + Key = property.Name, + Value = property.GetValue(data) + }; + } + } + + /// + /// GetArrayAdapter + /// + /// + /// + private IEnumerable GetArrayAdapter(ICollection collection) + { + int i = 0; + foreach (var item in collection) + { + yield return new Entry + { + Key = i.ToString(), + Value = item + }; + i++; + } + } + + /// + /// GetDictionaryAdapter + /// + /// + /// + private IEnumerable GetDictionaryAdapter(IDictionary collection) + { + foreach (DictionaryEntry item in collection) + { + yield return new Entry + { + Key = item.Key.ToString(), + Value = item.Value + }; + } + } + } +} \ No newline at end of file diff --git a/Retailcrm/Request.cs b/Retailcrm/Request.cs new file mode 100644 index 0000000..403b472 --- /dev/null +++ b/Retailcrm/Request.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; + +namespace Retailcrm +{ + /// + /// Request + /// + public class Request + { + /// + /// Get method + /// + public const string MethodGet = "GET"; + /// + /// Post method + /// + public const string MethodPost = "POST"; + private const string UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; + private const string ContentType = "application/x-www-form-urlencoded"; + + private readonly string _url; + private readonly Dictionary _defaultParameters; + + /// + /// Request constructor + /// + /// + /// + /// + public Request(string apiUrl, Dictionary parameters = null) + { + if (apiUrl.IndexOf("https://", StringComparison.Ordinal) == -1) + { + throw new ArgumentException("API schema requires HTTPS protocol"); + } + + _url = apiUrl; + _defaultParameters = parameters; + } + + /// + /// Make request method + /// + /// + /// + /// + /// + /// + /// + public Response MakeRequest(string path, string method, Dictionary parameters = null) + { + string[] allowedMethods = { MethodGet, MethodPost }; + + if (allowedMethods.Contains(method) == false) + { + throw new ArgumentException($"Method {method} is not valid. Allowed HTTP methods are {string.Join(", ", allowedMethods)}"); + } + + if (parameters == null) + { + parameters = new Dictionary(); + } + + parameters = _defaultParameters.Union(parameters).ToDictionary(k => k.Key, v => v.Value); + path = _url + path; + + string httpQuery = QueryBuilder.BuildQueryString(parameters); + + if (method.Equals(MethodGet) && parameters.Count > 0) + { + path += "?" + httpQuery; + } + + Exception exception = null; + + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path); + request.Method = method; + + if (method.Equals(MethodPost)) + { + UTF8Encoding encoding = new UTF8Encoding(); + byte[] bytes = encoding.GetBytes(httpQuery); + request.ContentLength = bytes.Length; + request.ContentType = ContentType; + request.UserAgent = UserAgent; + + Stream post = request.GetRequestStream(); + post.Write(bytes, 0, bytes.Length); + post.Flush(); + post.Close(); + } + + HttpWebResponse response; + + try + { + response = (HttpWebResponse)request.GetResponse(); + } + catch (WebException webException) + { + response = (HttpWebResponse)webException.Response; + exception = webException; + } + + if (request == null || response == null) + { + throw new WebException(exception.ToString(), exception); + } + + // ReSharper disable once AssignNullToNotNullAttribute + StreamReader reader = new StreamReader(response.GetResponseStream()); + string responseBody = reader.ReadToEnd(); + int statusCode = (int)response.StatusCode; + + return new Response(statusCode, responseBody); + } + } +} \ No newline at end of file diff --git a/Retailcrm/Response.cs b/Retailcrm/Response.cs new file mode 100644 index 0000000..a312ed6 --- /dev/null +++ b/Retailcrm/Response.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm +{ + /// + /// Response + /// + public class Response + { + private readonly int _statusCode; + private readonly string _rawResponse; + private readonly Dictionary _responseData; + + /// + /// Response constructor + /// + /// + /// + /// + public Response(int statusCode, string responseBody = null) + { + _statusCode = statusCode; + + if (string.IsNullOrEmpty(responseBody)) + { + throw new ArgumentException("Response body is empty"); + } + + _rawResponse = responseBody; + + var jsSerializer = new JavaScriptSerializer(); + _responseData = (Dictionary)jsSerializer.DeserializeObject(responseBody); + } + + /// + /// Get response status code + /// + /// + public int GetStatusCode() + { + return _statusCode; + } + + /// + /// Get response body data + /// + /// + public Dictionary GetResponse() + { + return _responseData; + } + + /// + /// Get raw response body + /// + /// + public string GetRawResponse() + { + return _rawResponse; + } + + /// + /// Check response is successfull + /// + /// + public bool IsSuccessfull() + { + return _statusCode < 400; + } + } +} \ No newline at end of file diff --git a/Retailcrm/Retailcrm.csproj b/Retailcrm/Retailcrm.csproj new file mode 100644 index 0000000..418a598 --- /dev/null +++ b/Retailcrm/Retailcrm.csproj @@ -0,0 +1,91 @@ + + + + + Debug + AnyCPU + {9C378EF4-9F9B-4214-A9AA-1FC3C44EDB41} + Library + Properties + Retailcrm + Retailcrm + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\Retailcrm.xml + + + + ..\..\Marwin\packages\JetBrains.Annotations.11.0.0\lib\net20\JetBrains.Annotations.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Retailcrm/Versions/V3/Client.cs b/Retailcrm/Versions/V3/Client.cs new file mode 100644 index 0000000..f2ea125 --- /dev/null +++ b/Retailcrm/Versions/V3/Client.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Retailcrm.Versions.V3 +{ + /// + /// V3 Client + /// + public partial class Client + { + /// + /// Request + /// + protected Request Request; + /// + /// Site code + /// + protected string SiteCode; + + /// + /// V3 Client Constructor + /// + /// + /// + /// + public Client(string url, string key, string site = "") + { + if ("/" != url.Substring(url.Length - 1, 1)) + { + url += "/"; + } + + url += "api/v3"; + + Request = new Request(url, new Dictionary { { "apiKey", key } }); + SiteCode = site; + } + + /// + /// Return current site + /// + /// string + public string GetSite() + { + return SiteCode; + } + + /// + /// Return current site + /// + public void SetSite(string site) + { + SiteCode = site; + } + + /// + /// Check ID parameter + /// + /// + protected static void CheckIdParameter(string by) + { + string[] allowedForBy = { "externalId", "id" }; + if (allowedForBy.Contains(by) == false) + { + throw new ArgumentException($"Value {by} for parameter `by` is not valid. Allowed values are {string.Join(", ", allowedForBy)}"); + } + } + + /// + /// Fill params by site value + /// + /// + /// + /// Dictionary + protected Dictionary FillSite(string site, Dictionary param) + { + if (site.Length > 1) + { + param.Add("site", site); + } + else if (SiteCode.Length > 1) + { + param.Add("site", SiteCode); + } + + return param; + } + } +} diff --git a/Retailcrm/Versions/V3/Customers.cs b/Retailcrm/Versions/V3/Customers.cs new file mode 100644 index 0000000..3204bf8 --- /dev/null +++ b/Retailcrm/Versions/V3/Customers.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Create customer + /// + /// + /// + /// + /// + public Response CustomersCreate(Dictionary customer, string site = "") + { + if (customer.Count < 1) + { + throw new ArgumentException("Parameter `customer` must contains a data"); + } + + return Request.MakeRequest( + "/customers/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "customer", new JavaScriptSerializer().Serialize(customer) } + } + ) + ); + } + + /// + /// Update customer + /// + /// + /// + /// + /// + /// + public Response CustomersUpdate(Dictionary customer, string by = "externalId", string site = "") + { + if (customer.Count < 1) + { + throw new ArgumentException("Parameter `customer` must contains a data"); + } + + if (!customer.ContainsKey("id") && !customer.ContainsKey("externalId")) + { + throw new ArgumentException("Parameter `customer` must contains an id or externalId"); + } + + CheckIdParameter(by); + + string uid = by == "externalId" ? customer["externalId"].ToString() : customer["id"].ToString(); + + return Request.MakeRequest( + $"/customers/{uid}/edit", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "by", by }, + { "customer", new JavaScriptSerializer().Serialize(customer) } + } + ) + ); + } + + /// + /// Get customer + /// + /// + /// + /// + /// + public Response CustomersGet(string id, string by = "externalId", string site = "") + { + CheckIdParameter(by); + + return Request.MakeRequest( + $"/customers/{id}", + Request.MethodGet, + FillSite( + site, + new Dictionary + { + { "by", by } + } + ) + ); + } + + /// + /// Get customers list + /// + /// + /// + /// + /// + public Response CustomersList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/customers", Request.MethodGet, parameters); + } + + /// + /// Fix external id + /// + /// + /// + public Response CustomersFixExternalIds(Dictionary[] ids) + { + return Request.MakeRequest( + "/customers/fix-external-ids", + Request.MethodPost, + new Dictionary + { + { "customers", new JavaScriptSerializer().Serialize(ids) } + } + ); + } + + /// + /// Upload customers + /// + /// + /// + /// + /// + public Response CustomersUpload(List customers, string site = "") + { + if (customers.Count < 1) + { + throw new ArgumentException("Parameter `customers` must contains a data"); + } + + if (customers.Count > 50) + { + throw new ArgumentException("Parameter `customers` must contain 50 or less records"); + } + + return Request.MakeRequest( + "/customers/upload", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "customers", new JavaScriptSerializer().Serialize(customers) } + } + ) + ); + } + } +} diff --git a/Retailcrm/Versions/V3/Orders.cs b/Retailcrm/Versions/V3/Orders.cs new file mode 100644 index 0000000..8630e73 --- /dev/null +++ b/Retailcrm/Versions/V3/Orders.cs @@ -0,0 +1,256 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Create order + /// + /// + /// + /// + public Response OrdersCreate(Dictionary order, string site = "") + { + if (order.Count < 1) + { + throw new ArgumentException("Parameter `order` must contains a data"); + } + + return Request.MakeRequest( + "/orders/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "order", new JavaScriptSerializer().Serialize(order) } + } + ) + ); + } + + /// + /// Update order + /// + /// + /// + /// + /// + public Response OrdersUpdate(Dictionary order, string by = "externalId", string site = "") + { + if (order.Count < 1) + { + throw new ArgumentException("Parameter `order` must contains a data"); + } + + if (!order.ContainsKey("id") && !order.ContainsKey("externalId")) + { + throw new ArgumentException("Parameter `order` must contains an id or externalId"); + } + + CheckIdParameter(by); + + string uid = by == "externalId" ? order["externalId"].ToString() : order["id"].ToString(); + + return Request.MakeRequest( + $"/orders/{uid}/edit", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "by", by }, + { "order", new JavaScriptSerializer().Serialize(order) } + } + ) + ); + } + + /// + /// Get order + /// + /// + /// + /// + /// + public Response OrdersGet(string id, string by = "externalId", string site = "") + { + CheckIdParameter(by); + + return Request.MakeRequest( + $"/orders/{id}", + Request.MethodGet, + FillSite( + site, + new Dictionary + { + { "by", by } + } + ) + ); + } + + /// + /// + /// + /// + /// + /// + /// + public Response OrdersList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 1) + { + parameters.Add("page", page); + } + + if (limit > 20) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/orders", Request.MethodGet, parameters); + } + + /// + /// Fix external ids + /// + /// + /// + public Response OrdersFixExternalIds(Dictionary[] ids) + { + return Request.MakeRequest( + "/orders/fix-external-ids", + Request.MethodPost, + new Dictionary + { + { "orders", new JavaScriptSerializer().Serialize(ids) } + } + ); + } + + /// + /// Get orders history + /// + /// + /// + /// + /// + /// + /// + public Response OrdersHistory(DateTime? startDate = null, DateTime? endDate = null, int limit = 200, int offset = 0, bool skipMyChanges = true) + { + Dictionary parameters = new Dictionary(); + + if (startDate != null) + { + parameters.Add("startDate", startDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); + } + + if (endDate != null) + { + parameters.Add("endDate", endDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + if (offset > 0) + { + parameters.Add("offset", offset); + } + + parameters.Add("skipMyChanges", skipMyChanges); + + return Request.MakeRequest( + "/orders/history", + Request.MethodGet, + parameters + ); + } + + /// + /// Get orders statuses + /// + /// + /// + /// + public Response OrdersStatuses(List ids, List externalIds = null) + { + Dictionary parameters = new Dictionary(); + + if (ids == null && externalIds == null) + { + throw new ArgumentException("You must set the array of `ids` or `externalIds`."); + } + + if ( + ids != null && externalIds != null && ids.Count + externalIds.Count > 500 || + ids == null && externalIds != null && externalIds.Count > 500 || + ids != null && externalIds == null && ids.Count > 500 + ) + { + throw new ArgumentException("Too many ids or externalIds. Maximum number of elements is 500"); + } + + if (ids != null && ids.Count > 0) + { + parameters.Add("ids", ids); + } + + if (externalIds != null && externalIds.Count > 0) + { + parameters.Add("externalIds", externalIds); + } + + return Request.MakeRequest( + "/orders/statuses", + Request.MethodGet, + parameters + ); + } + + /// + /// Orders upload + /// + /// + /// + /// + public Response OrdersUpload(List orders, string site = "") + { + if (orders.Count < 1) + { + throw new ArgumentException("Parameter `orders` must contains a data"); + } + + if (orders.Count > 50) + { + throw new ArgumentException("Parameter `orders` must contain 50 or less records"); + } + + return Request.MakeRequest( + "/orders/upload", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "orders", new JavaScriptSerializer().Serialize(orders) } + } + ) + ); + } + } +} diff --git a/Retailcrm/Versions/V3/Packs.cs b/Retailcrm/Versions/V3/Packs.cs new file mode 100644 index 0000000..44ecb80 --- /dev/null +++ b/Retailcrm/Versions/V3/Packs.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Get packs list + /// + /// + /// + /// + /// + public Response PacksList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/orders/packs", Request.MethodGet, parameters); + } + + /// + /// Create pack + /// + /// + /// + public Response PacksCreate(Dictionary pack) + { + if (pack.Count < 1) + { + throw new ArgumentException("Parameter `pack` must contains a data"); + } + + return Request.MakeRequest( + "/orders/packs/create", + Request.MethodPost, + new Dictionary + { + { "pack", new JavaScriptSerializer().Serialize(pack) } + } + ); + } + + /// + /// Update pack data + /// + /// + /// + public Response PacksUpdate(Dictionary pack) + { + if (pack.Count < 1) + { + throw new ArgumentException("Parameter `pack` must contains a data"); + } + + if (!pack.ContainsKey("id")) + { + throw new ArgumentException("Parameter `pack` must contains an id"); + } + + return Request.MakeRequest( + $"/orders/packs/{pack["id"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "pack", new JavaScriptSerializer().Serialize(pack) } + } + ); + } + + /// + /// Delete pack + /// + /// + /// + public Response PacksDelete(string id) + { + return Request.MakeRequest( + $"/orders/packs/{id}/delete", + Request.MethodPost + ); + } + + /// + /// Get pack by id + /// + /// + /// + public Response PacksGet(string id) + { + return Request.MakeRequest( + $"/orders/packs/{id}", + Request.MethodGet + ); + } + + /// + /// Get packs history + /// + /// + /// + /// + /// + public Response PacksHistory(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 1) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/orders/packs/history", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V3/References.cs b/Retailcrm/Versions/V3/References.cs new file mode 100644 index 0000000..8aa8b71 --- /dev/null +++ b/Retailcrm/Versions/V3/References.cs @@ -0,0 +1,461 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Countries + /// + /// + public Response Countries() + { + return Request.MakeRequest( + "/reference/countries", + Request.MethodGet + ); + } + + /// + /// Delivery services + /// + /// + public Response DeliveryServices() + { + return Request.MakeRequest( + "/reference/delivery-services", + Request.MethodGet + ); + } + + /// + /// Delivery types + /// + /// + public Response DeliveryTypes() + { + return Request.MakeRequest( + "/reference/delivery-types", + Request.MethodGet + ); + } + + /// + /// Order methods + /// + /// + public Response OrderMethods() + { + return Request.MakeRequest( + "/reference/order-methods", + Request.MethodGet + ); + } + + /// + /// Order types + /// + /// + public Response OrderTypes() + { + return Request.MakeRequest( + "/reference/order-types", + Request.MethodGet + ); + } + + /// + /// Payment statuses + /// + /// + public Response PaymentStatuses() + { + return Request.MakeRequest( + "/reference/payment-statuses", + Request.MethodGet + ); + } + + /// + /// Payment types + /// + /// + public Response PaymentTypes() + { + return Request.MakeRequest( + "/reference/payment-types", + Request.MethodGet + ); + } + + /// + /// Product statuses + /// + /// + public Response ProductStatuses() + { + return Request.MakeRequest( + "/reference/product-statuses", + Request.MethodGet + ); + } + + /// + /// Sites + /// + /// + public Response Sites() + { + return Request.MakeRequest( + "/reference/sites", + Request.MethodGet + ); + } + + /// + /// Statuses groups + /// + /// + public Response StatusGroups() + { + return Request.MakeRequest( + "/reference/status-groups", + Request.MethodGet + ); + } + + /// + /// Statuses + /// + /// + public Response Statuses() + { + return Request.MakeRequest( + "/reference/statuses", + Request.MethodGet + ); + } + + /// + /// Stores + /// + /// + public Response Stores() + { + return Request.MakeRequest( + "/reference/stores", + Request.MethodGet + ); + } + + /// + /// Delivery services edit + /// + /// + /// + public Response DeliveryServicesEdit(Dictionary service) + { + if (!service.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!service.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/delivery-services/{service["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "deliveryService", new JavaScriptSerializer().Serialize(service) } + } + ); + } + + /// + /// Delivery types edit + /// + /// + /// + public Response DeliveryTypesEdit(Dictionary type) + { + if (!type.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!type.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + if (!type.ContainsKey("defaultCost")) + { + throw new ArgumentException("Parameter `defaultCost` is missing"); + } + + if (!type.ContainsKey("defaultNetCost")) + { + throw new ArgumentException("Parameter `defaultCost` is missing"); + } + + return Request.MakeRequest( + $"/reference/delivery-types/{type["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "deliveryType", new JavaScriptSerializer().Serialize(type) } + } + ); + } + + /// + /// Orders methods edit + /// + /// + /// + public Response OrderMethodsEdit(Dictionary method) + { + if (!method.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!method.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/order-methods/{method["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "orderMethod", new JavaScriptSerializer().Serialize(method) } + } + ); + } + + /// + /// Order types edit + /// + /// + /// + public Response OrderTypesEdit(Dictionary type) + { + if (!type.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!type.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/order-types/{type["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "orderType", new JavaScriptSerializer().Serialize(type) } + } + ); + } + + /// + /// Payment statuses edit + /// + /// + /// + public Response PaymentStatusesEdit(Dictionary status) + { + if (!status.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!status.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/payment-statuses/{status["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "paymentStatus", new JavaScriptSerializer().Serialize(status) } + } + ); + } + + /// + /// Payment types edit + /// + /// + /// + public Response PaymentTypesEdit(Dictionary type) + { + if (!type.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!type.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/payment-types/{type["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "paymentType", new JavaScriptSerializer().Serialize(type) } + } + ); + } + + /// + /// Product statuses edit + /// + /// + /// + public Response ProductStatusesEdit(Dictionary status) + { + if (!status.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!status.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/product-statuses/{status["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "productStatus", new JavaScriptSerializer().Serialize(status) } + } + ); + } + + /// + /// Sites edit + /// + /// + /// + public Response SitesEdit(Dictionary site) + { + if (!site.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!site.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + if (!site.ContainsKey("url")) + { + throw new ArgumentException("Parameter `url` is missing"); + } + + return Request.MakeRequest( + $"/reference/sites/{site["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "site", new JavaScriptSerializer().Serialize(site) } + } + ); + } + + /// + /// Statuses edit + /// + /// + /// + public Response StatusesEdit(Dictionary status) + { + if (!status.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!status.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + if (!status.ContainsKey("ordering")) + { + throw new ArgumentException("Parameter `ordering` is missing"); + } + + if (!status.ContainsKey("group")) + { + throw new ArgumentException("Parameter `group` is missing"); + } + + return Request.MakeRequest( + $"/reference/statuses/{status["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "status", new JavaScriptSerializer().Serialize(status) } + } + ); + } + + /// + /// Stores edit + /// + /// + /// + public Response StoresEdit(Dictionary store) + { + if (!store.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!store.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + List types = new List + { + "store-type-online", + "store-type-retail", + "store-type-supplier", + "store-type-warehouse" + }; + + if (store.ContainsKey("type") && !types.Contains(store["type"].ToString())) + { + throw new ArgumentException("Parameter `type` should be equal to one of `store-type-online|store-type-retail|store-type-supplier|store-type-warehouse`"); + } + + return Request.MakeRequest( + $"/reference/stores/{store["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "store", new JavaScriptSerializer().Serialize(store) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V3/Statistic.cs b/Retailcrm/Versions/V3/Statistic.cs new file mode 100644 index 0000000..fbb93f2 --- /dev/null +++ b/Retailcrm/Versions/V3/Statistic.cs @@ -0,0 +1,17 @@ +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Update statistic + /// + /// + public Response StatisticUpdate() + { + return Request.MakeRequest( + "/statistic/update", + Request.MethodGet + ); + } + } +} diff --git a/Retailcrm/Versions/V3/Stores.cs b/Retailcrm/Versions/V3/Stores.cs new file mode 100644 index 0000000..536ccc9 --- /dev/null +++ b/Retailcrm/Versions/V3/Stores.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Get inventories + /// + /// + /// + /// + /// + public Response StoreInventoriesGet(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/store/inventories", Request.MethodGet, parameters); + } + + /// + /// Upload inventories + /// + /// + /// + /// + public Response StoreInventoriesUpload(List offers, string site = "") + { + if (offers.Count< 1) + { + throw new ArgumentException("Parameter `offers` must contains a data"); + } + + if (offers.Count > 250) + { + throw new ArgumentException("Parameter `offers` must contain 250 or less records"); + } + + return Request.MakeRequest( + "/store/inventories/upload", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "offers", new JavaScriptSerializer().Serialize(offers) } + } + ) + ); + } + } +} diff --git a/Retailcrm/Versions/V3/Telephony.cs b/Retailcrm/Versions/V3/Telephony.cs new file mode 100644 index 0000000..330ad95 --- /dev/null +++ b/Retailcrm/Versions/V3/Telephony.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V3 +{ + public partial class Client + { + /// + /// Get manager + /// + /// + /// + /// + public Response TelephonyManagerGet(string phone, string details = "1") + { + Dictionary parameters = new Dictionary(); + + if (string.IsNullOrEmpty(phone)) + { + throw new ArgumentException("Parameter `phone` must contains a data"); + } + + parameters.Add("details", details); + parameters.Add("phone", phone); + + return Request.MakeRequest("/telephony/manager", Request.MethodGet, parameters); + } + + /// + /// Send call event + /// + /// + /// + /// + /// + /// + public Response TelephonyCallEvent(string phone, string type, string status, string code) + { + if (string.IsNullOrEmpty(phone)) + { + throw new ArgumentException("Parameter `phone` must contains a data"); + } + + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `phone` must contains a data"); + } + + List statuses = new List { "answered", "busy", "cancel", "failed", "no answered" }; + List types = new List { "hangup", "in", "out" }; + + if (!statuses.Contains(status)) + { + throw new ArgumentException("Parameter `status` must be equal one of `answered|busy|cancel|failed|no answered`"); + } + + if (!types.Contains(type)) + { + throw new ArgumentException("Parameter `type` must be equal one of `hangup|in|out`"); + } + + return Request.MakeRequest( + "/telephony/call/event", + Request.MethodPost, + new Dictionary + { + { "phone", phone }, + { "type", type }, + { "hangupStatus", status}, + { "code", code } + } + ); + } + + /// + /// Upload calls + /// + /// + /// + public Response TelephonyCallsUpload(List calls) + { + if (calls.Count < 1) + { + throw new ArgumentException("Parameter `calls` must contains a data"); + } + + if (calls.Count > 50) + { + throw new ArgumentException("Parameter `calls` must contain 50 or less records"); + } + + return Request.MakeRequest( + "/telephony/calls/upload", + Request.MethodPost, + new Dictionary + { + { "calls", new JavaScriptSerializer().Serialize(calls) } + } + ); + } + + /// + /// Edit telephony settings + /// + /// + /// + /// + /// + /// + /// + /// + public Response TelephonySettingsEdit(string code, string clientId, string url, string name, string logo, string active = "true") + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentException("Parameter `name` must contains a data"); + } + + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `phone` must contains a data"); + } + + if (string.IsNullOrEmpty(url)) + { + throw new ArgumentException("Parameter `url` must contains a data"); + } + + if (string.IsNullOrEmpty(clientId)) + { + throw new ArgumentException("Parameter `clientId` must contains a data"); + } + + return Request.MakeRequest( + $"/telephony/setting/{code}", + Request.MethodPost, + new Dictionary + { + { "code", code }, + { "name", name }, + { "clientId", clientId}, + { "makeCallUrl", url }, + { "image", logo }, + { "active", active } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Client.cs b/Retailcrm/Versions/V4/Client.cs new file mode 100644 index 0000000..706b265 --- /dev/null +++ b/Retailcrm/Versions/V4/Client.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V4 +{ + using ParentClass = V3.Client; + + /// + /// V4 Client + /// + public partial class Client : ParentClass + { + /// + /// V4 Client Constructor + /// + /// + /// + /// + public Client(string url, string key, string site = "") : base(url, key, site) + { + if ("/" != url.Substring(url.Length - 1, 1)) + { + url += "/"; + } + + url += "api/v4"; + + Request = new Request(url, new Dictionary { { "apiKey", key } }); + SiteCode = site; + } + } +} diff --git a/Retailcrm/Versions/V4/Customers.cs b/Retailcrm/Versions/V4/Customers.cs new file mode 100644 index 0000000..ce63f78 --- /dev/null +++ b/Retailcrm/Versions/V4/Customers.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Customers history + /// + /// + /// + /// + /// + public Response CustomersHistory(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/customers/history", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V4/Delivery.cs b/Retailcrm/Versions/V4/Delivery.cs new file mode 100644 index 0000000..c33774b --- /dev/null +++ b/Retailcrm/Versions/V4/Delivery.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Get delivery settings + /// + /// + /// + public Response DeliverySettingGet(string code) + { + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `code` is mandatory"); + } + + return Request.MakeRequest( + $"/delivery/generic/setting/{code}", + Request.MethodGet + ); + } + + /// + /// Edit delivery settings + /// + /// + /// + public Response DeliverySettingsEdit(Dictionary configuration) + { + if (configuration.Count < 1) + { + throw new ArgumentException("Parameter `configuration` must contain data"); + } + + if (!configuration.ContainsKey("clientId")) + { + throw new ArgumentException("Parameter `configuration` should contain `clientId`"); + } + + if (!configuration.ContainsKey("baseUrl")) + { + throw new ArgumentException("Parameter `configuration` should contain `baseUrl`"); + } + + if (!configuration.ContainsKey("code")) + { + throw new ArgumentException("Parameter `configuration` should contain `code`"); + } + + if (!configuration.ContainsKey("name")) + { + throw new ArgumentException("Parameter `configuration` should contain `name`"); + } + + return Request.MakeRequest( + $"/delivery/generic/setting/{configuration["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "configuration", new JavaScriptSerializer().Serialize(configuration) } + } + ); + } + + /// + /// Update delivery tracking + /// + /// + /// + /// + public Response DeliveryTracking(string code, List statusUpdate) + { + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `code` is mandatory"); + } + + if (statusUpdate.Count < 1) + { + throw new ArgumentException("Parameter `statusUpdate` must contain data"); + } + + return Request.MakeRequest( + $"delivery/generic/{code}/edit", + Request.MethodPost, + new Dictionary + { + { "statusUpdate", new JavaScriptSerializer().Serialize(statusUpdate) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Marketplace.cs b/Retailcrm/Versions/V4/Marketplace.cs new file mode 100644 index 0000000..9e13f7c --- /dev/null +++ b/Retailcrm/Versions/V4/Marketplace.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Edit marketplace module settings + /// + /// + /// + public Response MarketplaceSettingsEdit(Dictionary configuration) + { + if (configuration.Count < 1) + { + throw new ArgumentException("Parameter `configuration` must contain data"); + } + + if (!configuration.ContainsKey("code")) + { + throw new ArgumentException("Parameter `configuration` should contain `code`"); + } + + if (!configuration.ContainsKey("name")) + { + throw new ArgumentException("Parameter `configuration` should contain `name`"); + } + + return Request.MakeRequest( + $"/marketplace/external/setting/{configuration["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "configuration", new JavaScriptSerializer().Serialize(configuration) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Orders.cs b/Retailcrm/Versions/V4/Orders.cs new file mode 100644 index 0000000..36008fd --- /dev/null +++ b/Retailcrm/Versions/V4/Orders.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Get orders history + /// + /// + /// + /// + /// + public Response OrdersHistory(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/orders/history", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V4/References.cs b/Retailcrm/Versions/V4/References.cs new file mode 100644 index 0000000..f9a9a26 --- /dev/null +++ b/Retailcrm/Versions/V4/References.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Price types + /// + /// + public Response PriceTypes() + { + return Request.MakeRequest( + "/reference/price-types", + Request.MethodGet + ); + } + + /// + /// Price type edit + /// + /// + /// + public Response PriceTypesEdit(Dictionary type) + { + if (!type.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!type.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + return Request.MakeRequest( + $"/reference/price-types/{type["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "priceType", new JavaScriptSerializer().Serialize(type) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Stores.cs b/Retailcrm/Versions/V4/Stores.cs new file mode 100644 index 0000000..80069f6 --- /dev/null +++ b/Retailcrm/Versions/V4/Stores.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Get products + /// + /// + /// + /// + /// + public Response StoreProducts(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/store/products", Request.MethodGet, parameters); + } + + /// + /// Upload prices + /// + /// + /// + public Response StorePricesUpload(List prices) + { + if (prices.Count< 1) + { + throw new ArgumentException("Parameter `prices` must contains a data"); + } + + if (prices.Count > 250) + { + throw new ArgumentException("Parameter `prices` must contain 250 or less records"); + } + + return Request.MakeRequest( + "/store/prices/upload", + Request.MethodPost, + new Dictionary + { + { "prices", new JavaScriptSerializer().Serialize(prices) } + } + ); + } + + /// + /// Get store settings + /// + /// + /// + public Response StoreSettingGet(string code) + { + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `code` is mandatory"); + } + + return Request.MakeRequest( + $"/store/setting/{code}", + Request.MethodGet + ); + } + + /// + /// Edit store settings + /// + /// + /// + public Response StoreSettingsEdit(Dictionary configuration) + { + if (configuration.Count < 1) + { + throw new ArgumentException("Parameter `configuration` must contain data"); + } + + if (!configuration.ContainsKey("clientId")) + { + throw new ArgumentException("Parameter `configuration` should contain `clientId`"); + } + + if (!configuration.ContainsKey("baseUrl")) + { + throw new ArgumentException("Parameter `configuration` should contain `baseUrl`"); + } + + if (!configuration.ContainsKey("code")) + { + throw new ArgumentException("Parameter `configuration` should contain `code`"); + } + + if (!configuration.ContainsKey("name")) + { + throw new ArgumentException("Parameter `configuration` should contain `name`"); + } + + return Request.MakeRequest( + $"/store/setting/{configuration["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "configuration", new JavaScriptSerializer().Serialize(configuration) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Telephony.cs b/Retailcrm/Versions/V4/Telephony.cs new file mode 100644 index 0000000..25f176f --- /dev/null +++ b/Retailcrm/Versions/V4/Telephony.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Send call event + /// + /// + /// + public Response TelephonyCallEvent(Dictionary ievent) + { + if (ievent.Count < 1) + { + throw new ArgumentException("Parameter `event` must contain data"); + } + + if (!ievent.ContainsKey("phone")) + { + throw new ArgumentException("Parameter `phone` must contains a data"); + } + + if (!ievent.ContainsKey("type")) + { + throw new ArgumentException("Parameter `type` must contains a data"); + } + + if (!ievent.ContainsKey("hangupStatus")) + { + throw new ArgumentException("Parameter `hangupStatus` must contains a data"); + } + + List statuses = new List { "answered", "busy", "cancel", "failed", "no answered" }; + List types = new List { "hangup", "in", "out" }; + + if (!statuses.Contains(ievent["hangupStatus"].ToString())) + { + throw new ArgumentException("Parameter `status` must be equal one of `answered|busy|cancel|failed|no answered`"); + } + + if (!types.Contains(ievent["type"].ToString())) + { + throw new ArgumentException("Parameter `type` must be equal one of `hangup|in|out`"); + } + + return Request.MakeRequest( + "/telephony/call/event", + Request.MethodPost, + new Dictionary + { + { "event", new JavaScriptSerializer().Serialize(ievent) } + } + ); + } + + /// + /// Get telephony settings + /// + /// + /// + public Response TelephonySettingsGet(string code) + { + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `code` should contain data"); + } + + return Request.MakeRequest($"/telephony/setting/{code}", Request.MethodGet); + } + + /// + /// Edit telephony settings + /// + /// + /// + public Response TelephonySettingsEdit(Dictionary configuration) + { + if (configuration.Count < 1) + { + throw new ArgumentException("Parameter `configuration` must contain data"); + } + + if (!configuration.ContainsKey("code")) + { + throw new ArgumentException("Parameter `configuration` should contain `code`"); + } + + if (!configuration.ContainsKey("name")) + { + throw new ArgumentException("Parameter `configuration` should contain `name`"); + } + + if (!configuration.ContainsKey("makeCallUrl")) + { + throw new ArgumentException("Parameter `configuration` should contain `makeCallUrl`"); + } + + if (!configuration.ContainsKey("clientId")) + { + throw new ArgumentException("Parameter `configuration` should contain `clientId`"); + } + + return Request.MakeRequest( + $"/telephony/setting/{configuration["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "configuration", new JavaScriptSerializer().Serialize(configuration) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V4/Users.cs b/Retailcrm/Versions/V4/Users.cs new file mode 100644 index 0000000..82b778e --- /dev/null +++ b/Retailcrm/Versions/V4/Users.cs @@ -0,0 +1,69 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V4 +{ + public partial class Client + { + /// + /// Get users + /// + /// + /// + /// + /// + public Response Users(Dictionary filter = null, int page = 0, int limit = 0) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/users", Request.MethodGet, parameters); + } + + /// + /// Get users groups + /// + /// + /// + /// + public Response UsersGroups(int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/user-groups", Request.MethodGet, parameters); + } + + /// + /// Get user + /// + /// + /// + public Response User(int id) + { + return Request.MakeRequest($"/users/{id}", Request.MethodGet); + } + } +} diff --git a/Retailcrm/Versions/V5/Client.cs b/Retailcrm/Versions/V5/Client.cs new file mode 100644 index 0000000..f047b01 --- /dev/null +++ b/Retailcrm/Versions/V5/Client.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + using ParentClass = V4.Client; + + /// + /// V5 Client + /// + public partial class Client : ParentClass + { + /// + /// V5 Client Constructor + /// + /// + /// + /// + public Client(string url, string key, string site = "") : base(url, key, site) + { + if ("/" != url.Substring(url.Length - 1, 1)) + { + url += "/"; + } + + url += "api/v5"; + + Request = new Request(url, new Dictionary { { "apiKey", key } }); + SiteCode = site; + } + } +} diff --git a/Retailcrm/Versions/V5/Costs.cs b/Retailcrm/Versions/V5/Costs.cs new file mode 100644 index 0000000..55109d4 --- /dev/null +++ b/Retailcrm/Versions/V5/Costs.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get costs + /// + /// + /// + /// + /// + public Response CostsList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/costs", Request.MethodGet, parameters); + } + + /// + /// Create cost + /// + /// + /// + /// + public Response CostsCreate(Dictionary cost, string site = "") + { + if (cost.Count < 1) + { + throw new ArgumentException("Parameter `cost` must contains a data"); + } + + if (!cost.ContainsKey("costItem")) + { + throw new ArgumentException("Parameter `costItem` must be set"); + } + + if (!cost.ContainsKey("summ")) + { + throw new ArgumentException("Parameter `summ` must be set"); + } + + if (!cost.ContainsKey("dateFrom")) + { + throw new ArgumentException("`dateFrom`: Time interval lower bound must not be blank"); + } + + if (!cost.ContainsKey("dateTo")) + { + throw new ArgumentException("`dateTo`: Time interval upper bound must not be blank"); + } + + return Request.MakeRequest( + "/costs/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "cost", new JavaScriptSerializer().Serialize(cost) } + } + ) + ); + } + + /// + /// Delete cost + /// + /// + /// + public Response CostsDelete(List ids) + { + if (ids.Count < 1) + { + throw new ArgumentException("Parameter `ids` must contains a data"); + } + + return Request.MakeRequest( + "/costs/delete", + Request.MethodPost, + new Dictionary + { + { "ids", new JavaScriptSerializer().Serialize(ids) } + } + ); + } + + /// + /// Upload costs + /// + /// + /// + public Response CostsUpload(List costs) + { + if (costs.Count < 1) + { + throw new ArgumentException("Parameter `costs` must contains a data"); + } + + if (costs.Count > 50) + { + throw new ArgumentException("Parameter `costs` must contain 50 or less records"); + } + + return Request.MakeRequest( + "/costs/upload", + Request.MethodPost, + new Dictionary + { + { "costs", new JavaScriptSerializer().Serialize(costs) } + } + ); + } + + /// + /// Get cost + /// + /// + /// + public Response CostsGet(int id) + { + return Request.MakeRequest($"/costs/{id}", Request.MethodGet); + } + + /// + /// Batch delete + /// + /// + /// + public Response CostsDelete(string id) + { + return Request.MakeRequest( + $"/costs/{id}/delete", + Request.MethodPost + ); + } + + /// + /// Update cost + /// + /// + /// + /// + public Response CostsUpdate(Dictionary cost, string site = "") + { + if (cost.Count < 1) + { + throw new ArgumentException("Parameter `cost` must contains a data"); + } + + if (!cost.ContainsKey("id")) + { + throw new ArgumentException("Parameter `cost` must contains an id"); + } + + return Request.MakeRequest( + $"/costs/{cost["id"].ToString()}/edit", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "cost", new JavaScriptSerializer().Serialize(cost) } + } + ) + ); + } + } +} diff --git a/Retailcrm/Versions/V5/CustomFields.cs b/Retailcrm/Versions/V5/CustomFields.cs new file mode 100644 index 0000000..f6733a5 --- /dev/null +++ b/Retailcrm/Versions/V5/CustomFields.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get custom fields + /// + /// + /// + /// + /// + public Response CustomFieldsList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/custom-fields", Request.MethodGet, parameters); + } + + /// + /// Create custom field + /// + /// + /// + public Response CustomFieldsCreate(Dictionary customField) + { + List types = new List + { + "boolean", "date", "dictionary", "email", "integer", "numeric", "string", "text" + }; + + if (customField.Count < 1) + { + throw new ArgumentException("Parameter `customField` must contains a data"); + } + + if (!customField.ContainsKey("code")) + { + throw new ArgumentException("Parameter `customField` should contain `code`"); + } + + if (!customField.ContainsKey("name")) + { + throw new ArgumentException("Parameter `customField` should contain `name`"); + } + + if (!customField.ContainsKey("type")) + { + throw new ArgumentException("Parameter `customField` should contain `type`"); + } + + if (!customField.ContainsKey("entity")) + { + throw new ArgumentException("Parameter `customField` should contain `entity`"); + } + + if (!types.Contains(customField["type"].ToString())) + { + throw new ArgumentException( + "Parameter `customField` should contain `type` & value of type should be on of `boolean|date|dictionary|email|integer|numeric|string|text`" + ); + } + + return Request.MakeRequest( + $"/custom-fields/{customField["entity"].ToString()}/create", + Request.MethodPost, + new Dictionary + { + { "customField", new JavaScriptSerializer().Serialize(customField) } + } + ); + } + + /// + /// Get custom field + /// + /// + /// + /// + public Response CustomFieldsGet(string code, string entity) + { + return Request.MakeRequest( + $"/custom-fields/{entity}/{code}", + Request.MethodGet + ); + } + + /// + /// Update custom field + /// + /// + /// + public Response CustomFieldsUpdate(Dictionary customField) + { + if (customField.Count < 1) + { + throw new ArgumentException("Parameter `customField` must contains a data"); + } + + if (!customField.ContainsKey("code")) + { + throw new ArgumentException("Parameter `customField` should contain `code`"); + } + + if (!customField.ContainsKey("name")) + { + throw new ArgumentException("Parameter `customField` should contain `name`"); + } + + return Request.MakeRequest( + $"/custom-fields/{customField["entity"].ToString()}/{customField["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "customField", new JavaScriptSerializer().Serialize(customField) } + } + ); + } + + /// + /// Get custom dictionaries + /// + /// + /// + /// + /// + public Response CustomDictionaryList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/custom-fields/dictionaries", Request.MethodGet, parameters); + } + + /// + /// Create custom dictionary + /// + /// + /// + public Response CustomDictionaryCreate(Dictionary customDictionary) + { + if (customDictionary.Count < 1) + { + throw new ArgumentException("Parameter `customDictionary` must contains a data"); + } + + if (!customDictionary.ContainsKey("code")) + { + throw new ArgumentException("Parameter `customDictionary` should contain `code`"); + } + + if (!customDictionary.ContainsKey("name")) + { + throw new ArgumentException("Parameter `customDictionary` should contain `name`"); + } + + return Request.MakeRequest( + "/custom-fields/dictionaries/create", + Request.MethodPost, + new Dictionary + { + { "customDictionary", new JavaScriptSerializer().Serialize(customDictionary) } + } + ); + } + + /// + /// Get custom dictionary + /// + /// + /// + public Response CustomDictionaryGet(string code) + { + return Request.MakeRequest( + $"/custom-fields/dictionaries/{code}", + Request.MethodGet + ); + } + + /// + /// Update custom dictionary + /// + /// + /// + public Response CustomDictionaryUpdate(Dictionary customDictionary) + { + if (customDictionary.Count < 1) + { + throw new ArgumentException("Parameter `customDictionary` must contains a data"); + } + + if (!customDictionary.ContainsKey("code")) + { + throw new ArgumentException("Parameter `customDictionary` should contain `code`"); + } + + if (!customDictionary.ContainsKey("name")) + { + throw new ArgumentException("Parameter `customDictionary` should contain `name`"); + } + + return Request.MakeRequest( + $"/custom-fields/dictionaries/{customDictionary["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "customDictionary", new JavaScriptSerializer().Serialize(customDictionary) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V5/Delivery.cs b/Retailcrm/Versions/V5/Delivery.cs new file mode 100644 index 0000000..923b90c --- /dev/null +++ b/Retailcrm/Versions/V5/Delivery.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get delivery settings + /// + /// + /// + public new Response DeliverySettingGet(string code) + { + throw new ArgumentException("This method is unavailable in API V5", code); + } + + /// + /// Update delivery settings + /// + /// + /// + public new Response DeliverySettingsEdit(Dictionary configuration) + { + throw new ArgumentException("This method is unavailable in API V5"); + } + } +} diff --git a/Retailcrm/Versions/V5/Integrations.cs b/Retailcrm/Versions/V5/Integrations.cs new file mode 100644 index 0000000..70858a3 --- /dev/null +++ b/Retailcrm/Versions/V5/Integrations.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get integration settings + /// + /// + /// + public Response IntegrationsSettingGet(string code) + { + if (string.IsNullOrEmpty(code)) + { + throw new ArgumentException("Parameter `code` is mandatory"); + } + + return Request.MakeRequest( + $"/integration-modules/{code}", + Request.MethodGet + ); + } + + /// + /// Create/Update integration settings + /// + /// + /// + public Response IntegrationsSettingsEdit(Dictionary integrationModule) + { + if (integrationModule.Count < 1) + { + throw new ArgumentException("Parameter `integrationModule` must contain data"); + } + + if (!integrationModule.ContainsKey("code")) + { + throw new ArgumentException("Parameter `integrationModule` should contain `code`"); + } + + if (!integrationModule.ContainsKey("name")) + { + throw new ArgumentException("Parameter `integrationModule` should contain `name`"); + } + + return Request.MakeRequest( + $"/integration-modules/{integrationModule["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "integrationModule", new JavaScriptSerializer().Serialize(integrationModule) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V5/Notes.cs b/Retailcrm/Versions/V5/Notes.cs new file mode 100644 index 0000000..d9e8ed1 --- /dev/null +++ b/Retailcrm/Versions/V5/Notes.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Create note + /// + /// + /// + /// + public Response NotesCreate(Dictionary note, string site = "") + { + if (note.Count < 1) + { + throw new ArgumentException("Parameter `note` must contains a data"); + } + + return Request.MakeRequest( + "/customers/notes/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "note", new JavaScriptSerializer().Serialize(note) } + } + ) + ); + } + + /// + /// Delete note + /// + /// + /// + public Response NotesDelete(string id) + { + return Request.MakeRequest( + $"/customers/notes/{id}/delete", + Request.MethodPost + ); + } + + /// + /// Get notes list + /// + /// + /// + /// + /// + public Response NotesList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/customers/notes", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V5/Orders.cs b/Retailcrm/Versions/V5/Orders.cs new file mode 100644 index 0000000..0b1e3b9 --- /dev/null +++ b/Retailcrm/Versions/V5/Orders.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Combine orders + /// + /// + /// + /// + /// + public Response OrdersCombine(Dictionary order, Dictionary resultOrder, string technique = "ours") + { + if (order.Count <= 0) + { + throw new ArgumentException("Parameter `order` must contains a data"); + } + + if (!order.ContainsKey("id")) + { + throw new ArgumentException("Parameter `order` must contains `id` key"); + } + + if (resultOrder.Count <= 0) + { + throw new ArgumentException("Parameter `resultOrder` must contains a data"); + } + + if (!resultOrder.ContainsKey("id")) + { + throw new ArgumentException("Parameter `resultOrder` must contains `id` key"); + } + + return Request.MakeRequest( + "/orders/combine", + Request.MethodPost, + new Dictionary + { + { "technique", technique }, + { "order", new JavaScriptSerializer().Serialize(order) }, + { "resultOrder", new JavaScriptSerializer().Serialize(resultOrder) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V5/Payments.cs b/Retailcrm/Versions/V5/Payments.cs new file mode 100644 index 0000000..39e920b --- /dev/null +++ b/Retailcrm/Versions/V5/Payments.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Create payment + /// + /// + /// + /// + public Response PaymentsCreate(Dictionary payment, string site = "") + { + if (payment.Count < 1) + { + throw new ArgumentException("Parameter `payment` must contains a data"); + } + + if (!payment.ContainsKey("type")) + { + throw new ArgumentException("Parameter `type` must be set"); + } + + if (!payment.ContainsKey("order")) + { + throw new ArgumentException("Parameter `order` must be set"); + } + + return Request.MakeRequest( + "/orders/payments/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "payment", new JavaScriptSerializer().Serialize(payment) } + } + ) + ); + } + + /// + /// Update payment + /// + /// + /// + /// + /// + public Response PaymentsUpdate(Dictionary payment, string by = "id", string site = "") + { + if (payment.Count < 1) + { + throw new ArgumentException("Parameter `payment` must contains a data"); + } + + if (!payment.ContainsKey("id") && !payment.ContainsKey("externalId")) + { + throw new ArgumentException("Parameter `payment` must contains an id or externalId"); + } + + CheckIdParameter(by); + + string uid = by == "externalId" ? payment["externalId"].ToString() : payment["id"].ToString(); + + return Request.MakeRequest( + $"/orders/payments/{uid}/edit", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "by", by }, + { "payment", new JavaScriptSerializer().Serialize(payment) } + } + ) + ); + } + + /// + /// Delete payment + /// + /// + /// + public Response PaymentsDelete(string id) + { + return Request.MakeRequest( + $"/orders/payments/{id}/delete", + Request.MethodPost + ); + } + } +} diff --git a/Retailcrm/Versions/V5/References.cs b/Retailcrm/Versions/V5/References.cs new file mode 100644 index 0000000..2a724cf --- /dev/null +++ b/Retailcrm/Versions/V5/References.cs @@ -0,0 +1,157 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Costs groups + /// + /// + public Response CostGroups() + { + return Request.MakeRequest( + "/reference/cost-groups", + Request.MethodGet + ); + } + + /// + /// Costs + /// + /// + public Response CostItems() + { + return Request.MakeRequest( + "/reference/cost-items", + Request.MethodGet + ); + } + + /// + /// Legal entities + /// + /// + public Response LegalEntities() + { + return Request.MakeRequest( + "/reference/legal-entities", + Request.MethodGet + ); + } + + /// + /// Cost group edit + /// + /// + /// + public Response CostGroupsEdit(Dictionary group) + { + if (!group.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!group.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + if (!group.ContainsKey("color")) + { + throw new ArgumentException("Parameter `color` is missing"); + } + + return Request.MakeRequest( + $"/reference/cost-groups/{group["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "costGroup", new JavaScriptSerializer().Serialize(group) } + } + ); + } + + /// + /// Cost items edit + /// + /// + /// + public Response CostItemsEdit(Dictionary item) + { + if (!item.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!item.ContainsKey("name")) + { + throw new ArgumentException("Parameter `name` is missing"); + } + + if (!item.ContainsKey("group")) + { + throw new ArgumentException("Parameter `group` is missing"); + } + + List types = new List + { + "const", + "var" + }; + + if (item.ContainsKey("type") && !types.Contains(item["type"].ToString())) + { + throw new ArgumentException("Parameter `type` should be one of `const|var`"); + } + + return Request.MakeRequest( + $"/reference/cost-items/{item["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "costItem", new JavaScriptSerializer().Serialize(item) } + } + ); + } + + /// + /// Legal entities edit + /// + /// + /// + public Response LegalEntitiesEdit(Dictionary entity) + { + if (!entity.ContainsKey("code")) + { + throw new ArgumentException("Parameter `code` is missing"); + } + + if (!entity.ContainsKey("legalName")) + { + throw new ArgumentException("Parameter `legalName` is missing"); + } + + if (!entity.ContainsKey("countryIso")) + { + throw new ArgumentException("Parameter `countryIso` is missing"); + } + + if (!entity.ContainsKey("contragentType")) + { + throw new ArgumentException("Parameter `contragentType` is missing"); + } + + return Request.MakeRequest( + $"/reference/legal-entities/{entity["code"].ToString()}/edit", + Request.MethodPost, + new Dictionary + { + { "legalEntity", new JavaScriptSerializer().Serialize(entity) } + } + ); + } + } +} diff --git a/Retailcrm/Versions/V5/Segments.cs b/Retailcrm/Versions/V5/Segments.cs new file mode 100644 index 0000000..89a5b05 --- /dev/null +++ b/Retailcrm/Versions/V5/Segments.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get segments + /// + /// + /// + /// + /// + public Response Segments(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/segments", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V5/Stores.cs b/Retailcrm/Versions/V5/Stores.cs new file mode 100644 index 0000000..cebc55d --- /dev/null +++ b/Retailcrm/Versions/V5/Stores.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get external store settings + /// + /// + /// + public new Response StoreSettingGet(string code) + { + throw new ArgumentException("This method is unavailable in API V5", code); + } + + /// + /// Edit external store settings + /// + /// + /// + public new Response StoreSettingsEdit(Dictionary configuration) + { + throw new ArgumentException("This method is unavailable in API V5"); + } + + /// + /// Get products groups + /// + /// + /// + /// + /// + public Response StoreProductsGroups(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/store/products-groups", Request.MethodGet, parameters); + } + + /// + /// Get products properties + /// + /// + /// + /// + /// + public Response StoreProductsProperties(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/store/products/properties", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V5/Tasks.cs b/Retailcrm/Versions/V5/Tasks.cs new file mode 100644 index 0000000..44466a5 --- /dev/null +++ b/Retailcrm/Versions/V5/Tasks.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Create a task + /// + /// + /// + /// + public Response TasksCreate(Dictionary task, string site = "") + { + if (task.Count < 1) + { + throw new ArgumentException("Parameter `task` must contains a data"); + } + + return Request.MakeRequest( + "/tasks/create", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "task", new JavaScriptSerializer().Serialize(task) } + } + ) + ); + } + + /// + /// Update a task + /// + /// + /// + /// + public Response TasksUpdate(Dictionary task, string site = "") + { + if (task.Count < 1) + { + throw new ArgumentException("Parameter `task` must contains a data"); + } + + if (!task.ContainsKey("id")) + { + throw new ArgumentException("Parameter `task` must contains an id"); + } + + return Request.MakeRequest( + $"/tasks/{task["id"].ToString()}/edit", + Request.MethodPost, + FillSite( + site, + new Dictionary + { + { "task", new JavaScriptSerializer().Serialize(task) } + } + ) + ); + } + + /// + /// Get task + /// + /// + /// + public Response TasksGet(string id) + { + return Request.MakeRequest( + $"/tasks/{id}", + Request.MethodGet + ); + } + + /// + /// Get tasks list + /// + /// + /// + /// + /// + public Response TasksList(Dictionary filter = null, int page = 1, int limit = 20) + { + Dictionary parameters = new Dictionary(); + + if (filter != null && filter.Count > 0) + { + parameters.Add("filter", filter); + } + + if (page > 0) + { + parameters.Add("page", page); + } + + if (limit > 0) + { + parameters.Add("limit", limit); + } + + return Request.MakeRequest("/tasks", Request.MethodGet, parameters); + } + } +} diff --git a/Retailcrm/Versions/V5/Telephony.cs b/Retailcrm/Versions/V5/Telephony.cs new file mode 100644 index 0000000..90923bb --- /dev/null +++ b/Retailcrm/Versions/V5/Telephony.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Get telephony settings + /// + /// + /// + public new Response TelephonySettingsGet(string code) + { + throw new ArgumentException("This method is unavailable in API V5", code); + } + + /// + /// Edit telephony settings + /// + /// + /// + public new Response TelephonySettingsEdit(Dictionary configuration) + { + throw new ArgumentException("This method is unavailable in API V5", configuration.ToString()); + } + } +} diff --git a/Retailcrm/Versions/V5/Users.cs b/Retailcrm/Versions/V5/Users.cs new file mode 100644 index 0000000..be6f3bb --- /dev/null +++ b/Retailcrm/Versions/V5/Users.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace Retailcrm.Versions.V5 +{ + public partial class Client + { + /// + /// Update user status + /// + /// + /// + /// + public Response UsersStatus(int id, string status) + { + List statuses = new List { "free", "busy", "dinner", "break"}; + + if (!statuses.Contains(status)) + { + throw new ArgumentException("Parameter `status` must be equal one of these values: `free|busy|dinner|break`"); + } + + return Request.MakeRequest( + $"/users/{id}/status", + Request.MethodPost, + new Dictionary + { + { "status", status } + } + ); + } + } +} diff --git a/Retailcrm/packages.config b/Retailcrm/packages.config new file mode 100644 index 0000000..4672169 --- /dev/null +++ b/Retailcrm/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/RetailcrmUnitTest/ApiTest.cs b/RetailcrmUnitTest/ApiTest.cs new file mode 100644 index 0000000..00dc6ef --- /dev/null +++ b/RetailcrmUnitTest/ApiTest.cs @@ -0,0 +1,39 @@ +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; + +namespace RetailcrmUnitTest +{ + [TestClass] + public class ApiTest + { + private readonly Connection _connection; + + public ApiTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _connection = new Connection(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void Versions() + { + Response response = _connection.Versions(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("versions")); + } + + [TestMethod] + public void Credentials() + { + Response response = _connection.Credentials(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("credentials")); + } + } +} diff --git a/RetailcrmUnitTest/App.config.dist b/RetailcrmUnitTest/App.config.dist new file mode 100644 index 0000000..1e318f9 --- /dev/null +++ b/RetailcrmUnitTest/App.config.dist @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/RetailcrmUnitTest/Properties/AssemblyInfo.cs b/RetailcrmUnitTest/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7117b97 --- /dev/null +++ b/RetailcrmUnitTest/Properties/AssemblyInfo.cs @@ -0,0 +1,19 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("RetailcrmUnitTest")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RetailcrmUnitTest")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: ComVisible(false)] + +[assembly: Guid("4069c2bc-c277-48a3-96ae-da5934a75f4d")] + +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/RetailcrmUnitTest/RetailcrmUnitTest.csproj b/RetailcrmUnitTest/RetailcrmUnitTest.csproj new file mode 100644 index 0000000..4e311fc --- /dev/null +++ b/RetailcrmUnitTest/RetailcrmUnitTest.csproj @@ -0,0 +1,106 @@ + + + + + Debug + AnyCPU + {4069C2BC-C277-48A3-96AE-DA5934A75F4D} + Library + Properties + RetailcrmUnitTest + RetailcrmUnitTest + v4.5 + 512 + {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 15.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages + False + UnitTest + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll + + + ..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Designer + + + + + {9c378ef4-9f9b-4214-a9aa-1fc3c44edb41} + Retailcrm + + + + + + + Данный проект ссылается на пакеты NuGet, отсутствующие на этом компьютере. Используйте восстановление пакетов NuGet, чтобы скачать их. Дополнительную информацию см. по адресу: http://go.microsoft.com/fwlink/?LinkID=322105. Отсутствует следующий файл: {0}. + + + + + + \ No newline at end of file diff --git a/RetailcrmUnitTest/V3/ClientTest.cs b/RetailcrmUnitTest/V3/ClientTest.cs new file mode 100644 index 0000000..acbb2b1 --- /dev/null +++ b/RetailcrmUnitTest/V3/ClientTest.cs @@ -0,0 +1,42 @@ +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class ClientTest + { + private readonly Client _client; + + public ClientTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"], appSettings["site"]); + } + + [TestMethod] + public void InitTest() + { + Assert.IsInstanceOfType(_client, typeof(Client)); + + string siteCode = "default"; + + _client.SetSite(siteCode); + + Assert.AreEqual(_client.GetSite(), siteCode); + } + + [TestMethod] + public void StatisticUpdate() + { + Response response = _client.StatisticUpdate(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetStatusCode() == 200); + } + } +} diff --git a/RetailcrmUnitTest/V3/CustomersTest.cs b/RetailcrmUnitTest/V3/CustomersTest.cs new file mode 100644 index 0000000..f2487c1 --- /dev/null +++ b/RetailcrmUnitTest/V3/CustomersTest.cs @@ -0,0 +1,210 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class CustomersTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public CustomersTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void CustomersCreateReadUpdate() + { + Dictionary customer = new Dictionary + { + {"externalId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + {"lastName", "Baggins"}, + {"firstName", "Frodo"}, + {"email", "frodo@example.com"}, + {"phone", "+78888888888"} + }; + + Response createResponse = _client.CustomersCreate(customer); + + Assert.IsTrue(createResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetStatusCode() == 201); + Assert.IsTrue(createResponse.GetResponse().ContainsKey("id")); + + string id = createResponse.GetResponse()["id"].ToString(); + + Response getResponse = _client.CustomersGet(id, "id"); + Assert.IsTrue(getResponse.IsSuccessfull()); + Assert.IsInstanceOfType(getResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetStatusCode() == 201); + Assert.IsTrue(getResponse.GetResponse().ContainsKey("customer")); + + Dictionary update = new Dictionary + { + {"id", id}, + {"email", "frodobaggins@example.com"} + }; + + Response updateResponse = _client.CustomersUpdate(update, "id"); + Assert.IsTrue(updateResponse.IsSuccessfull()); + Assert.IsInstanceOfType(updateResponse, typeof(Response)); + Assert.IsTrue(updateResponse.GetStatusCode() == 200); + } + + [TestMethod] + public void CustomersFixExternalId() + { + long epochTicks = new DateTime(1970, 1, 1).Ticks; + long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond); + + Dictionary customer = new Dictionary + { + {"externalId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Bull"}, + {"firstName", "John"}, + {"email", "bull@example.com"}, + {"phone", "+77777777777"} + }; + + Response createResponse = _client.CustomersCreate(customer); + string id = createResponse.GetResponse()["id"].ToString(); + string externalId = $"{unixTime}ID"; + + Dictionary[] fix = + { + new Dictionary + { + { "id", id }, + { "externalId", externalId } + } + }; + + Assert.IsTrue(createResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetStatusCode() == 201); + Assert.IsTrue(createResponse.GetResponse().ContainsKey("id")); + + Response fixResponse = _client.CustomersFixExternalIds(fix); + Assert.IsTrue(fixResponse.IsSuccessfull()); + Assert.IsInstanceOfType(fixResponse, typeof(Response)); + Assert.IsTrue(fixResponse.GetStatusCode() == 200); + } + + [TestMethod] + public void CustomersList() + { + _client.SetSite(_appSettings["site"]); + + Response response = _client.CustomersList(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("customers")); + + + Dictionary filter = new Dictionary + { + { "dateTo", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + + Response responseFiltered = _client.CustomersList(filter, 2, 100); + + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("customers")); + } + + [TestMethod] + public void CustomersUpload() + { + List customers = new List(); + + for (int i = 0; i < 5; i++) + { + Dictionary customer = new Dictionary + { + { "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, + { "lastName", $"Doe{i}" }, + { "firstName", $"John{i}" }, + { "email", $"john{i}@example.com" }, + { "phone", $"+7999999999{i}" } + }; + + customers.Add(customer); + } + + Response response = _client.CustomersUpload(customers); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("uploadedCustomers")); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains a data")] + public void CustomersCreateArgumentExeption() + { + Dictionary customer = new Dictionary(); + _client.CustomersCreate(customer); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains a data")] + public void CustomersUpdateEmptyCustomerArgumentExeption() + { + Dictionary customer = new Dictionary(); + _client.CustomersUpdate(customer); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `customer` must contains an id or externalId")] + public void CustomersUpdateIdArgumentExeption() + { + Dictionary customer = new Dictionary { { "lastName", "Doe" } }; + _client.CustomersUpdate(customer); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `customers` must contains a data")] + public void CustomersUploadEmptyCustomersArgumentExeption() + { + List customers = new List(); + _client.CustomersUpload(customers); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `customers` must contain 50 or less records")] + public void CustomersUploadLimitArgumentExeption() + { + List customers = new List(); + + for (int i = 0; i < 51; i++) + { + Dictionary customer = new Dictionary + { + { "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, + { "lastName", $"Doe{i}" }, + { "firstName", $"John{i}" }, + { "email", $"john{i}@example.com" }, + { "phone", $"+7999999999{i}" } + }; + + customers.Add(customer); + } + + _client.CustomersUpload(customers); + } + } +} diff --git a/RetailcrmUnitTest/V3/OrdersTest.cs b/RetailcrmUnitTest/V3/OrdersTest.cs new file mode 100644 index 0000000..0da1443 --- /dev/null +++ b/RetailcrmUnitTest/V3/OrdersTest.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class OrdersTest + { + private readonly Client _client; + + public OrdersTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void OrdersCreateReadUpdate() + { + long epochTicks = new DateTime(1970, 1, 1).Ticks; + long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond); + + Dictionary order = new Dictionary + { + {"number", unixTime}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", "john@example.com"}, + {"phone", "+79999999999"} + }; + + + Response createResponse = _client.OrdersCreate(order); + Assert.IsTrue(createResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetResponse().ContainsKey("id")); + + string id = createResponse.GetResponse()["id"].ToString(); + + Response getResponse = _client.OrdersGet(id, "id"); + Assert.IsTrue(getResponse.IsSuccessfull()); + Assert.IsInstanceOfType(getResponse, typeof(Response)); + Assert.IsTrue(getResponse.GetResponse().ContainsKey("order")); + + Dictionary update = new Dictionary + { + {"id", id}, + {"status", "cancel-other"} + }; + + Response updateResponse = _client.OrdersUpdate(update, "id"); + Assert.IsTrue(updateResponse.IsSuccessfull()); + Assert.IsInstanceOfType(updateResponse, typeof(Response)); + Assert.IsTrue(updateResponse.GetStatusCode() == 200); + } + + [TestMethod] + public void OrdersFixExternalId() + { + long epochTicks = new DateTime(1970, 1, 1).Ticks; + long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond); + + Dictionary order = new Dictionary + { + {"number", unixTime}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", "john@example.com"}, + {"phone", "+79999999999"} + }; + + Response createResponse = _client.OrdersCreate(order); + string id = createResponse.GetResponse()["id"].ToString(); + string externalId = $"{unixTime}ID"; + + Dictionary[] fix = + { + new Dictionary + { + { "id", id }, + { "externalId", externalId } + } + }; + + Assert.IsTrue(createResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetResponse().ContainsKey("id")); + + Response fixResponse = _client.OrdersFixExternalIds(fix); + Assert.IsTrue(fixResponse.IsSuccessfull()); + Assert.IsInstanceOfType(fixResponse, typeof(Response)); + } + + [TestMethod] + public void OrdersList() + { + Response response = _client.OrdersList(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("orders")); + + Dictionary filter = new Dictionary + { + { "extendedStatus", "new" }, + { "createdAtTo", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + + Response responseFiltered = _client.OrdersList(filter, 2, 100); + + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("orders")); + } + + [TestMethod] + public void OrdersHistory() + { + Response response = _client.OrdersHistory(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("orders")); + + + DateTime datetime = DateTime.Now; + DateTime from = datetime.AddHours(-24); + DateTime to = datetime.AddHours(-1); + + Response responseFiltered = _client.OrdersHistory(from, to, 50, 1, false); + + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("orders")); + } + + [TestMethod] + public void OrdersStatuses() + { + List ids = new List(); + + for (int i = 0; i < 5; i++) + { + string[] statuses = new string[5]; + + statuses[0] = "new"; + statuses[1] = "cancel-other"; + statuses[2] = "complete"; + statuses[3] = "assembling-complete"; + statuses[4] = "client-confirmed"; + + Dictionary order = new Dictionary + { + { "number", $"order-{i}" }, + { "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, + { "lastName", $"Doe{i}" }, + { "firstName", $"John{i}" }, + { "email", $"john{i}@example.com" }, + { "phone", $"+7999999999{i}" }, + { "status", statuses[i] } + }; + + Response createResponse = _client.OrdersCreate(order); + ids.Add(createResponse.GetResponse()["id"].ToString()); + } + + Response response = _client.OrdersStatuses(ids); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("orders")); + } + + [TestMethod] + public void OrdersUpload() + { + List orders = new List(); + + for (int i = 0; i < 5; i++) + { + string[] statuses = new string[5]; + + statuses[0] = "new"; + statuses[1] = "cancel-other"; + statuses[2] = "complete"; + statuses[3] = "assembling-complete"; + statuses[4] = "client-confirmed"; + + Dictionary order = new Dictionary + { + { "number", $"order-{i}" }, + { "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, + { "lastName", $"Doe{i}" }, + { "firstName", $"John{i}" }, + { "email", $"john{i}@example.com" }, + { "phone", $"+7999999999{i}" }, + { "status", statuses[i] } + }; + + orders.Add(order); + } + + Response response = _client.OrdersUpload(orders); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("uploadedOrders")); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `order` must contains a data")] + public void OrdersCreateArgumentExeption() + { + Dictionary order = new Dictionary(); + _client.OrdersCreate(order); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `order` must contains a data")] + public void OrdersUpdateEmptyOrderArgumentExeption() + { + Dictionary order = new Dictionary(); + _client.OrdersUpdate(order); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `order` must contains an id or externalId")] + public void OrdersUpdateIdArgumentExeption() + { + Dictionary order = new Dictionary {{"status", "cancel-other"}}; + _client.OrdersUpdate(order); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "You must set the array of `ids` or `externalIds`.")] + public void OrdersStatusesArgumentExeption() + { + _client.OrdersStatuses(null); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Too many ids or externalIds. Maximum number of elements is 500")] + public void OrdersStatusesLimitArgumentExeption() + { + List ids = new List(); + + for (int i = 0; i <= 501; i++) + { + ids.Add(i.ToString()); + } + + _client.OrdersStatuses(ids); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `orders` must contains a data")] + public void OrdersUploadEmptyOrdersArgumentExeption() + { + List orders = new List(); + _client.OrdersUpload(orders); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `orders` must contain 50 or less records")] + public void OrdersUploadLimitArgumentExeption() + { + List orders = new List(); + + for (int i = 0; i < 51; i++) + { + Dictionary order = new Dictionary + { + { "number", $"order-{i}" }, + { "createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, + { "lastName", $"Doe{i}" }, + { "firstName", $"John{i}" }, + { "email", $"john{i}@example.com" }, + { "phone", $"+7999999999{i}" } + }; + + orders.Add(order); + } + + _client.OrdersUpload(orders); + } + } +} diff --git a/RetailcrmUnitTest/V3/PacksTest.cs b/RetailcrmUnitTest/V3/PacksTest.cs new file mode 100644 index 0000000..454c7ee --- /dev/null +++ b/RetailcrmUnitTest/V3/PacksTest.cs @@ -0,0 +1,183 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Globalization; +using System.Linq; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class PacksTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public PacksTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"], _appSettings["site"]); + } + + [TestMethod] + public void PacksCreateUpdateReadDelete() + { + string uid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12); + + Dictionary order = new Dictionary + { + { "number", $"packs-test-{uid}" }, + { "firstName", $"John_{uid}" }, + { "lastName", $"Doe_{uid}"}, + { "email", $"{uid}@example.com"}, + { + "items", new List + { + new Dictionary + { + { "initialPrice", 500 }, + { "quantity", 2}, + { "productId", "_jAjMfjjgs6ukFxOiTE433"}, + { "productName", "Test"} + } + } + } + }; + + Response orderCreateResponse = _client.OrdersCreate(order); + + Assert.IsTrue(orderCreateResponse.IsSuccessfull()); + Assert.IsTrue(orderCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(orderCreateResponse, typeof(Response)); + Assert.IsTrue(orderCreateResponse.GetResponse().ContainsKey("id")); + + Response orderGetResponse = _client.OrdersGet(orderCreateResponse.GetResponse()["id"].ToString(), "id"); + + Assert.IsTrue(orderGetResponse.IsSuccessfull()); + Assert.IsTrue(orderGetResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(orderGetResponse, typeof(Response)); + Assert.IsTrue(orderGetResponse.GetResponse().ContainsKey("order")); + + Dictionary orderFromResponse = + (Dictionary) orderGetResponse.GetResponse()["order"]; + + object[] arr = (object[])orderFromResponse["items"]; + int[] id = new int[1]; + + + foreach (Dictionary s in arr.OfType>()) + { + int itemId; + int.TryParse(s["id"].ToString(), NumberStyles.Any, null, out itemId); + id[0] = itemId; + } + + Dictionary pack = new Dictionary + { + { "purchasePrice", 100 }, + { "quantity", 1}, + { "store", _appSettings["store"]}, + { "itemId", id[0]} + }; + + Response packsCreateResponse = _client.PacksCreate(pack); + + Assert.IsTrue(packsCreateResponse.IsSuccessfull()); + Assert.IsTrue(packsCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(packsCreateResponse, typeof(Response)); + Assert.IsTrue(packsCreateResponse.GetResponse().ContainsKey("id")); + + string packId = packsCreateResponse.GetResponse()["id"].ToString(); + + Dictionary packEdit = new Dictionary + { + { "id", packId }, + { "quantity", 2} + }; + + Response packsUpdateResponse = _client.PacksUpdate(packEdit); + + Assert.IsTrue(packsUpdateResponse.IsSuccessfull()); + Assert.IsTrue(packsUpdateResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(packsUpdateResponse, typeof(Response)); + Assert.IsTrue(packsUpdateResponse.GetResponse().ContainsKey("id")); + + Response packsGetResponse = _client.PacksGet(packId); + + Assert.IsTrue(packsGetResponse.IsSuccessfull()); + Assert.IsTrue(packsGetResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(packsGetResponse, typeof(Response)); + Assert.IsTrue(packsGetResponse.GetResponse().ContainsKey("pack")); + + Response packsDeleteResponse = _client.PacksDelete(packId); + + Assert.IsTrue(packsDeleteResponse.IsSuccessfull()); + Assert.IsTrue(packsDeleteResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(packsDeleteResponse, typeof(Response)); + + } + + [TestMethod] + public void PacksList() + { + Dictionary filter = new Dictionary + { + { "store", _appSettings["store"]} + }; + + Response response = _client.PacksList(filter, 1, 100); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("packs")); + } + + [TestMethod] + public void PacksHistory() + { + Dictionary filter = new Dictionary + { + { "endDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + + Response response = _client.PacksHistory(filter, 2, 100); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("history")); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `pack` must contains a data")] + public void PacksCreateArgumentExeption() + { + Dictionary pack = new Dictionary(); + _client.PacksCreate(pack); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `pack` must contains a data")] + public void PacksUpdateArgumentExeption() + { + Dictionary pack = new Dictionary(); + _client.PacksUpdate(pack); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `pack` must contains an id")] + public void PacksUpdateWithoutIdArgumentExeption() + { + Dictionary pack = new Dictionary + { + { "quantity", 2 } + }; + + _client.PacksUpdate(pack); + } + } +} diff --git a/RetailcrmUnitTest/V3/ReferencesTest.cs b/RetailcrmUnitTest/V3/ReferencesTest.cs new file mode 100644 index 0000000..667d310 --- /dev/null +++ b/RetailcrmUnitTest/V3/ReferencesTest.cs @@ -0,0 +1,349 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class ReferencesTest + { + private readonly Client _client; + + public ReferencesTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void Countries() + { + Response response = _client.Countries(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void DeliveryServices() + { + Response response = _client.DeliveryServices(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void DeliveryTypes() + { + Response response = _client.DeliveryTypes(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void OrderMethods() + { + Response response = _client.OrderMethods(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void OrderTypes() + { + Response response = _client.OrderTypes(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void PaymentStatuses() + { + Response response = _client.PaymentStatuses(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void PaymentTypes() + { + Response response = _client.PaymentTypes(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void ProductStatuses() + { + Response response = _client.ProductStatuses(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void Sites() + { + Response response = _client.Sites(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void StatusGroups() + { + Response response = _client.StatusGroups(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void Statuses() + { + Response response = _client.Statuses(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void Stores() + { + Response response = _client.Stores(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void DeliveryServicesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.DeliveryServicesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestDeliveryService-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void DeliveryTypesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.DeliveryTypesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestDeliveryType-{guid}" }, + { "defaultCost", 300 }, + { "defaultNetCost", 250} + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void OrderMethodsEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.OrderMethodsEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestOrderMethod-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void OrderTypesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.OrderTypesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestOrderType-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void PaymentStatusesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.PaymentStatusesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestPaymentStatus-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void PaymentTypesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.PaymentTypesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestPaymentType-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void ProductStatusesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.ProductStatusesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestProductStatus-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void SitesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.SitesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestProductStatus-{guid}" }, + { "url", $"http://{guid}.example.org" } + } + ); + + Assert.IsFalse(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void StatusesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.StatusesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestProductStatus-{guid}" }, + { "ordering", 40}, + { "group", "cancel"} + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void StoresEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.StoresEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestProductStatus-{guid}" }, + { "type", "store-type-warehouse"} + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} \ No newline at end of file diff --git a/RetailcrmUnitTest/V3/StoresTest.cs b/RetailcrmUnitTest/V3/StoresTest.cs new file mode 100644 index 0000000..f1ae7c3 --- /dev/null +++ b/RetailcrmUnitTest/V3/StoresTest.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class StoresTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public StoresTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"], _appSettings["site"]); + } + + [TestMethod] + public void InventoriesUpload() + { + List offers = new List + { + new Dictionary + { + { "xmlId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + { "stores", new List + { + new Dictionary + { + { "code", _appSettings["store"] }, + { "available", 500 }, + { "purchasePrice", 300} + } + } + } + }, + new Dictionary + { + { "xmlId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + { "stores", new List + { + new Dictionary + { + { "code", _appSettings["store"] }, + { "available", 600 }, + { "purchasePrice", 350} + } + } + } + }, + new Dictionary + { + { "xmlId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + { "stores", new List + { + new Dictionary + { + { "code", _appSettings["store"] }, + { "available", 700 }, + { "purchasePrice", 400} + } + } + } + } + }; + + Response response = _client.StoreInventoriesUpload(offers); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("processedOffersCount")); + } + + [TestMethod] + public void Inventories() + { + Dictionary filter = new Dictionary + { + { "site", _appSettings["site"]}, + { "details", 1} + }; + + Response response = _client.StoreInventoriesGet(filter, 1, 50); + + Debug.WriteLine(response.GetRawResponse()); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("offers")); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `offers` must contains a data")] + public void StoreInventoriesUploadArgumentExeption() + { + List offers = new List(); + _client.StoreInventoriesUpload(offers); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `offers` must contain 250 or less records")] + public void StoreInventoriesUploadLimitArgumentExeption() + { + List offers = new List(); + + for (int i = 0; i < 300; i++) + { + offers.Add( + new Dictionary + { + { "xmlId", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + { "stores", new List + { + new Dictionary + { + { "code", _appSettings["store"] }, + { "available", 700 }, + { "purchasePrice", 400} + } + } + } + } + ); + } + + _client.StoreInventoriesUpload(offers); + } + } +} diff --git a/RetailcrmUnitTest/V3/TelephonyTest.cs b/RetailcrmUnitTest/V3/TelephonyTest.cs new file mode 100644 index 0000000..22ab2e9 --- /dev/null +++ b/RetailcrmUnitTest/V3/TelephonyTest.cs @@ -0,0 +1,33 @@ +using System.Collections.Specialized; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V3; + +namespace RetailcrmUnitTest.V3 +{ + [TestClass] + public class TelephonyTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public TelephonyTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void TelephonyManagerGet() + { + Response response = _client.TelephonyManagerGet(_appSettings["phone"]); + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V4/CustomersTest.cs b/RetailcrmUnitTest/V4/CustomersTest.cs new file mode 100644 index 0000000..38f6b3c --- /dev/null +++ b/RetailcrmUnitTest/V4/CustomersTest.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class CustomersTest + { + private readonly Client _client; + + public CustomersTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void CustomersHistory() + { + Response response = _client.CustomersHistory(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("history")); + + DateTime datetime = DateTime.Now; + + Response responseFiltered = _client.CustomersHistory( + new Dictionary + { + { "startDate", datetime.AddMonths(-2).ToString("yyyy-MM-dd HH:mm:ss") }, + { "endDate", datetime.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss")} + } + ); + + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("history")); + } + } +} diff --git a/RetailcrmUnitTest/V4/MarketplaceTest.cs b/RetailcrmUnitTest/V4/MarketplaceTest.cs new file mode 100644 index 0000000..c18875f --- /dev/null +++ b/RetailcrmUnitTest/V4/MarketplaceTest.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class MarketplaceTest + { + private readonly Client _client; + + public MarketplaceTest() + { + var appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void MarketplaceSettingsEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.MarketplaceSettingsEdit( + new Dictionary() + { + { "name", $"MarketplaceApp-{guid}" }, + { "code", guid}, + { "configurationUrl", $"http://{guid}.example.com"}, + { "active", false} + } + ); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V4/OrdersTest.cs b/RetailcrmUnitTest/V4/OrdersTest.cs new file mode 100644 index 0000000..91e4989 --- /dev/null +++ b/RetailcrmUnitTest/V4/OrdersTest.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class OrdersTest + { + private readonly Client _client; + + public OrdersTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void OrdersHistory() + { + DateTime datetime = DateTime.Now; + + Dictionary filter = new Dictionary + { + { "startDate", datetime.AddHours(-24).ToString("yyyy-MM-dd HH:mm:ss") }, + { "endDate", datetime.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss")} + }; + + Response response = _client.OrdersHistory(filter, 1, 50); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("history")); + } + } +} diff --git a/RetailcrmUnitTest/V4/ReferencesTest.cs b/RetailcrmUnitTest/V4/ReferencesTest.cs new file mode 100644 index 0000000..00aa3e1 --- /dev/null +++ b/RetailcrmUnitTest/V4/ReferencesTest.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class ReferencesTest + { + private readonly Client _client; + + public ReferencesTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void PriceTypes() + { + Response response = _client.PriceTypes(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("priceTypes")); + } + + [TestMethod] + public void PriceTypesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.PriceTypesEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestPriceType-{guid}" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V4/StoresTest.cs b/RetailcrmUnitTest/V4/StoresTest.cs new file mode 100644 index 0000000..ee1598d --- /dev/null +++ b/RetailcrmUnitTest/V4/StoresTest.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class StoresTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public StoresTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"], _appSettings["site"]); + } + + [TestMethod] + public void StoreProducts() + { + Response response = _client.StoreProducts(); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("products")); + } + + + } +} diff --git a/RetailcrmUnitTest/V4/TelephonyTest.cs b/RetailcrmUnitTest/V4/TelephonyTest.cs new file mode 100644 index 0000000..9b30814 --- /dev/null +++ b/RetailcrmUnitTest/V4/TelephonyTest.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class TelephonyTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + private readonly string _phoneCode = "100"; + private readonly string _logoUrl = "http://www.onsitemaintenance.com/img/voip.svg"; + private readonly string _telephonyCode = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + public TelephonyTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void TelephonySettingsEdit() + { + Response response = _client.TelephonySettingsEdit( + new Dictionary + { + + { "code", _telephonyCode}, + { "clientId", _appSettings["customer"] }, + { "makeCallUrl", $"http://{_telephonyCode}.example.com/call"}, + { "name", $"TestTelephony-{_telephonyCode}"}, + { "image", _logoUrl}, + { "inputEventSupported", true}, + { "outputEventSupported", true}, + { "hangupEventSupported", true}, + { + "additionalCodes", + new List + { + new Dictionary + { + { "userId", _appSettings["manager"] }, + { "code", _phoneCode } + } + } + } + } + ); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void TelephonyCallEvent() + { + Response response = _client.TelephonyCallEvent( + new Dictionary + { + { "phone", _appSettings["phone"] }, + { "type", "in" }, + { "hangupStatus", "failed"}, + { "codes", new List { _phoneCode }}, + { "userIds", new List { int.Parse(_appSettings["customer"]) }} + } + + ); + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V4/UsersTest.cs b/RetailcrmUnitTest/V4/UsersTest.cs new file mode 100644 index 0000000..5a8a441 --- /dev/null +++ b/RetailcrmUnitTest/V4/UsersTest.cs @@ -0,0 +1,41 @@ +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V4; + +namespace RetailcrmUnitTest.V4 +{ + [TestClass] + public class UsersTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public UsersTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void UsersGroups() + { + Response usersGroups = _client.UsersGroups(); + Assert.IsTrue(usersGroups.IsSuccessfull()); + Assert.IsTrue(usersGroups.GetStatusCode() == 200); + Assert.IsInstanceOfType(usersGroups, typeof(Response)); + Assert.IsTrue(usersGroups.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void User() + { + Response usersGroups = _client.User(int.Parse(_appSettings["manager"])); + Assert.IsTrue(usersGroups.IsSuccessfull()); + Assert.IsTrue(usersGroups.GetStatusCode() == 200); + Assert.IsInstanceOfType(usersGroups, typeof(Response)); + Assert.IsTrue(usersGroups.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V5/CostsTest.cs b/RetailcrmUnitTest/V5/CostsTest.cs new file mode 100644 index 0000000..77012dc --- /dev/null +++ b/RetailcrmUnitTest/V5/CostsTest.cs @@ -0,0 +1,226 @@ +using System; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class CostsTest + { + private readonly Client _client; + + public CostsTest() + { + var appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void CostsCreateUpdateReadDelete() + { + DateTime datetime = DateTime.Now; + + string groupGuid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response groupResponse = _client.CostGroupsEdit( + new Dictionary + { + { "code", groupGuid}, + { "name", $"TestCostGroup-{groupGuid}" }, + { "color", "#60b29a" } + } + ); + + Debug.WriteLine(groupResponse.GetRawResponse()); + Assert.IsTrue(groupResponse.IsSuccessfull()); + Assert.IsTrue(groupResponse.GetStatusCode() == 200 || groupResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(groupResponse, typeof(Response)); + Assert.IsTrue(groupResponse.GetResponse().ContainsKey("success")); + + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response itemCostResponse = _client.CostItemsEdit( + new Dictionary + { + { "code", guid}, + { "group", groupGuid }, + { "name", $"TestCostItem-{guid}" }, + { "type", "const" } + } + ); + + Debug.WriteLine(itemCostResponse.GetRawResponse()); + Assert.IsTrue(itemCostResponse.IsSuccessfull()); + Assert.IsTrue(itemCostResponse.GetStatusCode() == 200 || itemCostResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(itemCostResponse, typeof(Response)); + Assert.IsTrue(itemCostResponse.GetResponse().ContainsKey("success")); + + Response costsCreateResponse = _client.CostsCreate( + new Dictionary + { + { "summ", 20000 }, + { "comment", "test cost" }, + { "costItem", guid }, + { "dateFrom", datetime.AddDays(-3).ToString("yyyy-MM-dd")}, + { "dateTo", datetime.AddDays(+3).ToString("yyyy-MM-dd")}, + } + ); + + Debug.WriteLine(costsCreateResponse.GetRawResponse()); + Assert.IsTrue(costsCreateResponse.IsSuccessfull()); + Assert.IsTrue(costsCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(costsCreateResponse, typeof(Response)); + Assert.IsTrue(costsCreateResponse.GetResponse().ContainsKey("success")); + + Response costsUpdateResponse = _client.CostsUpdate( + new Dictionary + { + { "id", costsCreateResponse.GetResponse()["id"].ToString()}, + { "summ", 30000 }, + { "comment", "test cost update" }, + { "costItem", guid }, + { "dateFrom", datetime.AddDays(-3).ToString("yyyy-MM-dd")}, + { "dateTo", datetime.AddDays(+3).ToString("yyyy-MM-dd")}, + } + ); + + Debug.WriteLine(costsUpdateResponse.GetRawResponse()); + Assert.IsTrue(costsUpdateResponse.IsSuccessfull()); + Assert.IsTrue(costsUpdateResponse.GetStatusCode() == 200 || costsUpdateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(costsUpdateResponse, typeof(Response)); + Assert.IsTrue(costsUpdateResponse.GetResponse().ContainsKey("success")); + + Response responseGet = _client.CostsGet(int.Parse(costsCreateResponse.GetResponse()["id"].ToString())); + + Debug.WriteLine(responseGet.GetRawResponse()); + Assert.IsTrue(responseGet.IsSuccessfull()); + Assert.IsTrue(responseGet.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseGet, typeof(Response)); + Assert.IsTrue(responseGet.GetResponse().ContainsKey("success")); + + Response response = _client.CostsDelete(costsCreateResponse.GetResponse()["id"].ToString()); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void CostsList() + { + DateTime datetime = DateTime.Now; + + Response responseFiltered = _client.CostsList( + new Dictionary + { + { "createdAtFrom", datetime.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss") } + }, + 2, + 50 + ); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("costs")); + } + + [TestMethod] + public void CostsUploadDelete() + { + DateTime datetime = DateTime.Now; + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + string groupGuid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response groupResponse = _client.CostGroupsEdit( + new Dictionary + { + { "code", groupGuid}, + { "name", $"TestCostGroup-{groupGuid}" }, + { "color", "#60b29a" } + } + ); + + Debug.WriteLine(groupResponse.GetRawResponse()); + Assert.IsTrue(groupResponse.IsSuccessfull()); + Assert.IsTrue(groupResponse.GetStatusCode() == 200 || groupResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(groupResponse, typeof(Response)); + Assert.IsTrue(groupResponse.GetResponse().ContainsKey("success")); + + Response itemCostResponse = _client.CostItemsEdit( + new Dictionary + { + { "code", guid}, + { "group", groupGuid }, + { "name", $"TestCostItem-{guid}" }, + { "type", "const" } + } + ); + + Debug.WriteLine(itemCostResponse.GetRawResponse()); + Assert.IsTrue(itemCostResponse.IsSuccessfull()); + Assert.IsTrue(itemCostResponse.GetStatusCode() == 200 || itemCostResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(itemCostResponse, typeof(Response)); + Assert.IsTrue(itemCostResponse.GetResponse().ContainsKey("success")); + + Response costsUploadResponse = _client.CostsUpload( + new List + { + new Dictionary + { + { "summ", 10000 }, + { "comment", "test cost 1" }, + { "costItem", guid }, + { "dateFrom", datetime.AddDays(-3).ToString("yyyy-MM-dd")}, + { "dateTo", datetime.AddDays(+3).ToString("yyyy-MM-dd")}, + }, + new Dictionary + { + { "summ", 20000 }, + { "comment", "test cost 2" }, + { "costItem", guid }, + { "dateFrom", datetime.AddDays(-3).ToString("yyyy-MM-dd")}, + { "dateTo", datetime.AddDays(+3).ToString("yyyy-MM-dd")}, + }, + new Dictionary + { + { "summ", 30000 }, + { "comment", "test cost 3" }, + { "costItem", guid }, + { "dateFrom", datetime.AddDays(-3).ToString("yyyy-MM-dd")}, + { "dateTo", datetime.AddDays(+3).ToString("yyyy-MM-dd")}, + }, + } + ); + + Debug.WriteLine(costsUploadResponse.GetRawResponse()); + Assert.IsTrue(costsUploadResponse.IsSuccessfull()); + Assert.IsTrue(costsUploadResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(costsUploadResponse, typeof(Response)); + Assert.IsTrue(costsUploadResponse.GetResponse().ContainsKey("success")); + + List uploadedCosts = new List(); + object[] uids = (object[]) costsUploadResponse.GetResponse()["uploadedCosts"]; + + foreach (var uid in uids) + { + uploadedCosts.Add(uid.ToString()); + } + + Response costsDeleteResponse = _client.CostsDelete(uploadedCosts); + + Debug.WriteLine(costsDeleteResponse.GetRawResponse()); + Assert.IsTrue(costsDeleteResponse.IsSuccessfull()); + Assert.IsTrue(costsDeleteResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(costsUploadResponse, typeof(Response)); + Assert.IsTrue(costsUploadResponse.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V5/CustomFieldsTest.cs b/RetailcrmUnitTest/V5/CustomFieldsTest.cs new file mode 100644 index 0000000..ab42b21 --- /dev/null +++ b/RetailcrmUnitTest/V5/CustomFieldsTest.cs @@ -0,0 +1,163 @@ +using System; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class CustomFieldsTest + { + private readonly Client _client; + + public CustomFieldsTest() + { + var appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void CustomFieldsList() + { + Response responseFiltered = _client.CustomFieldsList(new Dictionary { { "entity", "order" } }, 2, 50); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("customFields")); + } + + [TestMethod] + public void CustomFieldsCreateUpdateRead() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response customFieldsCreateResponse = _client.CustomFieldsCreate( + new Dictionary + { + { "code", $"customfield{guid}" }, + { "name", $"CustomField-{guid}"}, + { "type", "string"}, + { "entity", "order"} + } + ); + + Debug.WriteLine(customFieldsCreateResponse.GetRawResponse()); + Assert.IsTrue(customFieldsCreateResponse.IsSuccessfull()); + Assert.IsTrue(customFieldsCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(customFieldsCreateResponse, typeof(Response)); + Assert.IsTrue(customFieldsCreateResponse.GetResponse().ContainsKey("code")); + + Response customFieldGetResponse = _client.CustomFieldsGet($"customfield{guid}", "order"); + + Debug.WriteLine(customFieldGetResponse.GetRawResponse()); + Assert.IsTrue(customFieldGetResponse.IsSuccessfull()); + Assert.IsTrue(customFieldGetResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(customFieldGetResponse, typeof(Response)); + Assert.IsTrue(customFieldGetResponse.GetResponse().ContainsKey("customField")); + + Response customFieldsUpdateResponse = _client.CustomFieldsUpdate( + new Dictionary + { + { "code", $"customfield{guid}" }, + { "name", $"CustomField-{guid}"}, + { "type", "string"}, + { "entity", "order"}, + { "inList", false} + } + ); + + Debug.WriteLine(customFieldsUpdateResponse.GetRawResponse()); + Assert.IsTrue(customFieldsUpdateResponse.IsSuccessfull()); + Assert.IsTrue(customFieldsUpdateResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(customFieldsUpdateResponse, typeof(Response)); + Assert.IsTrue(customFieldsUpdateResponse.GetResponse().ContainsKey("code")); + } + + [TestMethod] + public void CustomDictionaryList() + { + Response responseFiltered = _client.CustomDictionaryList(new Dictionary(), 2, 50); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("customDictionaries")); + } + + [TestMethod] + public void CustomDictionariesCreateUpdateRead() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + string fuid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response customDictionaryCreateResponse = _client.CustomDictionaryCreate( + new Dictionary + { + { "code", $"customdict{guid}" }, + { "name", $"CustomDict-{guid}"}, + { + "elements", + new List + { + new Dictionary + { + { "code", $"customdictelement-{fuid}" }, + { "name", $"CustomDictElement-{fuid}" } + } + } + } + } + ); + + Debug.WriteLine(customDictionaryCreateResponse.GetRawResponse()); + Assert.IsTrue(customDictionaryCreateResponse.IsSuccessfull()); + Assert.IsTrue(customDictionaryCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(customDictionaryCreateResponse, typeof(Response)); + Assert.IsTrue(customDictionaryCreateResponse.GetResponse().ContainsKey("code")); + + Response customDictionaryGetResponse = _client.CustomDictionaryGet(customDictionaryCreateResponse.GetResponse()["code"].ToString()); + + Debug.WriteLine(customDictionaryGetResponse.GetRawResponse()); + Assert.IsTrue(customDictionaryGetResponse.IsSuccessfull()); + Assert.IsTrue(customDictionaryGetResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(customDictionaryGetResponse, typeof(Response)); + Assert.IsTrue(customDictionaryGetResponse.GetResponse().ContainsKey("customDictionary")); + + Response customDictionaryEditResponse = _client.CustomDictionaryUpdate( + new Dictionary + { + { "code", $"customdict{guid}" }, + { "name", $"CustomDict-{guid}Edited"}, + { + "elements", + new List + { + new Dictionary + { + { "code", $"customdictelement-{fuid}" }, + { "name", $"CustomDictElement-{fuid}" } + }, + new Dictionary + { + { "code", $"customdictelement-{fuid}1" }, + { "name", $"CustomDictElement-{fuid}1" } + } + } + } + } + ); + + Debug.WriteLine(customDictionaryEditResponse.GetRawResponse()); + Assert.IsTrue(customDictionaryEditResponse.IsSuccessfull()); + Assert.IsTrue(customDictionaryEditResponse.GetStatusCode() == 200); + Assert.IsInstanceOfType(customDictionaryEditResponse, typeof(Response)); + Assert.IsTrue(customDictionaryEditResponse.GetResponse().ContainsKey("code")); + } + } +} diff --git a/RetailcrmUnitTest/V5/IntegrationTest.cs b/RetailcrmUnitTest/V5/IntegrationTest.cs new file mode 100644 index 0000000..c53ca08 --- /dev/null +++ b/RetailcrmUnitTest/V5/IntegrationTest.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class IntegrationTest + { + private readonly Client _client; + + public IntegrationTest() + { + var appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void IntegrationsSettingsEditSettingsGet() + { + string uid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.IntegrationsSettingsEdit( + new Dictionary + { + { "code", uid}, + { "name", $"TestIntegration-{uid}"}, + { "active", true}, + { "accountUrl", $"http://{uid}.example.com"}, + { "logo", "https://www.ibm.com/cloud-computing/images/cloud/products/cloud-integration/api-economy-icon.svg"}, + } + ); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + + Response responseGet = _client.IntegrationsSettingGet(uid); + + Debug.WriteLine(responseGet.GetRawResponse()); + Assert.IsTrue(responseGet.IsSuccessfull()); + Assert.IsInstanceOfType(responseGet, typeof(Response)); + Assert.IsTrue(responseGet.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V5/NotesTest.cs b/RetailcrmUnitTest/V5/NotesTest.cs new file mode 100644 index 0000000..a3711be --- /dev/null +++ b/RetailcrmUnitTest/V5/NotesTest.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class NotesTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public NotesTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void NotesCreateDelete() + { + Response responseFiltered = _client.NotesCreate( + new Dictionary + { + { "text", "test task" }, + { "customer", new Dictionary { { "id", "2015" } }}, + { "managerId", _appSettings["manager"]} + } + ); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 201); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("success")); + + Response response = _client.NotesDelete(responseFiltered.GetResponse()["id"].ToString()); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void NotesList() + { + DateTime datetime = DateTime.Now; + + Response responseFiltered = _client.NotesList( + new Dictionary + { + { "createdAtFrom", datetime.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss") } + }, + 2, + 50 + ); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("notes")); + } + } +} diff --git a/RetailcrmUnitTest/V5/OrdersTest.cs b/RetailcrmUnitTest/V5/OrdersTest.cs new file mode 100644 index 0000000..cfd3fd5 --- /dev/null +++ b/RetailcrmUnitTest/V5/OrdersTest.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class OrdersTest + { + private readonly Client _client; + + public OrdersTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void OrdersCombine() + { + Dictionary firstOrder = new Dictionary + { + {"number", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", $"{Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}@example.com"}, + {"phone", "+79999999999"} + }; + + + Response createFirstResponse = _client.OrdersCreate(firstOrder); + Assert.IsTrue(createFirstResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createFirstResponse, typeof(Response)); + Assert.IsTrue(createFirstResponse.GetResponse().ContainsKey("id")); + + string firstId = createFirstResponse.GetResponse()["id"].ToString(); + + Dictionary secondOrder = new Dictionary + { + {"number", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}, + {"createdAt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", $"{Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12)}@example.com"}, + {"phone", "+79999999999"} + }; + + + Response createSecondResponse = _client.OrdersCreate(secondOrder); + Assert.IsTrue(createSecondResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createSecondResponse, typeof(Response)); + Assert.IsTrue(createSecondResponse.GetResponse().ContainsKey("id")); + + string secondId = createSecondResponse.GetResponse()["id"].ToString(); + + Dictionary firstCombineOrder = new Dictionary + { + {"id", firstId } + }; + + Dictionary secondCombineOrder = new Dictionary + { + {"id", secondId } + }; + + Response combineResponse = _client.OrdersCombine(firstCombineOrder, secondCombineOrder); + + Debug.WriteLine(combineResponse.GetRawResponse()); + + Assert.IsTrue(combineResponse.IsSuccessfull()); + Assert.IsInstanceOfType(combineResponse, typeof(Response)); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `order` must contains a data")] + public void OrdersCombineEmptyOrderArgumentExeption() + { + Dictionary firstOrder = new Dictionary(); + Dictionary secondOrder = new Dictionary + { + { "id", "111" } + }; + + _client.OrdersCombine(firstOrder, secondOrder); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `resultOrder` must contains a data")] + public void OrdersCombineEmptyResultOrderArgumentExeption() + { + Dictionary secondOrder = new Dictionary(); + Dictionary firstOrder = new Dictionary + { + { "id", "111" } + }; + + _client.OrdersCombine(firstOrder, secondOrder); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `order` must contains `id` key")] + public void OrdersCombineEmptyIdOrderArgumentExeption() + { + Dictionary firstOrder = new Dictionary + { + { "number", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12) } + }; + + Dictionary secondOrder = new Dictionary + { + { "id", "111" } + }; + + _client.OrdersCombine(firstOrder, secondOrder); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "Parameter `resultOrder` must contains `id` key")] + public void OrdersCombineEmptyIdResultOrderArgumentExeption() + { + Dictionary secondOrder = new Dictionary + { + { "number", Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12) } + }; + + Dictionary firstOrder = new Dictionary + { + { "id", "111" } + }; + + _client.OrdersCombine(firstOrder, secondOrder); + } + } +} diff --git a/RetailcrmUnitTest/V5/PaymentsTest.cs b/RetailcrmUnitTest/V5/PaymentsTest.cs new file mode 100644 index 0000000..ed931b8 --- /dev/null +++ b/RetailcrmUnitTest/V5/PaymentsTest.cs @@ -0,0 +1,83 @@ +using System; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class PaymentsTest + { + private readonly Client _client; + + public PaymentsTest() + { + var appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void PaymentsCreateUpdateDelete() + { + DateTime datetime = DateTime.Now; + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response createResponse = _client.OrdersCreate(new Dictionary + { + {"externalId", guid}, + {"createdAt", datetime.ToString("yyyy-MM-dd HH:mm:ss")}, + {"lastName", "Doe"}, + {"firstName", "John"}, + {"email", "john@example.com"}, + {"phone", "+79999999999"} + }); + + Debug.WriteLine(createResponse.GetRawResponse()); + Assert.IsTrue(createResponse.IsSuccessfull()); + Assert.IsInstanceOfType(createResponse, typeof(Response)); + Assert.IsTrue(createResponse.GetResponse().ContainsKey("id")); + + Response paymentCreateResponse = _client.PaymentsCreate( + new Dictionary + { + { "externalId", guid }, + { "type", "cash" }, + { "comment", "test payment" }, + { "order", new Dictionary { { "id", createResponse.GetResponse()["id"].ToString() } } }, + } + ); + + Debug.WriteLine(paymentCreateResponse.GetRawResponse()); + Assert.IsTrue(paymentCreateResponse.IsSuccessfull()); + Assert.IsTrue(paymentCreateResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(paymentCreateResponse, typeof(Response)); + Assert.IsTrue(paymentCreateResponse.GetResponse().ContainsKey("success")); + + Response paymentUpdateResponse = _client.PaymentsUpdate( + new Dictionary + { + { "id", paymentCreateResponse.GetResponse()["id"].ToString()}, + { "status", "paid"}, + { "paidAt", datetime.ToString("yyyy-MM-dd HH:mm:ss")}, + { "amount", 4000 } + } + ); + + Debug.WriteLine(paymentUpdateResponse.GetRawResponse()); + Assert.IsTrue(paymentUpdateResponse.IsSuccessfull()); + Assert.IsInstanceOfType(paymentUpdateResponse, typeof(Response)); + Assert.IsTrue(paymentUpdateResponse.GetResponse().ContainsKey("success")); + + Response response = _client.PaymentsDelete(paymentCreateResponse.GetResponse()["id"].ToString()); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V5/ReferencesTest.cs b/RetailcrmUnitTest/V5/ReferencesTest.cs new file mode 100644 index 0000000..662a87d --- /dev/null +++ b/RetailcrmUnitTest/V5/ReferencesTest.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class ReferencesTest + { + private readonly Client _client; + + public ReferencesTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void CostGroups() + { + Response response = _client.CostGroups(); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("costGroups")); + } + + [TestMethod] + public void CostItems() + { + Response response = _client.CostItems(); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("costItems")); + } + + [TestMethod] + public void LegalEntities() + { + Response response = _client.LegalEntities(); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("legalEntities")); + } + + [TestMethod] + public void CostGroupsEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.CostGroupsEdit( + new Dictionary + { + { "code", guid}, + { "name", $"TestCostGroup-{guid}" }, + { "color", "#da5c98" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void CostItemsEdit() + { + string groupGuid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response groupResponse = _client.CostGroupsEdit( + new Dictionary + { + { "code", groupGuid}, + { "name", $"TestCostGroup-{groupGuid}" }, + { "color", "#60b29a" } + } + ); + + Assert.IsTrue(groupResponse.IsSuccessfull()); + Assert.IsTrue(groupResponse.GetStatusCode() == 200 || groupResponse.GetStatusCode() == 201); + Assert.IsInstanceOfType(groupResponse, typeof(Response)); + Assert.IsTrue(groupResponse.GetResponse().ContainsKey("success")); + + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.CostItemsEdit( + new Dictionary + { + { "code", guid}, + { "group", groupGuid }, + { "name", $"TestCostItem-{guid}" }, + { "type", "const" } + } + ); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void LegalEntitiesEdit() + { + string guid = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 6); + + Response response = _client.LegalEntitiesEdit( + new Dictionary + { + { "code", guid}, + { "legalName", $"Test LegalEntity-{guid}" }, + { "contragentType", "legal-entity"}, + { "countryIso", "RU"} + } + ); + + Debug.WriteLine(response.GetRawResponse()); + + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200 || response.GetStatusCode() == 201); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/V5/SegmentsTest.cs b/RetailcrmUnitTest/V5/SegmentsTest.cs new file mode 100644 index 0000000..713b009 --- /dev/null +++ b/RetailcrmUnitTest/V5/SegmentsTest.cs @@ -0,0 +1,39 @@ +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class SegmentsTest + { + private readonly Client _client; + + public SegmentsTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void Segments() + { + Response responseFiltered = _client.Segments( + new Dictionary + { + { "active", "1" } + }, + 2, + 50 + ); + + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("segments")); + } + } +} diff --git a/RetailcrmUnitTest/V5/TasksTest.cs b/RetailcrmUnitTest/V5/TasksTest.cs new file mode 100644 index 0000000..f13e78d --- /dev/null +++ b/RetailcrmUnitTest/V5/TasksTest.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class TasksTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public TasksTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + public void TasksCreateUpdateGet() + { + DateTime datetime = DateTime.Now; + + Response responseFiltered = _client.TasksCreate( + new Dictionary + { + { "text", "test task" }, + { "commentary", "test commentary"}, + { "datetime", datetime.AddHours(+3).ToString("yyyy-MM-dd HH:mm")}, + { "performerId", _appSettings["manager"]} + } + ); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 201); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("success")); + + Response response = _client.TasksUpdate( + new Dictionary + { + { "id", responseFiltered.GetResponse()["id"].ToString()}, + { "text", "test task edited" }, + { "commentary", "test commentary"}, + { "datetime", datetime.AddHours(+4).ToString("yyyy-MM-dd HH:mm")}, + { "performerId", _appSettings["manager"]} + } + ); + + Debug.WriteLine(response.GetRawResponse()); + Assert.IsTrue(response.IsSuccessfull()); + Assert.IsTrue(response.GetStatusCode() == 200); + Assert.IsInstanceOfType(response, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + + Response responseGet = _client.TasksGet(responseFiltered.GetResponse()["id"].ToString()); + + Debug.WriteLine(responseGet.GetRawResponse()); + Assert.IsTrue(responseGet.IsSuccessfull()); + Assert.IsTrue(responseGet.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseGet, typeof(Response)); + Assert.IsTrue(response.GetResponse().ContainsKey("success")); + } + + [TestMethod] + public void TasksList() + { + Response responseFiltered = _client.TasksList( + new Dictionary + { + { "performers", new List { _appSettings["manager"] } }, + { "status", "performing" } + }, + 2, + 50 + ); + + Debug.WriteLine(responseFiltered.GetRawResponse()); + Assert.IsTrue(responseFiltered.IsSuccessfull()); + Assert.IsTrue(responseFiltered.GetStatusCode() == 200); + Assert.IsInstanceOfType(responseFiltered, typeof(Response)); + Assert.IsTrue(responseFiltered.GetResponse().ContainsKey("tasks")); + } + } +} diff --git a/RetailcrmUnitTest/V5/TelephonyTest.cs b/RetailcrmUnitTest/V5/TelephonyTest.cs new file mode 100644 index 0000000..9a962da --- /dev/null +++ b/RetailcrmUnitTest/V5/TelephonyTest.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class TelephonyTest + { + private readonly Client _client; + private readonly NameValueCollection _appSettings; + + public TelephonyTest() + { + _appSettings = ConfigurationManager.AppSettings; + _client = new Client(_appSettings["apiUrl"], _appSettings["apiKey"]); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "This method is unavailable in API V5")] + public void TelephonySettingsGetArgumentExeption() + { + _client.TelephonySettingsGet("anycode"); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException), "This method is unavailable in API V5")] + public void TelephonySettingsGetTelephonySettingsEditArgumentExeption() + { + _client.TelephonySettingsEdit(new Dictionary()); + } + } +} diff --git a/RetailcrmUnitTest/V5/UsersTest.cs b/RetailcrmUnitTest/V5/UsersTest.cs new file mode 100644 index 0000000..18fc7ce --- /dev/null +++ b/RetailcrmUnitTest/V5/UsersTest.cs @@ -0,0 +1,43 @@ +using System.Collections.Specialized; +using System.Configuration; +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Retailcrm; +using Retailcrm.Versions.V5; + +namespace RetailcrmUnitTest.V5 +{ + [TestClass] + public class UsersTest + { + private readonly Client _client; + + public UsersTest() + { + NameValueCollection appSettings = ConfigurationManager.AppSettings; + _client = new Client(appSettings["apiUrl"], appSettings["apiKey"]); + } + + [TestMethod] + public void UsersStatus() + { + Response users = _client.Users(); + Assert.IsTrue(users.IsSuccessfull()); + Assert.IsTrue(users.GetStatusCode() == 200); + Assert.IsInstanceOfType(users, typeof(Response)); + Assert.IsTrue(users.GetResponse().ContainsKey("success")); + + object[] list = (object[])users.GetResponse()["users"]; + var user = list[0] as Dictionary; + Debug.Assert(user != null, nameof(user) + " != null"); + int uid = int.Parse(user["id"].ToString()); + + Response status = _client.UsersStatus(uid, "break"); + Assert.IsTrue(status.IsSuccessfull()); + Assert.IsTrue(status.GetStatusCode() == 200); + Assert.IsInstanceOfType(status, typeof(Response)); + Assert.IsTrue(status.GetResponse().ContainsKey("success")); + } + } +} diff --git a/RetailcrmUnitTest/packages.config b/RetailcrmUnitTest/packages.config new file mode 100644 index 0000000..fc2bbdd --- /dev/null +++ b/RetailcrmUnitTest/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file