defmodule FreshdeskExport do @doc """ Returns a list of all of the tickets from a Freshdesk instance. By default it will start on page 1 but accepts an integer ```start_page``` as a parameter for starting on a page greater than or equal to 1. """ def get_tickets(start_page \\ 1) when start_page >= 1 do tickets = request_tickets(start_page) tickets ++ get_tickets(tickets, start_page+1) end defp get_tickets([_head|_tail], current_page) do tickets = request_tickets(current_page) tickets ++ get_tickets(tickets, current_page+1) end defp get_tickets([], _end_page), do: [] @doc """ Returns a single ticket. Requires an ```id``` as a parameter. """ def get_ticket(id) do import Poison, only: [decode!: 1] http_params = %{ url: Application.get_env(:freshdesk_export, :domain) <> "/api/v2/tickets/" <> Integer.to_string(id), headers: [ {"Accept", "application/json"}, {"authorization", "Basic " <> Application.get_env(:freshdesk_export, :api_key)} ] } response = HTTPoison.request!(:get, http_params.url, "", http_params.headers) decode!(response.body) end @doc """ Returns a list of tickets on a specific page. Requires a ```page``` number as a parameter. """ def request_tickets(page) do import Poison, only: [decode!: 1] http_params = %{ url: Application.get_env(:freshdesk_export, :domain) <> "/api/v2/tickets?per_page=100&page=" <> Integer.to_string(page), headers: [ {"Accept", "application/json"}, {"authorization", "Basic " <> Application.get_env(:freshdesk_export, :api_key)} ] } response = HTTPoison.request!(:get, http_params.url, "", http_params.headers) decode!(response.body) end @doc """ Naturally, the get/request functions will return a descending list of data. This function utilizes ```Enum.reverse()``` to switch it to an ascending list instead. ```|>``` your ticket lists to this function for ease of use. """ def sort_ascending(data) when is_list(data) === true, do: Enum.reverse(data) @doc """ By default, this function will create a directory structure of "data/json" and store a JSON file in the json directory with a unix timestamp in the title to make sure the file is unique. Alternatively, you can provide a second custom path parameter to save it to by providing a string for a folder name or utilizing ```Path.join()/1``` or ```Path.join()/2```. You can also provide a custom filename as a third parameter if unix timestamps aren't your thing. Furthermore, parent directories will be created automatically so feel free to provide a longer path as the second parameter. Otherwise, you can simply ```|>``` your ticket lists to this function for ease of use if the defaults are good enough. """ def write_json(data, save_path \\ Path.join("data", "json"), filename \\ "freshdesk-export-" <> Integer.to_string(DateTime.to_unix(DateTime.utc_now))) do import Poison, only: [encode!: 1] if File.exists?(save_path) === false, do: File.mkdir_p(save_path) File.write(Path.join(save_path, filename <> ".json"), encode!(data)) end end