repo
string | commit
string | message
string | diff
string |
---|---|---|---|
ish/couchish
|
a2fa8210aed0d17e964886932c108b4ab87e44cc
|
fixed bug in filehandling (conflict on multiple files). Added type to Reference and also CouchDB form widgets
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index 7a75c2e..02862df 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,409 +1,417 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
from dottedish import get_dict_from_dotted_dict
from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
+ type = "Reference"
+
def __init__(self, **k):
self.refersto = k['attr']['refersto']
#self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
+ type="FileUpload"
+
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
+ type="SelectChoice"
+
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
self.sort = k.pop('sort', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
if self.sort == True:
_options.sort(lambda x, y: cmp(x[1], y[1]))
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
def get_parent(segments):
if len(segments) == 1:
return ''
else:
return '.'.join(segments[:-1])
def mktree(options):
last_segments_len = 1
root = {'': {'data':('root', 'Root'), 'children':[]} }
for id, label in options:
segments = id.split('.')
parent = get_parent(segments)
root[id] = {'data': (id, label), 'children':[]}
root[parent]['children'].append(root[id])
return root['']
class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
_template='CheckboxMultiChoiceTreeCouchDB'
+ type = "CheckboxMultiChoiceTree"
def __init__(self, full_options, cssClass=None):
self.options = [ (key, value['data']['label']) for key, value in full_options]
self.full_options = dict(full_options)
self.optiontree = mktree(self.options)
widgets.Widget.__init__(self,cssClass=cssClass)
def pre_render(self, schema_type, data):
if data is None:
return []
return [c['path'] for c in data]
def checked(self, option, values, schema_type):
if values is not None and option[0] in values:
return ' checked="checked"'
else:
return ''
def convert(self, schema_type, data):
out = []
for item in data:
out.append(self.full_options[item])
return out
class SeqRefTextArea(formish.Input):
"""
Textarea input field
:arg cols: set the cols attr on the textarea element
:arg rows: set the cols attr on the textarea element
"""
_template = 'SeqRefTextArea'
+ type="SeqRefTextArea"
def __init__(self, db, view, **k):
self.cols = k.pop('cols', None)
self.rows = k.pop('rows', None)
self.strip = k.pop('strip', True)
self.db = db
self.view = view
formish.Input.__init__(self, **k)
if not self.converter_options.has_key('delimiter'):
self.converter_options['delimiter'] = '\n'
def pre_render(self, schema_type, data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
if data is None:
return []
string_data = [d['_ref'] for d in data]
return string_data
def convert(self, schema_type, request_data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
string_data = request_data[0]
if self.strip is True:
string_data = string_data.strip()
if string_data == '':
return self.empty
ids = [s.strip() for s in string_data.splitlines()]
docs = self.db.view(self.view, keys=ids)
out = []
for d in docs:
d.value.update({'_ref': d.key})
out.append(d.value)
return out
def __repr__(self):
attributes = []
if self.strip is False:
attributes.append('strip=%r'%self.strip)
if self.converter_options != {'delimiter':','}:
attributes.append('converter_options=%r'%self.converter_options)
if self.css_class:
attributes.append('css_class=%r'%self.css_class)
if self.empty is not None:
attributes.append('empty=%r'%self.empty)
return 'couchish_formish_jsonbuilder.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SeqRefTextArea'] = self.seqreftextarea_factory
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
k['sort'] = widget_spec.get('sort')
attr = spec.get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
def seqreftextarea_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
attr = spec.get('attr',{}).get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SeqRefTextArea(self.db, view, **k)
def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
facet = list(db.view(view, include_docs=True))[0].doc
options = []
for item in facet['category']:
options.append( (item['path'],item) )
return options
view = 'facet_%s/all'%widgetSpec['facet']
return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
diff --git a/couchish/filehandling.py b/couchish/filehandling.py
index e4a1f32..a809f2c 100644
--- a/couchish/filehandling.py
+++ b/couchish/filehandling.py
@@ -1,211 +1,212 @@
"""
Views we can build:
* by type, one view should be ok
* x_by_y views, from config (optional)
* ref and ref reversed views, one pair per relationship
"""
from dottedish import dotted
import base64
import uuid
from schemaish.type import File
from StringIO import StringIO
import shutil
from couchish import jsonutil
def get_attr(prefix, parent=None):
# combine prefix and parent where prefix is a list and parent is a dotted string
if parent is None:
segments = [str(segment) for segment in prefix]
return '.'.join(segments)
if prefix is None:
return parent
segments = [str(segment) for segment in prefix]
if parent != '':
segments += parent.split('.')
attr = '.'.join( segments )
return attr
def get_files(data, original=None, prefix=None):
# scan old data to collect any file refs and then scan new data for file changes
files = {}
inlinefiles = {}
original_files = {}
get_files_from_original(data, original, files, inlinefiles, original_files, prefix)
get_files_from_data(data, original, files, inlinefiles, original_files, prefix)
return data, files, inlinefiles, original_files
def has_unmodified_signature(f):
if f.file is None:
return True
return False
def make_dotted_or_emptydict(d):
if isinstance(d, dict):
return dotted(d)
return dotted({})
def get_files_from_data(data, original, files, inlinefiles, original_files, prefix):
if isinstance(data, File):
get_file_from_item(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(data, dict):
return
dd = dotted(data)
ddoriginal = make_dotted_or_emptydict(original)
for k,f in dd.dotteditems():
if isinstance(f, File):
if isinstance(ddoriginal.get(k), File):
of = ddoriginal[k]
else:
of = None
get_file_from_item(f, of, files, inlinefiles, original_files, get_attr(prefix, k))
def get_file_from_item(f, of, files, inlinefiles, original_files, fullprefix):
if f.file is None:
# if we have no original data then we presume the file should remain unchanged
f.id = of.id
if f.mimetype is None:
f.mimetype = of.mimetype
if f.filename is None:
f.filename = of.filename
- if not hasattr(f, 'metadata') or f.metadata is None:
+ if not hasattr(f, 'metadata') or f.metadata is None or f.metadata=={}:
f.metadata = getattr(of, 'metadata', None)
else:
if of and hasattr(of,'id'):
f.id = of.id
else:
f.id = uuid.uuid4().hex
if getattr(f,'inline',False) is True:
filestore = inlinefiles
else:
filestore = files
if hasattr(f, 'inline'):
del f.inline
# add the files for attachment handling and remove the file data from document
if getattr(f,'b64', None):
filestore[fullprefix] = jsonutil.CouchishFile(f.file, f.filename, f.mimetype, f.id, metadata = f.metadata, b64=True)
del f.b64
else:
fh = StringIO()
shutil.copyfileobj(f.file, fh)
fh.seek(0)
filestore[fullprefix] = jsonutil.CouchishFile(fh, f.filename, f.mimetype, f.id, metadata = f.metadata)
del f.file
def get_file_from_original(f, of, files, inlinefiles, original_files, fullprefix):
if not isinstance(f, File):
original_files[fullprefix] = of
def get_files_from_original(data, original, files, inlinefiles, original_files, prefix):
if isinstance(original, File):
get_file_from_original(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(original, dict):
return
dd = make_dotted_or_emptydict(data)
ddoriginal = dotted(original)
for k, of in ddoriginal.dotteditems():
if isinstance(of, File):
f = dd.get(k)
get_file_from_original(f, of, files, inlinefiles, original_files, get_attr(prefix, kparent))
def _parse_changes_for_files(session, deletions, additions, changes):
""" returns deletions, additions """
additions = list(additions)
changes = list(changes)
deletions = list(deletions)
all_separate_files = {}
all_inline_files = {}
for addition in additions:
addition, files, inlinefiles, original_files_notused = get_files(addition)
if files:
all_separate_files.setdefault(addition['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(addition['_id'],{}).update(inlinefiles)
_extract_inline_attachments(addition, inlinefiles)
all_original_files = {}
changes = list(changes)
for n, changeset in enumerate(changes):
d, cs = changeset
cs = list(cs)
for m, c in enumerate(cs):
if c['action'] in ['edit','create','remove']:
c['value'], files, inlinefiles, original_files = get_files(c.get('value'), original=c.get('was'), prefix=c['path'])
cs[m] = c
if files:
all_separate_files.setdefault(d['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(d['_id'],{}).update(inlinefiles)
all_original_files.setdefault(d['_id'], {}).update(original_files)
_extract_inline_attachments(d, inlinefiles)
changes[n] = (d, cs)
return all_original_files, all_separate_files
def _extract_inline_attachments(doc, files):
"""
Move the any attachment data that we've found into the _attachments attribute
"""
for attr, f in files.items():
if f.b64:
data = f.file.replace('\n', '')
else:
data = base64.encodestring(f.file.read()).replace('\n','')
f.file.close()
del f.file
del f.b64
del f.inline
del f.doc_id
doc.setdefault('_attachments',{})[f.id] = {'content_type': f.mimetype,'data': data}
def _handle_separate_attachments(session, deletions, additions):
"""
add attachments that aren't inline and remove any attachments without references
"""
# XXX This needs to cope with files moving when sequences are re-numbered. We need
# XXX to talk to matt about what a renumbering like this looks like
for id, attrfiles in additions.items():
doc = session.get(id)
+ stubdoc = {'_id':doc['_id'], '_rev':doc['_rev']}
for attr, f in attrfiles.items():
data = ''
if f.file:
if f.b64:
data = base64.decodestring(f.file)
else:
data = f.file.read()
f.file.close()
- session._db.put_attachment({'_id':doc['_id'], '_rev':doc['_rev']}, data, filename=f.id, content_type=f.mimetype)
+ session._db.put_attachment(stubdoc, data, filename=f.id, content_type=f.mimetype)
del f.file
del f.b64
del f.inline
del f.doc_id
for id, attrfiles in deletions.items():
# XXX had to use _db because delete attachment freeaked using session version.
doc = session._db.get(id)
for attr, f in attrfiles.items():
session._db.delete_attachment(doc, f.id)
additions = {}
deletions = {}
diff --git a/couchish/jsonutil.py b/couchish/jsonutil.py
index 63ff9cb..893c1c0 100644
--- a/couchish/jsonutil.py
+++ b/couchish/jsonutil.py
@@ -1,102 +1,101 @@
from jsonish import pythonjson
from schemaish.type import File
import base64
from dottedish import dotted
class CouchishFile(File):
def __init__(self, file, filename, mimetype, id=None, doc_id=None, inline=False, b64=False, metadata=None):
self.file = file
self.filename = filename
self.mimetype = mimetype
self.id = id
self.doc_id = doc_id
self.inline = inline
self.b64 = b64
if metadata is None:
metadata = {}
self.metadata = metadata
def __repr__(self):
return '<couchish.jsonutil.CouchishFile file="%r" filename="%s", mimetype="%s", id="%s", doc_id="%s", inline="%s", b64="%s", metadata="%r" >' % (getattr(self,'file',None), self.filename, self.mimetype, self.id, getattr(self, 'doc_id',None), getattr(self,'inline',None), getattr(self,'b64', None), getattr(self, 'metadata', {}))
def file_to_dict(obj):
d = {
'__type__': 'file',
'filename': obj.filename,
'mimetype': obj.mimetype,
'id': getattr(obj, 'id', None),
}
if hasattr(obj, 'metadata') and obj.metadata:
d['metadata'] = obj.metadata
if hasattr(obj,'doc_id') and obj.doc_id is not None:
d['doc_id'] = obj.doc_id
if hasattr(obj, 'inline') and obj.inline is not False:
d['inline'] = obj.inline
if hasattr(obj,'file') and hasattr(obj,'b64'):
d['base64'] = obj.file
else:
if hasattr(obj,'file') and obj.file is not None:
d['base64'] = base64.encodestring(obj.file.read())
return d
def file_from_dict(obj):
filename = obj['filename']
mimetype = obj['mimetype']
inline = obj.get('inline', False)
id = obj.get('id')
doc_id = obj.get('doc_id')
metadata = obj.get('metadata',{})
if 'base64' in obj:
data = obj['base64']
return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, b64=True, metadata=metadata)
elif 'file' in obj:
data = obj['file']
return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, metadata=metadata)
else:
return CouchishFile(None, filename, mimetype, id=id, doc_id=doc_id, metadata=metadata)
pythonjson.json.register_type(File, file_to_dict, file_from_dict, "file")
pythonjson.json.register_type(CouchishFile, file_to_dict, file_from_dict, "file")
pythonjson.decode_mapping['file'] = file_from_dict
pythonjson.encode_mapping[File] = ('file',file_to_dict)
pythonjson.encode_mapping[CouchishFile] = ('file',file_to_dict)
def wrap_encode_to_dict(obj):
return pythonjson.encode_to_dict(obj)
def wrap_decode_from_dict(d):
obj = pythonjson.decode_from_dict(d)
obj = add_id_and_attr_to_files(obj)
return obj
encode_to_dict = wrap_encode_to_dict
decode_from_dict = wrap_decode_from_dict
def add_id_and_attr_to_files(data):
if not isinstance(data, dict):
return data
dd = dotted(data)
for k in dd.dottedkeys():
if isinstance(dd[k],File):
if '_id' in dd and '_rev' in dd:
dd[k].doc_id = dd['_id']
dd[k].rev = dd['_rev']
- return dd.data
segments = k.split('.')
for n in xrange(1,len(segments)):
subpath = '.'.join(segments[:-n])
if '_id' in dd[subpath] and '_rev' in dd[subpath]:
dd[k].doc_id = dd[subpath]['_id']
dd[k].rev = dd[subpath]['_rev']
data = dd.data
return data
dumps = pythonjson.dumps
loads = pythonjson.loads
|
ish/couchish
|
a3a19cb67cba7b018acac3153b0f647e5db70a2d
|
Add required package
|
diff --git a/couchish.egg-info/PKG-INFO b/couchish.egg-info/PKG-INFO
index 67a78d3..64c70ef 100644
--- a/couchish.egg-info/PKG-INFO
+++ b/couchish.egg-info/PKG-INFO
@@ -1,10 +1,10 @@
Metadata-Version: 1.0
Name: couchish
-Version: 0.1dev
+Version: 0.2
Summary: UNKNOWN
Home-page: UNKNOWN
Author: Tim Parkin & Matt Goodall
Author-email: [email protected]
License: UNKNOWN
Description: UNKNOWN
Platform: UNKNOWN
diff --git a/couchish.egg-info/SOURCES.txt b/couchish.egg-info/SOURCES.txt
index 0eb3e33..71ef926 100644
--- a/couchish.egg-info/SOURCES.txt
+++ b/couchish.egg-info/SOURCES.txt
@@ -1,9 +1,104 @@
-setup.cfg
+.gitignore
+README
+TODO
+run
setup.py
+unittests
couchish/__init__.py
+couchish/config.py
+couchish/couchish_formish_jsonbuilder.py
+couchish/couchish_jsonbuilder.py
+couchish/create_view.py
+couchish/errors.py
+couchish/filehandling.py
+couchish/filestore.py
+couchish/formish_jsonbuilder.py
+couchish/jsonutil.py
+couchish/schemaish_jsonbuilder.py
+couchish/store.py
+couchish/sync_categories.py
couchish.egg-info/PKG-INFO
couchish.egg-info/SOURCES.txt
couchish.egg-info/dependency_links.txt
couchish.egg-info/entry_points.txt
couchish.egg-info/not-zip-safe
-couchish.egg-info/top_level.txt
\ No newline at end of file
+couchish.egg-info/requires.txt
+couchish.egg-info/top_level.txt
+couchish/tests/__init__.py
+couchish/tests/test_couchish_formish_jsonbuilder.py
+couchish/tests/test_couchish_jsonbuilder.py
+couchish/tests/test_couchish_store.py
+couchish/tests/test_couchish_store_files.py
+couchish/tests/test_filestore.py
+couchish/tests/test_formish_jsonbuilder.py
+couchish/tests/test_schemaish_jsonbuilder.py
+couchish/tests/test_store.py
+couchish/tests/util.py
+couchish/tests/data/categories.yaml
+couchish/tests/data/test_couchish_author.yaml
+couchish/tests/data/test_couchish_book.yaml
+couchish/tests/data/test_couchish_dvd.yaml
+couchish/tests/data/test_couchish_post.yaml
+couchish/tests/data/test_couchish_simple.yaml
+couchish/tests/data/test_couchish_views.yaml
+couchish/tests/data/test_upload.yaml
+couchish/tests/data/autoviews/test_couchish_author.yaml
+couchish/tests/data/autoviews/test_couchish_post.yaml
+couchish/tests/data/autoviews/test_couchish_views.yaml
+couchish/tests/data/by/test_couchish_by_author.yaml
+couchish/tests/data/by/test_couchish_by_post.yaml
+couchish/tests/data/by/test_couchish_by_views.yaml
+couchish/tests/data/deepref/test_couchish_author.yaml
+couchish/tests/data/deepref/test_couchish_book.yaml
+couchish/tests/data/deepref/test_couchish_views.yaml
+couchish/tests/data/files/test-changed.txt
+couchish/tests/data/files/test.txt
+couchish/tests/data/formish_jsonbuilder/test_sequence.yaml
+couchish/tests/data/formish_jsonbuilder/test_sequenceofstructures.yaml
+couchish/tests/data/formish_jsonbuilder/test_simple.yaml
+couchish/tests/data/formish_jsonbuilder/test_substructure.yaml
+couchish/tests/data/formish_jsonbuilder/test_types.yaml
+couchish/tests/data/formish_jsonbuilder/test_widgets.yaml
+couchish/tests/data/nestedrefinnestedseq/test_couchish_author.yaml
+couchish/tests/data/nestedrefinnestedseq/test_couchish_book.yaml
+couchish/tests/data/nestedrefinnestedseq/test_couchish_views.yaml
+couchish/tests/data/nestedrefinseq/test_couchish_author.yaml
+couchish/tests/data/nestedrefinseq/test_couchish_book.yaml
+couchish/tests/data/nestedrefinseq/test_couchish_views.yaml
+couchish/tests/data/refinseq/test_couchish_author.yaml
+couchish/tests/data/refinseq/test_couchish_book.yaml
+couchish/tests/data/refinseq/test_couchish_views.yaml
+couchish/tests/data/schemaish_jsonbuilder/test_sequence.yaml
+couchish/tests/data/schemaish_jsonbuilder/test_sequenceofstructures.yaml
+couchish/tests/data/schemaish_jsonbuilder/test_simple.yaml
+couchish/tests/data/schemaish_jsonbuilder/test_substructure.yaml
+couchish/tests/data/schemaish_jsonbuilder/test_types.yaml
+docs-build/Makefile
+docs-build/conf.py
+docs-build/future.rst
+docs-build/index.rst
+docs/doctrees/environment.pickle
+docs/doctrees/future.doctree
+docs/doctrees/index.doctree
+docs/html/future.html
+docs/html/genindex.html
+docs/html/index.html
+docs/html/objects.inv
+docs/html/search.html
+docs/html/searchindex.js
+docs/html/_sources/future.txt
+docs/html/_sources/index.txt
+docs/html/_static/contents.png
+docs/html/_static/default.css
+docs/html/_static/doctools.js
+docs/html/_static/file.png
+docs/html/_static/jquery.js
+docs/html/_static/minus.png
+docs/html/_static/navigation.png
+docs/html/_static/plus.png
+docs/html/_static/pygments.css
+docs/html/_static/rightsidebar.css
+docs/html/_static/searchtools.js
+docs/html/_static/sphinxdoc.css
+docs/html/_static/stickysidebar.css
+docs/html/_static/traditional.css
\ No newline at end of file
diff --git a/couchish.egg-info/requires.txt b/couchish.egg-info/requires.txt
new file mode 100644
index 0000000..a00502f
--- /dev/null
+++ b/couchish.egg-info/requires.txt
@@ -0,0 +1,2 @@
+PyYAML
+couchdb-session
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 813a22c..a5d2d67 100644
--- a/setup.py
+++ b/setup.py
@@ -1,27 +1,28 @@
from setuptools import setup, find_packages
import sys, os
version = '0.2'
setup(name='couchish',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Tim Parkin & Matt Goodall',
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
"PyYAML",
+ "couchdb-session",
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
ish/couchish
|
5c171fb300c13c20b896930dbf4bed39754150be
|
Add required package
|
diff --git a/setup.py b/setup.py
index cb46cb3..813a22c 100644
--- a/setup.py
+++ b/setup.py
@@ -1,26 +1,27 @@
from setuptools import setup, find_packages
import sys, os
version = '0.2'
setup(name='couchish',
version=version,
description="",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Tim Parkin & Matt Goodall',
author_email='[email protected]',
url='',
license='',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
+ "PyYAML",
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
ish/couchish
|
563c13f8474593b16f81c03426cc9859e92e0257
|
allow doc_by_view to be used without a key
|
diff --git a/couchish/store.py b/couchish/store.py
index 8ed333c..070190a 100644
--- a/couchish/store.py
+++ b/couchish/store.py
@@ -1,243 +1,252 @@
"""
Views we can build:
* by type, one view should be ok
* x_by_y views, from config (optional)
* ref and ref reversed views, one pair per relationship
"""
from couchdb.design import ViewDefinition
from couchdbsession import a8n, session
import schemaish.type
from couchish import filehandling, errors, jsonutil
class CouchishStore(object):
def __init__(self, db, config):
self.db = db
self.config = config
def sync_views(self):
for url, view in self.config.viewdata['views'].items():
segments = url.split('/')
designdoc = segments[0]
name = '/'.join(segments[1:])
view = ViewDefinition(designdoc, name, view[0], view[1])
view.get_doc(self.db)
view.sync(self.db)
def session(self):
"""
Create an editing session.
"""
return CouchishStoreSession(self)
class CouchishStoreSession(object):
def __init__(self, store):
self.store = store
self.session = Session(store.db,
pre_flush_hook=self._pre_flush_hook,
post_flush_hook=self._post_flush_hook,
encode_doc=jsonutil.encode_to_dict,
decode_doc=jsonutil.decode_from_dict)
self.file_additions = {}
self.file_deletions = {}
def __enter__(self):
"""
"with" statement entry.
"""
return self
def __exit__(self, type, value, traceback):
"""
"with" statement exit.
"""
if type is None:
self.flush()
else:
self.reset()
def create(self, doc):
"""
Create a document.
"""
return self.session.create(doc)
def delete(self, doc_or_tuple):
"""
Delete the given document.
"""
if isinstance(doc_or_tuple, tuple):
id, rev = doc_or_tuple
doc = {'_id': id, 'rev': rev}
else:
doc = doc_or_tuple
return self.session.delete(doc)
def get_attachment(self, id_or_doc, filename):
return self.session._db.get_attachment(id_or_doc, filename)
def put_attachment(self, doc, content, filename=None, content_type=None):
return self.session._db.put_attachment(doc, content,
filename=filename, content_type=content_type)
def delete_attachment(self, doc, filename):
return self.session._db.delete_attachment(doc, filename)
def doc_by_id(self, id):
"""
Return a single document, given it's ID.
"""
doc = self.session.get(id)
if doc is None:
raise errors.NotFound("No document with id %r" % (id,))
return doc
- def doc_by_view(self, view, key):
- results = self.session.view(view, startkey=key, endkey=key, limit=2,
+ def doc_by_view(self, view, key=None):
+ if key is not None:
+ results = self.session.view(view, startkey=key, endkey=key, limit=2,
include_docs=True)
+ else:
+ results = self.session.view(view, limit=2, include_docs=True)
rows = results.rows
if len(rows) == 0:
- raise errors.NotFound("No document in view %r with key %r" % (view, key))
+ message = "No document in view %r"%view
+ if key is not None:
+ message += " with key %r"%key
+ raise errors.NotFound(message)
elif len(rows) == 2:
- raise errors.TooMany("Too many documents in view %r for key %r" % (view, key))
+ message = "Too many documents in view %r"%view
+ if key is not None:
+ message += " with key %r"%key
+ raise errors.TooMany(message)
return rows[0].doc
def docs_by_id(self, ids, **options):
"""
Generate the sequence of documents with the given ids.
"""
options = dict(options)
options['keys'] = ids
options['include_docs'] = True
results = self.session.view('_all_docs', **options)
return (row.doc for row in results.rows)
def docs_by_type(self, type, **options):
"""
Generate the sequence of docs of a given type.
"""
options = dict(options)
options['include_docs'] = True
results = self.session.view('%s/all'%type, **options)
return (row.doc for row in results.rows)
def docs_by_view(self, view, **options):
options = dict(options)
options['include_docs'] = True
results = self.session.view(view, **options)
return (row.doc for row in results.rows)
def view(self, view, **options):
"""
Call and return a view.
"""
return self.session.view(view, **options)
def _pre_flush_hook(self, session, deletions, additions, changes):
file_deletions, file_additions = filehandling._parse_changes_for_files(session, deletions, additions, changes)
self.file_deletions.update(file_deletions)
self.file_additions.update(file_additions)
def flush(self):
"""
Flush the session.
"""
returnvalue = self.session.flush()
filehandling._handle_separate_attachments(self.session, self.file_deletions, self.file_additions)
self.file_additions = {}
self.file_deletions = {}
return returnvalue
def reset(self):
"""
Reset the session, forgetting everything it knows.
"""
self.session.reset()
def _post_flush_hook(self, session, deletions, additions, changes):
# Sentinel to indicate we haven't retrieved the ref view data yet.
NO_REF_DATA = object()
# Easy access to the config.
views_by_viewname = self.store.config.viewdata['views_by_viewname']
viewnames_by_attribute = self.store.config.viewdata['viewnames_by_attribute']
attributes_by_viewname = self.store.config.viewdata['attributes_by_viewname']
# Updates any documents that refer to documents that have been changed.
for doc, actions in changes:
doc_type = doc['model_type']
edited = set('.'.join([doc_type, '.'.join(str(p) for p in action['path'])])
for action in actions if action['action'] == 'edit')
# Build a set of all the views affected by the changed attributes.
views = set()
for attr in edited:
views.update(viewnames_by_attribute.get(attr, []))
for view in views:
# Lazy load the ref_data.
ref_data = NO_REF_DATA
attrs_by_type = attributes_by_viewname[view]
view_url = views_by_viewname[view]['url']
# XXX should build a full key here, but let's assume just the
# id for a moment.
ref_key = doc['_id']
for ref_doc in self.docs_by_view(view_url+'-rev', startkey=ref_key, endkey=ref_key):
# Fetch the ref data for this ref view, if we don't already
# have it.
if ref_data is NO_REF_DATA:
ref_data = self.view(view_url, startkey=ref_key, limit=1).rows[0].value
if isinstance(ref_data, dict):
ref_data['_ref'] = ref_key
else:
ref_data = {'_ref': ref_key, 'data': ref_data}
for attr in attrs_by_type[ref_doc['model_type']]:
# Any of the attrs sections could be a sequence.. we need to iterate over them all to find matches..
# e.g. we may have authors*. or metadata*.authors*
self._find_and_match_nested_item(ref_doc, attr.split('.'), ref_data)
def _find_and_match_nested_item(self, ref_doc, segments, ref_data, prefix=None):
# Initialise of copy the prefix list, because we're about to change it.
if prefix is None:
prefix = []
else:
prefix = list(prefix)
if segments == []:
if ref_doc['_ref'] == ref_data['_ref']:
ref_doc.update(ref_data)
else:
current, segments = segments[0], segments[1:]
if current.endswith('*'):
is_seq = True
else:
is_seq = False
current = current.replace('*','')
prefix.append(current)
current_ref = ref_doc.get(current)
if current_ref is None:
return
if is_seq:
for ref_doc_ref in current_ref:
self._find_and_match_nested_item(ref_doc_ref, segments, ref_data, prefix)
else:
self._find_and_match_nested_item(current_ref, segments, ref_data, prefix)
class Tracker(a8n.Tracker):
def _track(self, obj, path):
if isinstance(obj, (jsonutil.CouchishFile, schemaish.type.File)):
return obj
return super(Tracker, self)._track(obj, path)
class Session(session.Session):
tracker_factory = Tracker
|
ish/couchish
|
e3b3963d03498b2ec5acc98f5ed3710da2053980
|
added a sort option to selectchoicecouchdb
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index 249aae9..b0343d7 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,405 +1,409 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
from dottedish import get_dict_from_dotted_dict
from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
#self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
+ self.sort = k.pop('sort', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
+ if self.sort == True:
+ _options.sort(lambda x, y: cmp(x[1], y[1]))
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
def get_parent(segments):
if len(segments) == 1:
return ''
else:
return '.'.join(segments[:-1])
def mktree(options):
last_segments_len = 1
root = {'': {'data':('root', 'Root'), 'children':[]} }
for id, label in options:
segments = id.split('.')
parent = get_parent(segments)
root[id] = {'data': (id, label), 'children':[]}
root[parent]['children'].append(root[id])
return root['']
class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
_template='CheckboxMultiChoiceTreeCouchDB'
def __init__(self, full_options, cssClass=None):
self.options = [ (key, value['data']['label']) for key, value in full_options]
self.full_options = dict(full_options)
self.optiontree = mktree(self.options)
widgets.Widget.__init__(self,cssClass=cssClass)
def pre_render(self, schema_type, data):
if data is None:
return []
return [c['path'] for c in data]
def checked(self, option, values, schema_type):
if values is not None and option[0] in values:
return ' checked="checked"'
else:
return ''
def convert(self, schema_type, data):
out = []
for item in data:
out.append(self.full_options[item])
return out
class SeqRefTextArea(formish.Input):
"""
Textarea input field
:arg cols: set the cols attr on the textarea element
:arg rows: set the cols attr on the textarea element
"""
_template = 'SeqRefTextArea'
def __init__(self, db, view, **k):
self.cols = k.pop('cols', None)
self.rows = k.pop('rows', None)
self.strip = k.pop('strip', True)
self.db = db
self.view = view
formish.Input.__init__(self, **k)
if not self.converter_options.has_key('delimiter'):
self.converter_options['delimiter'] = '\n'
def pre_render(self, schema_type, data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
if data is None:
return []
string_data = [d['_ref'] for d in data]
return [string_data]
def convert(self, schema_type, request_data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
string_data = request_data[0]
if self.strip is True:
string_data = string_data.strip()
if string_data == '':
return self.empty
ids = [s.strip() for s in string_data.splitlines()]
docs = self.db.view(self.view, keys=ids)
out = []
for d in docs:
d.value.update({'_ref': d.key})
out.append(d.value)
return out
def __repr__(self):
attributes = []
if self.strip is False:
attributes.append('strip=%r'%self.strip)
if self.converter_options != {'delimiter':','}:
attributes.append('converter_options=%r'%self.converter_options)
if self.css_class:
attributes.append('css_class=%r'%self.css_class)
if self.empty is not None:
attributes.append('empty=%r'%self.empty)
return 'couchish_formish_jsonbuilder.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SeqRefTextArea'] = self.seqreftextarea_factory
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
+ k['sort'] = widget_spec.get('sort')
attr = spec.get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
def seqreftextarea_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
attr = spec.get('attr',{}).get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SeqRefTextArea(self.db, view, **k)
def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
facet = list(db.view(view, include_docs=True))[0].doc
options = []
for item in facet['category']:
options.append( (item['path'],item) )
return options
view = 'facet_%s/all'%widgetSpec['facet']
return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
|
ish/couchish
|
282fb9814f62ea7c676a3e4beb7c0bd246ce61c8
|
Fix value conversion
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index 249aae9..1e5c76f 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,405 +1,405 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
from dottedish import get_dict_from_dotted_dict
from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
#self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
def get_parent(segments):
if len(segments) == 1:
return ''
else:
return '.'.join(segments[:-1])
def mktree(options):
last_segments_len = 1
root = {'': {'data':('root', 'Root'), 'children':[]} }
for id, label in options:
segments = id.split('.')
parent = get_parent(segments)
root[id] = {'data': (id, label), 'children':[]}
root[parent]['children'].append(root[id])
return root['']
class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
_template='CheckboxMultiChoiceTreeCouchDB'
def __init__(self, full_options, cssClass=None):
self.options = [ (key, value['data']['label']) for key, value in full_options]
self.full_options = dict(full_options)
self.optiontree = mktree(self.options)
widgets.Widget.__init__(self,cssClass=cssClass)
def pre_render(self, schema_type, data):
if data is None:
return []
return [c['path'] for c in data]
def checked(self, option, values, schema_type):
if values is not None and option[0] in values:
return ' checked="checked"'
else:
return ''
def convert(self, schema_type, data):
out = []
for item in data:
out.append(self.full_options[item])
return out
class SeqRefTextArea(formish.Input):
"""
Textarea input field
:arg cols: set the cols attr on the textarea element
:arg rows: set the cols attr on the textarea element
"""
_template = 'SeqRefTextArea'
def __init__(self, db, view, **k):
self.cols = k.pop('cols', None)
self.rows = k.pop('rows', None)
self.strip = k.pop('strip', True)
self.db = db
self.view = view
formish.Input.__init__(self, **k)
if not self.converter_options.has_key('delimiter'):
self.converter_options['delimiter'] = '\n'
def pre_render(self, schema_type, data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
if data is None:
return []
string_data = [d['_ref'] for d in data]
- return [string_data]
+ return string_data
def convert(self, schema_type, request_data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
string_data = request_data[0]
if self.strip is True:
string_data = string_data.strip()
if string_data == '':
return self.empty
ids = [s.strip() for s in string_data.splitlines()]
docs = self.db.view(self.view, keys=ids)
out = []
for d in docs:
d.value.update({'_ref': d.key})
out.append(d.value)
return out
def __repr__(self):
attributes = []
if self.strip is False:
attributes.append('strip=%r'%self.strip)
if self.converter_options != {'delimiter':','}:
attributes.append('converter_options=%r'%self.converter_options)
if self.css_class:
attributes.append('css_class=%r'%self.css_class)
if self.empty is not None:
attributes.append('empty=%r'%self.empty)
return 'couchish_formish_jsonbuilder.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SeqRefTextArea'] = self.seqreftextarea_factory
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
attr = spec.get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
def seqreftextarea_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
attr = spec.get('attr',{}).get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SeqRefTextArea(self.db, view, **k)
def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
facet = list(db.view(view, include_docs=True))[0].doc
options = []
for item in facet['category']:
options.append( (item['path'],item) )
return options
view = 'facet_%s/all'%widgetSpec['facet']
return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
|
ish/couchish
|
8ca4cff44e580983ae4326a4d94188b47a7f7327
|
fix for reference data in SeqRefTA
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index c5f134b..249aae9 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,404 +1,405 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
from dottedish import get_dict_from_dotted_dict
from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
#self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
def get_parent(segments):
if len(segments) == 1:
return ''
else:
return '.'.join(segments[:-1])
def mktree(options):
last_segments_len = 1
root = {'': {'data':('root', 'Root'), 'children':[]} }
for id, label in options:
segments = id.split('.')
parent = get_parent(segments)
root[id] = {'data': (id, label), 'children':[]}
root[parent]['children'].append(root[id])
return root['']
class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
_template='CheckboxMultiChoiceTreeCouchDB'
def __init__(self, full_options, cssClass=None):
self.options = [ (key, value['data']['label']) for key, value in full_options]
self.full_options = dict(full_options)
self.optiontree = mktree(self.options)
widgets.Widget.__init__(self,cssClass=cssClass)
def pre_render(self, schema_type, data):
if data is None:
return []
return [c['path'] for c in data]
def checked(self, option, values, schema_type):
if values is not None and option[0] in values:
return ' checked="checked"'
else:
return ''
def convert(self, schema_type, data):
out = []
for item in data:
out.append(self.full_options[item])
return out
class SeqRefTextArea(formish.Input):
"""
Textarea input field
:arg cols: set the cols attr on the textarea element
:arg rows: set the cols attr on the textarea element
"""
_template = 'SeqRefTextArea'
def __init__(self, db, view, **k):
self.cols = k.pop('cols', None)
self.rows = k.pop('rows', None)
self.strip = k.pop('strip', True)
self.db = db
self.view = view
formish.Input.__init__(self, **k)
if not self.converter_options.has_key('delimiter'):
self.converter_options['delimiter'] = '\n'
def pre_render(self, schema_type, data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
if data is None:
return []
string_data = [d['_ref'] for d in data]
return [string_data]
def convert(self, schema_type, request_data):
"""
We're using the converter options to allow processing sequence data
using the csv module
"""
string_data = request_data[0]
if self.strip is True:
string_data = string_data.strip()
if string_data == '':
return self.empty
ids = [s.strip() for s in string_data.splitlines()]
docs = self.db.view(self.view, keys=ids)
out = []
for d in docs:
- out.append( {'_ref': d.key, 'data': d.value} )
+ d.value.update({'_ref': d.key})
+ out.append(d.value)
return out
def __repr__(self):
attributes = []
if self.strip is False:
attributes.append('strip=%r'%self.strip)
if self.converter_options != {'delimiter':','}:
attributes.append('converter_options=%r'%self.converter_options)
if self.css_class:
attributes.append('css_class=%r'%self.css_class)
if self.empty is not None:
attributes.append('empty=%r'%self.empty)
return 'couchish_formish_jsonbuilder.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SeqRefTextArea'] = self.seqreftextarea_factory
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
attr = spec.get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
def seqreftextarea_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
attr = spec.get('attr',{}).get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SeqRefTextArea(self.db, view, **k)
def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
facet = list(db.view(view, include_docs=True))[0].doc
options = []
for item in facet['category']:
options.append( (item['path'],item) )
return options
view = 'facet_%s/all'%widgetSpec['facet']
return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
|
ish/couchish
|
b11520186041bbe1af521bb5102ade7d12daefba
|
added SeqRefTextArea
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index a4b93e1..c5f134b 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,308 +1,404 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
from dottedish import get_dict_from_dotted_dict
from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
#self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
+
+
+def get_parent(segments):
+ if len(segments) == 1:
+ return ''
+ else:
+ return '.'.join(segments[:-1])
+
+def mktree(options):
+ last_segments_len = 1
+ root = {'': {'data':('root', 'Root'), 'children':[]} }
+ for id, label in options:
+ segments = id.split('.')
+ parent = get_parent(segments)
+ root[id] = {'data': (id, label), 'children':[]}
+ root[parent]['children'].append(root[id])
+ return root['']
+
class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
_template='CheckboxMultiChoiceTreeCouchDB'
def __init__(self, full_options, cssClass=None):
self.options = [ (key, value['data']['label']) for key, value in full_options]
self.full_options = dict(full_options)
- self.optiontree = get_dict_from_dotted_dict(dict(self.options),noexcept=True)
+ self.optiontree = mktree(self.options)
widgets.Widget.__init__(self,cssClass=cssClass)
def pre_render(self, schema_type, data):
if data is None:
return []
return [c['path'] for c in data]
def checked(self, option, values, schema_type):
if values is not None and option[0] in values:
return ' checked="checked"'
else:
return ''
def convert(self, schema_type, data):
out = []
for item in data:
out.append(self.full_options[item])
return out
+class SeqRefTextArea(formish.Input):
+ """
+ Textarea input field
+
+ :arg cols: set the cols attr on the textarea element
+ :arg rows: set the cols attr on the textarea element
+ """
+
+ _template = 'SeqRefTextArea'
+
+ def __init__(self, db, view, **k):
+ self.cols = k.pop('cols', None)
+ self.rows = k.pop('rows', None)
+ self.strip = k.pop('strip', True)
+ self.db = db
+ self.view = view
+ formish.Input.__init__(self, **k)
+ if not self.converter_options.has_key('delimiter'):
+ self.converter_options['delimiter'] = '\n'
+
+ def pre_render(self, schema_type, data):
+ """
+ We're using the converter options to allow processing sequence data
+ using the csv module
+ """
+ if data is None:
+ return []
+ string_data = [d['_ref'] for d in data]
+ return [string_data]
+
+ def convert(self, schema_type, request_data):
+ """
+ We're using the converter options to allow processing sequence data
+ using the csv module
+ """
+ string_data = request_data[0]
+ if self.strip is True:
+ string_data = string_data.strip()
+ if string_data == '':
+ return self.empty
+ ids = [s.strip() for s in string_data.splitlines()]
+ docs = self.db.view(self.view, keys=ids)
+ out = []
+ for d in docs:
+ out.append( {'_ref': d.key, 'data': d.value} )
+ return out
+
+ def __repr__(self):
+ attributes = []
+ if self.strip is False:
+ attributes.append('strip=%r'%self.strip)
+ if self.converter_options != {'delimiter':','}:
+ attributes.append('converter_options=%r'%self.converter_options)
+ if self.css_class:
+ attributes.append('css_class=%r'%self.css_class)
+ if self.empty is not None:
+ attributes.append('empty=%r'%self.empty)
+
+ return 'couchish_formish_jsonbuilder.%s(%s)'%(self.__class__.__name__, ', '.join(attributes))
+
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
+ self.registry['SeqRefTextArea'] = self.seqreftextarea_factory
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
attr = spec.get('attr',{})
if attr is None:
refersto = None
else:
refersto = attr.get('refersto')
view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
+ def seqreftextarea_factory(self, spec, k):
+ if spec is None:
+ spec = {}
+ widget_spec = spec.get('widget')
+ if widget_spec is None:
+ widget_spec = {}
+ attr = spec.get('attr',{}).get('attr',{})
+ if attr is None:
+ refersto = None
+ else:
+ refersto = attr.get('refersto')
+ view = widget_spec.get('view', refersto)
+ return SeqRefTextArea(self.db, view, **k)
+
def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
facet = list(db.view(view, include_docs=True))[0].doc
options = []
for item in facet['category']:
options.append( (item['path'],item) )
return options
view = 'facet_%s/all'%widgetSpec['facet']
return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
+
+
+
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
|
ish/couchish
|
49e52fe3ff510eb85ef0f17284728020617039dd
|
added a facet category checkbox multi choice tree widget
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index 55a5854..a4b93e1 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,265 +1,308 @@
import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
from formish import widgets, filestore, safefilename
from PIL import Image
from schemaish.type import File as SchemaFile
+from dottedish import get_dict_from_dotted_dict
+from convertish.convert import string_converter
def get_size(filename):
IDENTIFY = '/usr/bin/identify'
stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
- print '#################',stdout
if 'JPEG' in stdout:
type = 'JPEG'
if 'PNG' in stdout:
type = 'PNG'
if 'GIF' in stdout:
type = 'GIF'
dims = stdout.split(type)[1].split(' ')[1]
width, height = [int(s) for s in dims.split('x')]
return width, height
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
- self.uses = k['attr']['uses']
+ #self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
class FileUpload(formish.FileUpload):
def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
self.identify_size = identify_size
def pre_parse_request(self, schema_type, data, full_request_data):
"""
File uploads are wierd; in out case this means assymetric. We store the
file in a temporary location and just store an identifier in the field.
This at least makes the file look symmetric.
"""
if data.get('remove', [None])[0] is not None:
data['name'] = ['']
data['mimetype'] = ['']
return data
fieldstorage = data.get('file', [''])[0]
if getattr(fieldstorage,'file',None):
filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
data['name'] = [filename]
data['mimetype'] = [fieldstorage.type]
- if self.identify_size is True:
+ if self.identify_size is True and fieldstorage != '':
fieldstorage.file.seek(0)
width, height = Image.open(fieldstorage.file).size
- print 'WH',width,height
data['width'] = [width]
data['height'] = [height]
return data
def convert(self, schema_type, request_data):
"""
Creates a File object if possible
"""
# XXX We could add a file converter that converts this to a string data?
if request_data['name'] == ['']:
return None
elif request_data['name'] == request_data['default']:
- return ImageFile(None, None, None)
+ return SchemaFile(None, None, None)
else:
filename = request_data['name'][0]
try:
content_type, cache_tag, f = self.filestore.get(filename)
except KeyError:
return None
if self.identify_size == True:
metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
else:
metadata = None
return SchemaFile(f, filename, content_type, metadata=metadata)
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
+class CheckboxMultiChoiceTreeCouchDB(formish.CheckboxMultiChoiceTree):
+ _template='CheckboxMultiChoiceTreeCouchDB'
+
+ def __init__(self, full_options, cssClass=None):
+ self.options = [ (key, value['data']['label']) for key, value in full_options]
+ self.full_options = dict(full_options)
+ self.optiontree = get_dict_from_dotted_dict(dict(self.options),noexcept=True)
+ widgets.Widget.__init__(self,cssClass=cssClass)
+
+ def pre_render(self, schema_type, data):
+ if data is None:
+ return []
+ return [c['path'] for c in data]
+
+ def checked(self, option, values, schema_type):
+ if values is not None and option[0] in values:
+ return ' checked="checked"'
+ else:
+ return ''
+
+ def convert(self, schema_type, data):
+ out = []
+ for item in data:
+ out.append(self.full_options[item])
+ return out
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
+ self.registry['CheckboxMultiChoiceTreeCouchDBFacet'] = self.checkboxmultichoicetree_couchdbfacet_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
- view = widget_spec.get('view', spec.get('attr',{}).get('refersto'))
+ attr = spec.get('attr',{})
+ if attr is None:
+ refersto = None
+ else:
+ refersto = attr.get('refersto')
+ view = widget_spec.get('view', refersto)
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
+ def checkboxmultichoicetree_couchdbfacet_factory(self, spec, k):
+ widgetSpec = spec.get('widget')
+ def options(db, view):
+ facet = list(db.view(view, include_docs=True))[0].doc
+ options = []
+ for item in facet['category']:
+ options.append( (item['path'],item) )
+ return options
+ view = 'facet_%s/all'%widgetSpec['facet']
+
+ return CheckboxMultiChoiceTreeCouchDB(full_options=options(self.db,view), **k)
+
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
identify_size = widget_spec.get('options',{}).get('identify_size',False)
return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
|
ish/couchish
|
d807111a092e56212d86d1c9ef8725923d980645
|
uses should appear within the attr block, not as a root level field element
|
diff --git a/couchish/couchish_jsonbuilder.py b/couchish/couchish_jsonbuilder.py
index 4b1cb9c..87dc959 100644
--- a/couchish/couchish_jsonbuilder.py
+++ b/couchish/couchish_jsonbuilder.py
@@ -1,194 +1,194 @@
from sets import Set
from couchish.create_view import getjs
from couchish.schemaish_jsonbuilder import strip_stars
from string import Template
def buildview(view):
"""
function (doc) {
if (doc.model_type == 'book'){
for (var i1 in doc.metadata) {
for (var i2 in doc.metadata[i1].authors) {
emit(doc.metadata[i1].authors[i2]._ref, null);
}
}
}
}
"""
main_template = Template( \
""" function (doc) {
$body
}""")
if_template = Template( \
""" if (doc.model_type == '$type'){
$body
}
""")
for_template = Template( \
""" for (var i$n in doc$attr) {
$body
}""")
emit_template = Template( \
""" emit(doc$attr._ref, null);""")
out = ''
for type, attrs in view.items():
out_fors = ''
for attr in attrs:
templ_if = if_template.substitute({'type': type, 'body':'$body'})
segments = attr.replace('.*','*').split('.')
cleansegments = attr.replace('.*','').split('.')
out_attr = ''
templ_fors = '$body\n'
for n,segment in enumerate(segments):
if segment.endswith('*'):
out_loop_var = out_attr + '.%s'%cleansegments[n]
out_attr += '.%s[i%s]'%(cleansegments[n], n)
templ_for = for_template.substitute(n=n, attr=out_loop_var, body='$body')
templ_fors = Template(templ_fors).substitute(body=templ_for)
else:
out_attr += '.%s'%cleansegments[n]
out_emit = emit_template.substitute(attr=out_attr)
out_fors += Template(templ_fors).substitute(body=out_emit)
out += Template(templ_if).substitute(body=out_fors)
return (main_template.substitute(body=out), None)
def build_refersto_view(uses):
model_types = set()
if isinstance(uses, basestring):
model_type = uses.split('.')[0]
uses = [uses]
else:
for use in uses:
mt = use.split('.')[0]
model_types.add(mt)
if len(model_types) > 1:
raise ValueError('Can only use one model type in "uses" at the moment')
model_type = list(model_types)[0]
viewdef = 'function (doc) {\n'
viewdef += ' if (doc.model_type == \''+model_type+'\'){\n'
viewdef += ' emit(doc._id, %s )\n'%getjs(uses)
viewdef += ' }\n'
viewdef += '}\n'
return viewdef
def get_view(view, views, views_by_viewname, model_type=None):
if model_type is None:
# Then we have to have an explicit model type set if we want to use auto built views
model_type = view.get('model_type')
if 'designdoc' not in view:
# Then we use the type as the design doc
view['designdoc'] = model_type
if 'map' in view:
# Then we have explicit javascript functions
map = view['map']
reduce = view.get('reduce')
elif 'type' in view:
# Then we're auto building views if possible
if 'name' not in view:
# Use the view type for the name
view['name'] = view['type']
if view['type'] == 'all':
map, reduce = ("function(doc) { if (doc.model_type == '%s') { emit(doc._id, null); } }"%model_type,None)
if view['type'] == 'all_count':
map, reduce = ("function(doc) { if (doc.model_type == '%s') { emit(doc._id, 1); } }"%model_type, "function(keys, values) { return sum(values); }")
else:
map = build_refersto_view(view['uses'])
reduce = view.get('reduce')
if 'url' not in view:
# Then we need to provide one
if view['designdoc'] is None:
# Then we use the couchish namespace
raise KeyError('Cannot work out a design doc for view %s'%view.get('name'))
else:
view['url'] = '%s/%s'%(view['designdoc'],view['name'])
views_by_viewname[view['url']] = {'url':view['url'], 'key': view.get('key','_id'), 'uses': view.get('uses')}
views_by_viewname[view['url']]['map'] = (map,reduce)
views[view['url']] = (map,reduce)
def get_views(models_definition, views_definition):
views = {}
views_by_viewname = {}
views_by_uses = {}
viewnames_by_attribute = {}
attributes_by_viewname = {}
for view in views_definition:
get_view(view, views, views_by_viewname)
for model_type, definition in models_definition.items():
for view in definition.get('views',[]):
get_view(view, views, views_by_viewname, model_type=model_type)
parents = []
field_to_view = {}
for model_type, definition in models_definition.items():
for field in definition['fields']:
# some uses need to know whether the attr is composed of any sequences
field['key'] = strip_stars(field['name'])
if field.get('type','').startswith('Sequence'):
fieldname = '%s.*'%field['name']
else:
fieldname = field['name']
# If we have any references, build the appropriate lookups
if 'attr' in field and 'refersto' in field['attr']:
refersto = field['attr']['refersto']
view = views_by_viewname[refersto]
- if 'uses' in field:
- uses = field['uses']
+ if 'uses' in field['attr']:
+ uses = field['attr']['uses']
else:
uses = view['uses']
# Build the reference views dynamically if not explicit
if isinstance(uses, basestring):
views_by_uses.setdefault(view['url']+'-rev',{}).setdefault(model_type,[]).append( fieldname )
viewnames_by_attribute.setdefault(uses, Set()).add(refersto)
attributes_by_viewname.setdefault(refersto, {}).setdefault(model_type,Set()).add( fieldname.replace('.*','*') )
else:
views_by_uses.setdefault(view['url']+'-rev',{}).setdefault(model_type,[]).append( fieldname )
attributes_by_viewname.setdefault(refersto, {}).setdefault(model_type,Set()).add( fieldname.replace('.*','*') )
for use in uses:
viewnames_by_attribute.setdefault(use, Set()).add(refersto)
# Create any 'viewby' views
if 'viewby' in field:
if '*' in fieldname:
raise Exception('Can\'t generate viewby views on attributes in sequences')
if field['viewby'] == True:
url = '%s/by_%s'%(model_type,fieldname)
else:
url = field['viewby']
views[url] = ("function(doc) { if (doc.model_type=='%s') { emit(doc.%s, null ); } }"%(model_type,field['name']),None)
if 'viewby_count' in field:
if field['viewby_count'] == True:
url = '%s/by_%s_count'%(model_type,fieldname)
else:
url = field['viewby_count']
views[url] = ("function(doc) { if (doc.model_type == '%s') { emit(doc._id, 1); } }"%model_type, "function(keys, values) { return sum(values); }")
# Generate dynamic views for reference reverse lookups
for url, view in views_by_uses.items():
views[url] = buildview(view)
out = {'views': views,'views_by_viewname': views_by_viewname, 'viewnames_by_attribute': viewnames_by_attribute, 'attributes_by_viewname':attributes_by_viewname,'views_by_uses':views_by_uses}
return out
|
ish/couchish
|
64e7cb91f9d2bfbe758d6c67a7fae7056c959195
|
allow files without metadata attached for legacy stuff
|
diff --git a/couchish/filehandling.py b/couchish/filehandling.py
index ed42924..e4a1f32 100644
--- a/couchish/filehandling.py
+++ b/couchish/filehandling.py
@@ -1,211 +1,211 @@
"""
Views we can build:
* by type, one view should be ok
* x_by_y views, from config (optional)
* ref and ref reversed views, one pair per relationship
"""
from dottedish import dotted
import base64
import uuid
from schemaish.type import File
from StringIO import StringIO
import shutil
from couchish import jsonutil
def get_attr(prefix, parent=None):
# combine prefix and parent where prefix is a list and parent is a dotted string
if parent is None:
segments = [str(segment) for segment in prefix]
return '.'.join(segments)
if prefix is None:
return parent
segments = [str(segment) for segment in prefix]
if parent != '':
segments += parent.split('.')
attr = '.'.join( segments )
return attr
def get_files(data, original=None, prefix=None):
# scan old data to collect any file refs and then scan new data for file changes
files = {}
inlinefiles = {}
original_files = {}
get_files_from_original(data, original, files, inlinefiles, original_files, prefix)
get_files_from_data(data, original, files, inlinefiles, original_files, prefix)
return data, files, inlinefiles, original_files
def has_unmodified_signature(f):
if f.file is None:
return True
return False
def make_dotted_or_emptydict(d):
if isinstance(d, dict):
return dotted(d)
return dotted({})
def get_files_from_data(data, original, files, inlinefiles, original_files, prefix):
if isinstance(data, File):
get_file_from_item(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(data, dict):
return
dd = dotted(data)
ddoriginal = make_dotted_or_emptydict(original)
for k,f in dd.dotteditems():
if isinstance(f, File):
if isinstance(ddoriginal.get(k), File):
of = ddoriginal[k]
else:
of = None
get_file_from_item(f, of, files, inlinefiles, original_files, get_attr(prefix, k))
def get_file_from_item(f, of, files, inlinefiles, original_files, fullprefix):
if f.file is None:
# if we have no original data then we presume the file should remain unchanged
f.id = of.id
if f.mimetype is None:
f.mimetype = of.mimetype
if f.filename is None:
f.filename = of.filename
- if f.metadata is None:
+ if not hasattr(f, 'metadata') or f.metadata is None:
f.metadata = getattr(of, 'metadata', None)
else:
if of and hasattr(of,'id'):
f.id = of.id
else:
f.id = uuid.uuid4().hex
if getattr(f,'inline',False) is True:
filestore = inlinefiles
else:
filestore = files
if hasattr(f, 'inline'):
del f.inline
# add the files for attachment handling and remove the file data from document
if getattr(f,'b64', None):
filestore[fullprefix] = jsonutil.CouchishFile(f.file, f.filename, f.mimetype, f.id, metadata = f.metadata, b64=True)
del f.b64
else:
fh = StringIO()
shutil.copyfileobj(f.file, fh)
fh.seek(0)
filestore[fullprefix] = jsonutil.CouchishFile(fh, f.filename, f.mimetype, f.id, metadata = f.metadata)
del f.file
def get_file_from_original(f, of, files, inlinefiles, original_files, fullprefix):
if not isinstance(f, File):
original_files[fullprefix] = of
def get_files_from_original(data, original, files, inlinefiles, original_files, prefix):
if isinstance(original, File):
get_file_from_original(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(original, dict):
return
dd = make_dotted_or_emptydict(data)
ddoriginal = dotted(original)
for k, of in ddoriginal.dotteditems():
if isinstance(of, File):
f = dd.get(k)
get_file_from_original(f, of, files, inlinefiles, original_files, get_attr(prefix, kparent))
def _parse_changes_for_files(session, deletions, additions, changes):
""" returns deletions, additions """
additions = list(additions)
changes = list(changes)
deletions = list(deletions)
all_separate_files = {}
all_inline_files = {}
for addition in additions:
addition, files, inlinefiles, original_files_notused = get_files(addition)
if files:
all_separate_files.setdefault(addition['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(addition['_id'],{}).update(inlinefiles)
_extract_inline_attachments(addition, inlinefiles)
all_original_files = {}
changes = list(changes)
for n, changeset in enumerate(changes):
d, cs = changeset
cs = list(cs)
for m, c in enumerate(cs):
if c['action'] in ['edit','create','remove']:
c['value'], files, inlinefiles, original_files = get_files(c.get('value'), original=c.get('was'), prefix=c['path'])
cs[m] = c
if files:
all_separate_files.setdefault(d['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(d['_id'],{}).update(inlinefiles)
all_original_files.setdefault(d['_id'], {}).update(original_files)
_extract_inline_attachments(d, inlinefiles)
changes[n] = (d, cs)
return all_original_files, all_separate_files
def _extract_inline_attachments(doc, files):
"""
Move the any attachment data that we've found into the _attachments attribute
"""
for attr, f in files.items():
if f.b64:
data = f.file.replace('\n', '')
else:
data = base64.encodestring(f.file.read()).replace('\n','')
f.file.close()
del f.file
del f.b64
del f.inline
del f.doc_id
doc.setdefault('_attachments',{})[f.id] = {'content_type': f.mimetype,'data': data}
def _handle_separate_attachments(session, deletions, additions):
"""
add attachments that aren't inline and remove any attachments without references
"""
# XXX This needs to cope with files moving when sequences are re-numbered. We need
# XXX to talk to matt about what a renumbering like this looks like
for id, attrfiles in additions.items():
doc = session.get(id)
for attr, f in attrfiles.items():
data = ''
if f.file:
if f.b64:
data = base64.decodestring(f.file)
else:
data = f.file.read()
f.file.close()
session._db.put_attachment({'_id':doc['_id'], '_rev':doc['_rev']}, data, filename=f.id, content_type=f.mimetype)
del f.file
del f.b64
del f.inline
del f.doc_id
for id, attrfiles in deletions.items():
# XXX had to use _db because delete attachment freeaked using session version.
doc = session._db.get(id)
for attr, f in attrfiles.items():
session._db.delete_attachment(doc, f.id)
additions = {}
deletions = {}
|
ish/couchish
|
e6fc2e8ff4f71a87df741fb30aa3e6b7b8b29268
|
added metadata to couchish file
|
diff --git a/couchish/couchish_formish_jsonbuilder.py b/couchish/couchish_formish_jsonbuilder.py
index 119b6b8..55a5854 100644
--- a/couchish/couchish_formish_jsonbuilder.py
+++ b/couchish/couchish_formish_jsonbuilder.py
@@ -1,191 +1,265 @@
-import schemaish, formish
+import schemaish, formish, subprocess, uuid, os
from jsonish import pythonjson as json
from couchish.formish_jsonbuilder import build as formish_build
from couchish.schemaish_jsonbuilder import SchemaishTypeRegistry
from couchish.formish_jsonbuilder import FormishWidgetRegistry
-from formish import widgets, filestore
+from formish import widgets, filestore, safefilename
+from PIL import Image
+from schemaish.type import File as SchemaFile
+
+def get_size(filename):
+ IDENTIFY = '/usr/bin/identify'
+ stdout = subprocess.Popen([IDENTIFY, filename], stdout=subprocess.PIPE).communicate()[0]
+ print '#################',stdout
+ if 'JPEG' in stdout:
+ type = 'JPEG'
+ if 'PNG' in stdout:
+ type = 'PNG'
+ if 'GIF' in stdout:
+ type = 'GIF'
+ dims = stdout.split(type)[1].split(' ')[1]
+ width, height = [int(s) for s in dims.split('x')]
+ return width, height
+
class Reference(schemaish.attr.Attribute):
""" a generic reference
"""
def __init__(self, **k):
self.refersto = k['attr']['refersto']
self.uses = k['attr']['uses']
schemaish.attr.Attribute.__init__(self,**k)
class TypeRegistry(SchemaishTypeRegistry):
def __init__(self):
SchemaishTypeRegistry.__init__(self)
self.registry['Reference'] = self.reference_factory
def reference_factory(self, field):
return Reference(**field)
UNSET = object()
+class FileUpload(formish.FileUpload):
+
+ def __init__(self, filestore, show_file_preview=True, show_download_link=False, show_image_thumbnail=False, url_base=None, \
+ css_class=None, image_thumbnail_default=None, url_ident_factory=None, identify_size=False):
+ formish.FileUpload.__init__(self, filestore, show_file_preview=show_file_preview, show_download_link=show_download_link, \
+ show_image_thumbnail=show_image_thumbnail, url_base=url_base, css_class=css_class, image_thumbnail_default=image_thumbnail_default, url_ident_factory=url_ident_factory)
+ self.identify_size = identify_size
+
+ def pre_parse_request(self, schema_type, data, full_request_data):
+ """
+ File uploads are wierd; in out case this means assymetric. We store the
+ file in a temporary location and just store an identifier in the field.
+ This at least makes the file look symmetric.
+ """
+ if data.get('remove', [None])[0] is not None:
+ data['name'] = ['']
+ data['mimetype'] = ['']
+ return data
+
+ fieldstorage = data.get('file', [''])[0]
+ if getattr(fieldstorage,'file',None):
+ filename = '%s-%s'%(uuid.uuid4().hex,fieldstorage.filename)
+ self.filestore.put(filename, fieldstorage.file, fieldstorage.type, uuid.uuid4().hex)
+ data['name'] = [filename]
+ data['mimetype'] = [fieldstorage.type]
+ if self.identify_size is True:
+ fieldstorage.file.seek(0)
+ width, height = Image.open(fieldstorage.file).size
+ print 'WH',width,height
+ data['width'] = [width]
+ data['height'] = [height]
+ return data
+
+ def convert(self, schema_type, request_data):
+ """
+ Creates a File object if possible
+ """
+ # XXX We could add a file converter that converts this to a string data?
+
+ if request_data['name'] == ['']:
+ return None
+ elif request_data['name'] == request_data['default']:
+ return ImageFile(None, None, None)
+ else:
+ filename = request_data['name'][0]
+ try:
+ content_type, cache_tag, f = self.filestore.get(filename)
+ except KeyError:
+ return None
+ if self.identify_size == True:
+ metadata = {'width':request_data['width'][0], 'height': request_data['height'][0]}
+ else:
+ metadata = None
+ return SchemaFile(f, filename, content_type, metadata=metadata)
+
class SelectChoiceCouchDB(widgets.Widget):
none_option = (None, '- choose -')
_template='SelectChoice'
def __init__(self, db, view, label_template, **k):
"""
:arg options: either a list of values ``[value,]`` where value is used for the label or a list of tuples of the form ``[(value, label),]``
:arg none_option: a tuple of ``(value, label)`` to use as the unselected option
:arg css_class: a css class to apply to the field
"""
none_option = k.pop('none_option', UNSET)
if none_option is not UNSET:
self.none_option = none_option
widgets.Widget.__init__(self, **k)
self.db = db
self.view = view
self.label_template = label_template
self.options = None
self.results = None
def selected(self, option, value, schemaType):
if value == '':
v = self.empty
else:
v = value
if option[0] == v:
return ' selected="selected"'
else:
return ''
def pre_render(self, schema_type, data):
"""
Before the widget is rendered, the data is converted to a string
format.If the data is None then we return an empty string. The sequence
is request data representation.
"""
if data is None:
return ['']
string_data = data.get('_ref')
return [string_data]
def convert(self, schema_type, request_data):
"""
after the form has been submitted, the request data is converted into
to the schema type.
"""
self.get_options()
string_data = request_data[0]
if string_data == '':
return self.empty
result = self.results[string_data]
if isinstance(result, dict):
result['_ref'] = string_data
return result
else:
return {'_ref':string_data, 'data':result}
def get_none_option_value(self, schema_type):
"""
Get the default option (the 'unselected' option)
"""
none_option = self.none_option[0]
if none_option is self.empty:
return ''
return none_option
def get_options(self, schema_type=None):
"""
Return all of the options for the widget
"""
if self.options is not None:
return self.options
results = [json.decode_from_dict(item) for item in self.db.view(self.view)]
self.results = dict((result['id'], result['value']) for result in results)
_options = [ (result['id'], self.label_template%result['value']) for result in results]
self.options = []
for (value, label) in _options:
if value == self.empty:
self.options.append( ('',label) )
else:
self.options.append( (value,label) )
return self.options
class WidgetRegistry(FormishWidgetRegistry):
def __init__(self, db=None):
self.db = db
FormishWidgetRegistry.__init__(self)
self.registry['SelectChoiceCouchDB'] = self.selectchoice_couchdb_factory
self.registry['CheckboxMultiChoiceTreeCouchDB'] = self.checkboxmultichoicetree_couchdb_factory
self.defaults['Reference'] = self.selectchoice_couchdb_factory
def selectchoice_couchdb_factory(self, spec, k):
if spec is None:
spec = {}
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
label_template = widget_spec.get('label', '%s')
view = widget_spec.get('view', spec.get('attr',{}).get('refersto'))
return SelectChoiceCouchDB(self.db, view, label_template, **k)
def checkboxmultichoicetree_couchdb_factory(self, spec, k):
widgetSpec = spec.get('widget')
def options(db, view):
return [(item.id,item.doc['label']) for item in list(db.view(view, include_docs=True))]
view = widgetSpec['options']
return formish.CheckboxMultiChoiceTree(options=options(self.db,view), **k)
def fileupload_factory(self, spec, k):
widget_spec = spec.get('widget')
if widget_spec is None:
widget_spec = {}
def url_ident_factory(obj):
if isinstance(obj,schemaish.type.File):
return '%s/%s'%(obj.doc_id, obj.id)
elif obj:
return obj
else:
return None
root_dir = widget_spec.get('options',{}).get('root_dir',None)
url_base = widget_spec.get('options',{}).get('url_base',None)
image_thumbnail_default = widget_spec.get('image_thumbnail_default','/images/missing-image.jpg')
show_download_link = widget_spec.get('options',{}).get('show_download_link',False)
show_file_preview = widget_spec.get('options',{}).get('show_file_preview',True)
show_image_thumbnail = widget_spec.get('options',{}).get('show_image_thumbnail',False)
- return formish.FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
+ identify_size = widget_spec.get('options',{}).get('identify_size',False)
+ return FileUpload(filestore.CachedTempFilestore(root_dir=root_dir), \
url_base=url_base,
image_thumbnail_default=image_thumbnail_default,
show_download_link=show_download_link,
show_file_preview=show_file_preview,
show_image_thumbnail=show_image_thumbnail,
url_ident_factory=url_ident_factory,
+ identify_size=identify_size,
**k )
def build(definition, db=None, name=None, defaults=None, errors=None, action='', widget_registry=None, type_registry=None, add_id_and_rev=False):
if widget_registry is None:
widget_registry=WidgetRegistry(db)
if type_registry is None:
type_registry=TypeRegistry()
if add_id_and_rev is True:
# Copy the definition fict and its fields item so we can make changes
# without affecting the spec.
definition = dict(definition)
definition['fields'] = list(definition['fields'])
definition['fields'].insert(0, {'name': '_rev', 'widget':{'type': 'Hidden'}})
definition['fields'].insert(0, {'name': '_id', 'widget':{'type': 'Hidden'}})
form = formish_build(definition, name=name, defaults=defaults, errors=errors, action=action, widget_registry=widget_registry, type_registry=type_registry)
return form
diff --git a/couchish/filehandling.py b/couchish/filehandling.py
index 9013e26..ed42924 100644
--- a/couchish/filehandling.py
+++ b/couchish/filehandling.py
@@ -1,209 +1,211 @@
"""
Views we can build:
* by type, one view should be ok
* x_by_y views, from config (optional)
* ref and ref reversed views, one pair per relationship
"""
from dottedish import dotted
import base64
import uuid
from schemaish.type import File
from StringIO import StringIO
import shutil
from couchish import jsonutil
def get_attr(prefix, parent=None):
# combine prefix and parent where prefix is a list and parent is a dotted string
if parent is None:
segments = [str(segment) for segment in prefix]
return '.'.join(segments)
if prefix is None:
return parent
segments = [str(segment) for segment in prefix]
if parent != '':
segments += parent.split('.')
attr = '.'.join( segments )
return attr
def get_files(data, original=None, prefix=None):
# scan old data to collect any file refs and then scan new data for file changes
files = {}
inlinefiles = {}
original_files = {}
get_files_from_original(data, original, files, inlinefiles, original_files, prefix)
get_files_from_data(data, original, files, inlinefiles, original_files, prefix)
return data, files, inlinefiles, original_files
def has_unmodified_signature(f):
if f.file is None:
return True
return False
def make_dotted_or_emptydict(d):
if isinstance(d, dict):
return dotted(d)
return dotted({})
def get_files_from_data(data, original, files, inlinefiles, original_files, prefix):
if isinstance(data, File):
get_file_from_item(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(data, dict):
return
dd = dotted(data)
ddoriginal = make_dotted_or_emptydict(original)
for k,f in dd.dotteditems():
if isinstance(f, File):
if isinstance(ddoriginal.get(k), File):
of = ddoriginal[k]
else:
of = None
get_file_from_item(f, of, files, inlinefiles, original_files, get_attr(prefix, k))
def get_file_from_item(f, of, files, inlinefiles, original_files, fullprefix):
if f.file is None:
# if we have no original data then we presume the file should remain unchanged
f.id = of.id
if f.mimetype is None:
f.mimetype = of.mimetype
if f.filename is None:
f.filename = of.filename
+ if f.metadata is None:
+ f.metadata = getattr(of, 'metadata', None)
else:
if of and hasattr(of,'id'):
f.id = of.id
else:
f.id = uuid.uuid4().hex
if getattr(f,'inline',False) is True:
filestore = inlinefiles
else:
filestore = files
if hasattr(f, 'inline'):
del f.inline
# add the files for attachment handling and remove the file data from document
if getattr(f,'b64', None):
- filestore[fullprefix] = jsonutil.CouchishFile(f.file, f.filename, f.mimetype, f.id, b64=True)
+ filestore[fullprefix] = jsonutil.CouchishFile(f.file, f.filename, f.mimetype, f.id, metadata = f.metadata, b64=True)
del f.b64
else:
fh = StringIO()
shutil.copyfileobj(f.file, fh)
fh.seek(0)
- filestore[fullprefix] = jsonutil.CouchishFile(fh, f.filename, f.mimetype, f.id)
+ filestore[fullprefix] = jsonutil.CouchishFile(fh, f.filename, f.mimetype, f.id, metadata = f.metadata)
del f.file
def get_file_from_original(f, of, files, inlinefiles, original_files, fullprefix):
if not isinstance(f, File):
original_files[fullprefix] = of
def get_files_from_original(data, original, files, inlinefiles, original_files, prefix):
if isinstance(original, File):
get_file_from_original(data, original, files, inlinefiles, original_files, get_attr(prefix))
return
if not isinstance(original, dict):
return
dd = make_dotted_or_emptydict(data)
ddoriginal = dotted(original)
for k, of in ddoriginal.dotteditems():
if isinstance(of, File):
f = dd.get(k)
get_file_from_original(f, of, files, inlinefiles, original_files, get_attr(prefix, kparent))
def _parse_changes_for_files(session, deletions, additions, changes):
""" returns deletions, additions """
additions = list(additions)
changes = list(changes)
deletions = list(deletions)
all_separate_files = {}
all_inline_files = {}
for addition in additions:
addition, files, inlinefiles, original_files_notused = get_files(addition)
if files:
all_separate_files.setdefault(addition['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(addition['_id'],{}).update(inlinefiles)
_extract_inline_attachments(addition, inlinefiles)
all_original_files = {}
changes = list(changes)
for n, changeset in enumerate(changes):
d, cs = changeset
cs = list(cs)
for m, c in enumerate(cs):
if c['action'] in ['edit','create','remove']:
c['value'], files, inlinefiles, original_files = get_files(c.get('value'), original=c.get('was'), prefix=c['path'])
cs[m] = c
if files:
all_separate_files.setdefault(d['_id'],{}).update(files)
if inlinefiles:
all_inline_files.setdefault(d['_id'],{}).update(inlinefiles)
all_original_files.setdefault(d['_id'], {}).update(original_files)
_extract_inline_attachments(d, inlinefiles)
changes[n] = (d, cs)
return all_original_files, all_separate_files
def _extract_inline_attachments(doc, files):
"""
Move the any attachment data that we've found into the _attachments attribute
"""
for attr, f in files.items():
if f.b64:
data = f.file.replace('\n', '')
else:
data = base64.encodestring(f.file.read()).replace('\n','')
f.file.close()
del f.file
del f.b64
del f.inline
del f.doc_id
doc.setdefault('_attachments',{})[f.id] = {'content_type': f.mimetype,'data': data}
def _handle_separate_attachments(session, deletions, additions):
"""
add attachments that aren't inline and remove any attachments without references
"""
# XXX This needs to cope with files moving when sequences are re-numbered. We need
# XXX to talk to matt about what a renumbering like this looks like
for id, attrfiles in additions.items():
doc = session.get(id)
for attr, f in attrfiles.items():
data = ''
if f.file:
if f.b64:
data = base64.decodestring(f.file)
else:
data = f.file.read()
f.file.close()
session._db.put_attachment({'_id':doc['_id'], '_rev':doc['_rev']}, data, filename=f.id, content_type=f.mimetype)
del f.file
del f.b64
del f.inline
del f.doc_id
for id, attrfiles in deletions.items():
# XXX had to use _db because delete attachment freeaked using session version.
doc = session._db.get(id)
for attr, f in attrfiles.items():
session._db.delete_attachment(doc, f.id)
additions = {}
deletions = {}
diff --git a/couchish/jsonutil.py b/couchish/jsonutil.py
index 5e154b4..63ff9cb 100644
--- a/couchish/jsonutil.py
+++ b/couchish/jsonutil.py
@@ -1,96 +1,102 @@
from jsonish import pythonjson
from schemaish.type import File
import base64
from dottedish import dotted
class CouchishFile(File):
- def __init__(self, file, filename, mimetype, id=None, doc_id=None, inline=False, b64=False):
+ def __init__(self, file, filename, mimetype, id=None, doc_id=None, inline=False, b64=False, metadata=None):
self.file = file
self.filename = filename
self.mimetype = mimetype
self.id = id
self.doc_id = doc_id
self.inline = inline
self.b64 = b64
+ if metadata is None:
+ metadata = {}
+ self.metadata = metadata
def __repr__(self):
- return '<couchish.jsonutil.CouchishFile file="%r" filename="%s", mimetype="%s", id="%s", doc_id="%s", inline="%s", b64="%s" >' % (getattr(self,'file',None), self.filename, self.mimetype, self.id, getattr(self, 'doc_id',None), getattr(self,'inline',None), getattr(self,'b64', None))
+ return '<couchish.jsonutil.CouchishFile file="%r" filename="%s", mimetype="%s", id="%s", doc_id="%s", inline="%s", b64="%s", metadata="%r" >' % (getattr(self,'file',None), self.filename, self.mimetype, self.id, getattr(self, 'doc_id',None), getattr(self,'inline',None), getattr(self,'b64', None), getattr(self, 'metadata', {}))
def file_to_dict(obj):
d = {
'__type__': 'file',
'filename': obj.filename,
'mimetype': obj.mimetype,
'id': getattr(obj, 'id', None),
}
+ if hasattr(obj, 'metadata') and obj.metadata:
+ d['metadata'] = obj.metadata
if hasattr(obj,'doc_id') and obj.doc_id is not None:
d['doc_id'] = obj.doc_id
if hasattr(obj, 'inline') and obj.inline is not False:
d['inline'] = obj.inline
if hasattr(obj,'file') and hasattr(obj,'b64'):
d['base64'] = obj.file
else:
if hasattr(obj,'file') and obj.file is not None:
d['base64'] = base64.encodestring(obj.file.read())
return d
def file_from_dict(obj):
filename = obj['filename']
mimetype = obj['mimetype']
inline = obj.get('inline', False)
id = obj.get('id')
doc_id = obj.get('doc_id')
+ metadata = obj.get('metadata',{})
if 'base64' in obj:
data = obj['base64']
- return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, b64=True)
+ return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, b64=True, metadata=metadata)
elif 'file' in obj:
data = obj['file']
- return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline)
+ return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, metadata=metadata)
else:
- return CouchishFile(None, filename, mimetype, id=id, doc_id=doc_id)
+ return CouchishFile(None, filename, mimetype, id=id, doc_id=doc_id, metadata=metadata)
pythonjson.json.register_type(File, file_to_dict, file_from_dict, "file")
pythonjson.json.register_type(CouchishFile, file_to_dict, file_from_dict, "file")
pythonjson.decode_mapping['file'] = file_from_dict
pythonjson.encode_mapping[File] = ('file',file_to_dict)
pythonjson.encode_mapping[CouchishFile] = ('file',file_to_dict)
def wrap_encode_to_dict(obj):
return pythonjson.encode_to_dict(obj)
def wrap_decode_from_dict(d):
obj = pythonjson.decode_from_dict(d)
obj = add_id_and_attr_to_files(obj)
return obj
encode_to_dict = wrap_encode_to_dict
decode_from_dict = wrap_decode_from_dict
def add_id_and_attr_to_files(data):
if not isinstance(data, dict):
return data
dd = dotted(data)
for k in dd.dottedkeys():
if isinstance(dd[k],File):
if '_id' in dd and '_rev' in dd:
dd[k].doc_id = dd['_id']
dd[k].rev = dd['_rev']
return dd.data
segments = k.split('.')
for n in xrange(1,len(segments)):
subpath = '.'.join(segments[:-n])
if '_id' in dd[subpath] and '_rev' in dd[subpath]:
dd[k].doc_id = dd[subpath]['_id']
dd[k].rev = dd[subpath]['_rev']
data = dd.data
return data
dumps = pythonjson.dumps
loads = pythonjson.loads
|
ish/couchish
|
1731fb6d5fbc13a561d9af16228865b96958202f
|
dont store b64 data if there isnt a file attribute to do so
|
diff --git a/couchish/jsonutil.py b/couchish/jsonutil.py
index c1876ec..5e154b4 100644
--- a/couchish/jsonutil.py
+++ b/couchish/jsonutil.py
@@ -1,96 +1,96 @@
from jsonish import pythonjson
from schemaish.type import File
import base64
from dottedish import dotted
class CouchishFile(File):
def __init__(self, file, filename, mimetype, id=None, doc_id=None, inline=False, b64=False):
self.file = file
self.filename = filename
self.mimetype = mimetype
self.id = id
self.doc_id = doc_id
self.inline = inline
self.b64 = b64
def __repr__(self):
return '<couchish.jsonutil.CouchishFile file="%r" filename="%s", mimetype="%s", id="%s", doc_id="%s", inline="%s", b64="%s" >' % (getattr(self,'file',None), self.filename, self.mimetype, self.id, getattr(self, 'doc_id',None), getattr(self,'inline',None), getattr(self,'b64', None))
def file_to_dict(obj):
d = {
'__type__': 'file',
'filename': obj.filename,
'mimetype': obj.mimetype,
'id': getattr(obj, 'id', None),
}
if hasattr(obj,'doc_id') and obj.doc_id is not None:
d['doc_id'] = obj.doc_id
if hasattr(obj, 'inline') and obj.inline is not False:
d['inline'] = obj.inline
- if hasattr(obj,'b64'):
+ if hasattr(obj,'file') and hasattr(obj,'b64'):
d['base64'] = obj.file
else:
if hasattr(obj,'file') and obj.file is not None:
d['base64'] = base64.encodestring(obj.file.read())
return d
def file_from_dict(obj):
filename = obj['filename']
mimetype = obj['mimetype']
inline = obj.get('inline', False)
id = obj.get('id')
doc_id = obj.get('doc_id')
if 'base64' in obj:
data = obj['base64']
return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline, b64=True)
elif 'file' in obj:
data = obj['file']
return CouchishFile(data, filename, mimetype, id=id, doc_id=doc_id, inline=inline)
else:
return CouchishFile(None, filename, mimetype, id=id, doc_id=doc_id)
pythonjson.json.register_type(File, file_to_dict, file_from_dict, "file")
pythonjson.json.register_type(CouchishFile, file_to_dict, file_from_dict, "file")
pythonjson.decode_mapping['file'] = file_from_dict
pythonjson.encode_mapping[File] = ('file',file_to_dict)
pythonjson.encode_mapping[CouchishFile] = ('file',file_to_dict)
def wrap_encode_to_dict(obj):
return pythonjson.encode_to_dict(obj)
def wrap_decode_from_dict(d):
obj = pythonjson.decode_from_dict(d)
obj = add_id_and_attr_to_files(obj)
return obj
encode_to_dict = wrap_encode_to_dict
decode_from_dict = wrap_decode_from_dict
def add_id_and_attr_to_files(data):
if not isinstance(data, dict):
return data
dd = dotted(data)
for k in dd.dottedkeys():
if isinstance(dd[k],File):
if '_id' in dd and '_rev' in dd:
dd[k].doc_id = dd['_id']
dd[k].rev = dd['_rev']
return dd.data
segments = k.split('.')
for n in xrange(1,len(segments)):
subpath = '.'.join(segments[:-n])
if '_id' in dd[subpath] and '_rev' in dd[subpath]:
dd[k].doc_id = dd[subpath]['_id']
dd[k].rev = dd[subpath]['_rev']
data = dd.data
return data
dumps = pythonjson.dumps
loads = pythonjson.loads
|
ish/couchish
|
97b008238285ea64814af8b49e95329fa8b5cbc4
|
clear file additions and deletions store after every flush
|
diff --git a/couchish/store.py b/couchish/store.py
index 0a6a708..8ed333c 100644
--- a/couchish/store.py
+++ b/couchish/store.py
@@ -1,241 +1,243 @@
"""
Views we can build:
* by type, one view should be ok
* x_by_y views, from config (optional)
* ref and ref reversed views, one pair per relationship
"""
from couchdb.design import ViewDefinition
from couchdbsession import a8n, session
import schemaish.type
from couchish import filehandling, errors, jsonutil
class CouchishStore(object):
def __init__(self, db, config):
self.db = db
self.config = config
def sync_views(self):
for url, view in self.config.viewdata['views'].items():
segments = url.split('/')
designdoc = segments[0]
name = '/'.join(segments[1:])
view = ViewDefinition(designdoc, name, view[0], view[1])
view.get_doc(self.db)
view.sync(self.db)
def session(self):
"""
Create an editing session.
"""
return CouchishStoreSession(self)
class CouchishStoreSession(object):
def __init__(self, store):
self.store = store
self.session = Session(store.db,
pre_flush_hook=self._pre_flush_hook,
post_flush_hook=self._post_flush_hook,
encode_doc=jsonutil.encode_to_dict,
decode_doc=jsonutil.decode_from_dict)
self.file_additions = {}
self.file_deletions = {}
def __enter__(self):
"""
"with" statement entry.
"""
return self
def __exit__(self, type, value, traceback):
"""
"with" statement exit.
"""
if type is None:
self.flush()
else:
self.reset()
def create(self, doc):
"""
Create a document.
"""
return self.session.create(doc)
def delete(self, doc_or_tuple):
"""
Delete the given document.
"""
if isinstance(doc_or_tuple, tuple):
id, rev = doc_or_tuple
doc = {'_id': id, 'rev': rev}
else:
doc = doc_or_tuple
return self.session.delete(doc)
def get_attachment(self, id_or_doc, filename):
return self.session._db.get_attachment(id_or_doc, filename)
def put_attachment(self, doc, content, filename=None, content_type=None):
return self.session._db.put_attachment(doc, content,
filename=filename, content_type=content_type)
def delete_attachment(self, doc, filename):
return self.session._db.delete_attachment(doc, filename)
def doc_by_id(self, id):
"""
Return a single document, given it's ID.
"""
doc = self.session.get(id)
if doc is None:
raise errors.NotFound("No document with id %r" % (id,))
return doc
def doc_by_view(self, view, key):
results = self.session.view(view, startkey=key, endkey=key, limit=2,
include_docs=True)
rows = results.rows
if len(rows) == 0:
raise errors.NotFound("No document in view %r with key %r" % (view, key))
elif len(rows) == 2:
raise errors.TooMany("Too many documents in view %r for key %r" % (view, key))
return rows[0].doc
def docs_by_id(self, ids, **options):
"""
Generate the sequence of documents with the given ids.
"""
options = dict(options)
options['keys'] = ids
options['include_docs'] = True
results = self.session.view('_all_docs', **options)
return (row.doc for row in results.rows)
def docs_by_type(self, type, **options):
"""
Generate the sequence of docs of a given type.
"""
options = dict(options)
options['include_docs'] = True
results = self.session.view('%s/all'%type, **options)
return (row.doc for row in results.rows)
def docs_by_view(self, view, **options):
options = dict(options)
options['include_docs'] = True
results = self.session.view(view, **options)
return (row.doc for row in results.rows)
def view(self, view, **options):
"""
Call and return a view.
"""
return self.session.view(view, **options)
def _pre_flush_hook(self, session, deletions, additions, changes):
file_deletions, file_additions = filehandling._parse_changes_for_files(session, deletions, additions, changes)
self.file_deletions.update(file_deletions)
self.file_additions.update(file_additions)
def flush(self):
"""
Flush the session.
"""
returnvalue = self.session.flush()
filehandling._handle_separate_attachments(self.session, self.file_deletions, self.file_additions)
+ self.file_additions = {}
+ self.file_deletions = {}
return returnvalue
def reset(self):
"""
Reset the session, forgetting everything it knows.
"""
self.session.reset()
def _post_flush_hook(self, session, deletions, additions, changes):
# Sentinel to indicate we haven't retrieved the ref view data yet.
NO_REF_DATA = object()
# Easy access to the config.
views_by_viewname = self.store.config.viewdata['views_by_viewname']
viewnames_by_attribute = self.store.config.viewdata['viewnames_by_attribute']
attributes_by_viewname = self.store.config.viewdata['attributes_by_viewname']
# Updates any documents that refer to documents that have been changed.
for doc, actions in changes:
doc_type = doc['model_type']
edited = set('.'.join([doc_type, '.'.join(str(p) for p in action['path'])])
for action in actions if action['action'] == 'edit')
# Build a set of all the views affected by the changed attributes.
views = set()
for attr in edited:
views.update(viewnames_by_attribute.get(attr, []))
for view in views:
# Lazy load the ref_data.
ref_data = NO_REF_DATA
attrs_by_type = attributes_by_viewname[view]
view_url = views_by_viewname[view]['url']
# XXX should build a full key here, but let's assume just the
# id for a moment.
ref_key = doc['_id']
for ref_doc in self.docs_by_view(view_url+'-rev', startkey=ref_key, endkey=ref_key):
# Fetch the ref data for this ref view, if we don't already
# have it.
if ref_data is NO_REF_DATA:
ref_data = self.view(view_url, startkey=ref_key, limit=1).rows[0].value
if isinstance(ref_data, dict):
ref_data['_ref'] = ref_key
else:
ref_data = {'_ref': ref_key, 'data': ref_data}
for attr in attrs_by_type[ref_doc['model_type']]:
# Any of the attrs sections could be a sequence.. we need to iterate over them all to find matches..
# e.g. we may have authors*. or metadata*.authors*
self._find_and_match_nested_item(ref_doc, attr.split('.'), ref_data)
def _find_and_match_nested_item(self, ref_doc, segments, ref_data, prefix=None):
# Initialise of copy the prefix list, because we're about to change it.
if prefix is None:
prefix = []
else:
prefix = list(prefix)
if segments == []:
if ref_doc['_ref'] == ref_data['_ref']:
ref_doc.update(ref_data)
else:
current, segments = segments[0], segments[1:]
if current.endswith('*'):
is_seq = True
else:
is_seq = False
current = current.replace('*','')
prefix.append(current)
current_ref = ref_doc.get(current)
if current_ref is None:
return
if is_seq:
for ref_doc_ref in current_ref:
self._find_and_match_nested_item(ref_doc_ref, segments, ref_data, prefix)
else:
self._find_and_match_nested_item(current_ref, segments, ref_data, prefix)
class Tracker(a8n.Tracker):
def _track(self, obj, path):
if isinstance(obj, (jsonutil.CouchishFile, schemaish.type.File)):
return obj
return super(Tracker, self)._track(obj, path)
class Session(session.Session):
tracker_factory = Tracker
|
gfairbrother/fatcat
|
5fa2f83b840aa4af0ec228c7f7bf41f596c6511f
|
opps passing nil to gets gets the whole file, zero-length gets paragraph at a time
|
diff --git a/lib/fatcat_file.rb b/lib/fatcat_file.rb
index d54a977..10c941a 100644
--- a/lib/fatcat_file.rb
+++ b/lib/fatcat_file.rb
@@ -1,42 +1,42 @@
def load_file(fileloc)
if fileloc == nil
puts "No file specified"
exit
end
# log_contents will eventually hold all of our processed log file
log_contents = []
file = File.new(fileloc, 'r')
- while (paragraph = file.gets(nil)) # nil gets a whole paragraph (two successive newlines)
+ while (paragraph = file.gets(''))
# create a new LogEntry object which will hold all the data we extract from the log entry
log_entry = Fatcat::LogEntry.new(paragraph)
#split the paragraph into lines
lines = paragraph.split(/\n/)
# if the paragraph only has one line then it may be an error
# or a misc one liner like rubyamf
if lines.size == 1
# lets see if it's an error
if lines[0] =~ /error/
log_entry.error = true
end
end
# paragraph.gets.each do |line|
#
# if line[0,10] == 'Processing '
# # Processing UserDataStoresController#show (for 124.171.224.217 at 2009-04-06 09:24:37) [GET]
#
# end
#
# end
# add this log_entry to our log_contents array
log_contents << log_entry
end
# not really needed for ruby, but it's an old habbit and I like it for readability
return log_contents
end
|
nateleavitt/infusionsoft
|
84ff06f0dadd519afd42c2b394176c767a37077d
|
Reverting header as a result of improper documentation on Keap developer site
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 175addb..71733bb 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,63 +1,62 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {}, version: 'v1')
request(:get, path, token, version, query: query)
end
def post(path, token, query: {}, payload: {}, version: 'v1')
request(:post, path, token, version, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {}, version: 'v1')
request(:put, path, token, version, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {}, version: 'v1')
request(:patch, path, token, version, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {}, payload: {}, version: 'v1')
request(:delete, path, token, version, query, payload)
end
private
# Perform request
def request(method, path, token, version, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
- header.merge!({ 'X-Keap-API-Key': token.access_token }) if version == 'v2'
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/#{version}" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
rescue RestClient::ExceptionWithResponse => err
api_logger.error "[ERROR]: #{err}"
rescue => err
# RestClient::Unauthorized & SocketError
api_logger.error "[ERROR]: #{err}"
raise
end
end
end
|
nateleavitt/infusionsoft
|
5040cef187a08525d7f23156ce2e6cade5f10903
|
bumping to version 1.4.0
|
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index c656479..3b345a7 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.3.9'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.4.0'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
38241fd845e7d47512635ffe85479b655269f277
|
Adding REST v2 header
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d2d4f7c..175addb 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,61 +1,63 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {}, version: 'v1')
request(:get, path, token, version, query: query)
end
def post(path, token, query: {}, payload: {}, version: 'v1')
request(:post, path, token, version, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {}, version: 'v1')
request(:put, path, token, version, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {}, version: 'v1')
request(:patch, path, token, version, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {}, payload: {}, version: 'v1')
request(:delete, path, token, version, query, payload)
end
private
# Perform request
def request(method, path, token, version, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
+ header.merge!({ 'X-Keap-API-Key': token.access_token }) if version == 'v2'
+
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/#{version}" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
rescue RestClient::ExceptionWithResponse => err
api_logger.error "[ERROR]: #{err}"
rescue => err
# RestClient::Unauthorized & SocketError
api_logger.error "[ERROR]: #{err}"
raise
end
end
end
|
nateleavitt/infusionsoft
|
c853f622999364ae1a8b4e26dd7d0931fac21940
|
Adding payload to delete call
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index b9ae627..d2d4f7c 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,61 +1,61 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {}, version: 'v1')
- request(:get, path, token, query: query, version)
+ request(:get, path, token, version, query: query)
end
def post(path, token, query: {}, payload: {}, version: 'v1')
- request(:post, path, token, query, payload, version)
+ request(:post, path, token, version, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {}, version: 'v1')
- request(:put, path, token, query, payload, version)
+ request(:put, path, token, version, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {}, version: 'v1')
- request(:patch, path, token, query, payload, version)
+ request(:patch, path, token, version, query, payload)
end
# Perform an HTTP DELETE request
- def delete(path, token, query: {}, version: 'v1')
- request(:delete, path, token, query, version)
+ def delete(path, token, query: {}, payload: {}, version: 'v1')
+ request(:delete, path, token, version, query, payload)
end
private
# Perform request
- def request(method, path, token, query={}, payload={}, version)
+ def request(method, path, token, version, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/#{version}" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
rescue RestClient::ExceptionWithResponse => err
api_logger.error "[ERROR]: #{err}"
rescue => err
# RestClient::Unauthorized & SocketError
api_logger.error "[ERROR]: #{err}"
raise
end
end
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 46df4b9..c656479 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.3.6'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.9'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
7b46978153b3ef0224943710bd18aaf82fb5f7a4
|
Adding version into rest requests
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 9fca8da..b9ae627 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,61 +1,61 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
- def get(path, token, query: {})
- request(:get, path, token, query: query )
+ def get(path, token, query: {}, version: 'v1')
+ request(:get, path, token, query: query, version)
end
- def post(path, token, query: {}, payload: {})
- request(:post, path, token, query, payload)
+ def post(path, token, query: {}, payload: {}, version: 'v1')
+ request(:post, path, token, query, payload, version)
end
# Perform an HTTP PUT request
- def put(path, token, query: {}, payload: {})
- request(:put, path, token, query, payload)
+ def put(path, token, query: {}, payload: {}, version: 'v1')
+ request(:put, path, token, query, payload, version)
end
# Perform an HTTP PATCH request
- def patch(path, token, query: {}, payload: {})
- request(:patch, path, token, query, payload)
+ def patch(path, token, query: {}, payload: {}, version: 'v1')
+ request(:patch, path, token, query, payload, version)
end
# Perform an HTTP DELETE request
- def delete(path, token, query: {})
- request(:delete, path, token, query)
+ def delete(path, token, query: {}, version: 'v1')
+ request(:delete, path, token, query, version)
end
private
# Perform request
- def request(method, path, token, query={}, payload={})
+ def request(method, path, token, query={}, payload={}, version)
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
- url: "https://api.infusionsoft.com/crm/rest/v1" + path,
+ url: "https://api.infusionsoft.com/crm/rest/#{version}" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
rescue RestClient::ExceptionWithResponse => err
api_logger.error "[ERROR]: #{err}"
rescue => err
# RestClient::Unauthorized & SocketError
api_logger.error "[ERROR]: #{err}"
raise
end
end
end
|
nateleavitt/infusionsoft
|
afd0205839b4931a6b8c1b791421e58529a78be0
|
Adjusting errors
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index ce33937..9fca8da 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,58 +1,61 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {})
request(:patch, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
+ return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
rescue RestClient::ExceptionWithResponse => err
api_logger.error "[ERROR]: #{err}"
- else
- return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
+ rescue => err
+ # RestClient::Unauthorized & SocketError
+ api_logger.error "[ERROR]: #{err}"
+ raise
end
end
end
|
nateleavitt/infusionsoft
|
f5a3a7d49f83ac6c7d28d5ebf6a5f089c78e3d44
|
Rename new order method
|
diff --git a/lib/infusionsoft/client/order.rb b/lib/infusionsoft/client/order.rb
index 24133fc..6100940 100644
--- a/lib/infusionsoft/client/order.rb
+++ b/lib/infusionsoft/client/order.rb
@@ -1,40 +1,39 @@
module Infusionsoft
class Client
# The Order service allows you to create a new Order.
module Order
# Creates a new order.
#
# @param [Integer] contact_id
# ID of the order's Contact (0 is not a valid ID).
# @param [Integer] card_id
# ID of the card to charge. To skip charging a card, set to "0".
# @param [Integer] plan_id
# ID of the payment plan to use when creating the order. If not
# specified, the default plan is used.
# @param [Array<Integer>] product_ids
# A list of integers representing the products to add to the order.
# This cannot be emtpy if a subscription is not specified.
# @param [Array<Integer>] subscription_ids
# A list of integers representing the subscription(s) to add to the
# order. This cannot be empty if a product ID is not specified.
# @param [Boolean] process_specials
# Whether or not the order should consider discounts that would normally
# be applied if this order was placed through the shopping cart.
# @param [Array<String>] promo_codes
# Promo codes to add to the cart; only used if processing of specials
# is turned on.
# @param [Integer] lead_affiliate_id
# ID of the lead affiliate (0 should be used if none).
# @param [Integer] sale_affiliate_id
# ID of the sale affiliate (0 should be used if none).
# @return [Hash] The result of order placement with IDs of the order and
# invoice that were created and the status of a credit card charge
# (if applicable).
# {'Successful' => [Boolean], 'Message' => [String], 'RefNum' => [String], 'OrderId' => [String], 'InvoiceId' => [String], 'Code' => [String]}
- def order_create_order(contact_id, card_id, plan_id, product_ids, subscription_ids, process_specials, promo_codes, lead_affiliate_id, sale_affiliate_id)
+ def place_order(contact_id, card_id, plan_id, product_ids, subscription_ids, process_specials, promo_codes, lead_affiliate_id, sale_affiliate_id)
response = xmlrpc('OrderService.placeOrder', contact_id, card_id, plan_id, product_ids, subscription_ids, process_specials, promo_codes, lead_affiliate_id, sale_affiliate_id)
end
- alias_method :place_order, :order_create_order
end
end
end
|
nateleavitt/infusionsoft
|
7319ebb00ded681b3f87285eee95bd509c2efa9c
|
Add order creation
|
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index 111ffeb..e26448c 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,31 +1,33 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
+ require 'infusionsoft/client/order'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
require 'infusionsoft/client/funnel'
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
+ include Infusionsoft::Client::Order
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
include Infusionsoft::Client::Funnel
end
end
diff --git a/lib/infusionsoft/client/order.rb b/lib/infusionsoft/client/order.rb
new file mode 100644
index 0000000..24133fc
--- /dev/null
+++ b/lib/infusionsoft/client/order.rb
@@ -0,0 +1,40 @@
+module Infusionsoft
+ class Client
+ # The Order service allows you to create a new Order.
+ module Order
+ # Creates a new order.
+ #
+ # @param [Integer] contact_id
+ # ID of the order's Contact (0 is not a valid ID).
+ # @param [Integer] card_id
+ # ID of the card to charge. To skip charging a card, set to "0".
+ # @param [Integer] plan_id
+ # ID of the payment plan to use when creating the order. If not
+ # specified, the default plan is used.
+ # @param [Array<Integer>] product_ids
+ # A list of integers representing the products to add to the order.
+ # This cannot be emtpy if a subscription is not specified.
+ # @param [Array<Integer>] subscription_ids
+ # A list of integers representing the subscription(s) to add to the
+ # order. This cannot be empty if a product ID is not specified.
+ # @param [Boolean] process_specials
+ # Whether or not the order should consider discounts that would normally
+ # be applied if this order was placed through the shopping cart.
+ # @param [Array<String>] promo_codes
+ # Promo codes to add to the cart; only used if processing of specials
+ # is turned on.
+ # @param [Integer] lead_affiliate_id
+ # ID of the lead affiliate (0 should be used if none).
+ # @param [Integer] sale_affiliate_id
+ # ID of the sale affiliate (0 should be used if none).
+ # @return [Hash] The result of order placement with IDs of the order and
+ # invoice that were created and the status of a credit card charge
+ # (if applicable).
+ # {'Successful' => [Boolean], 'Message' => [String], 'RefNum' => [String], 'OrderId' => [String], 'InvoiceId' => [String], 'Code' => [String]}
+ def order_create_order(contact_id, card_id, plan_id, product_ids, subscription_ids, process_specials, promo_codes, lead_affiliate_id, sale_affiliate_id)
+ response = xmlrpc('OrderService.placeOrder', contact_id, card_id, plan_id, product_ids, subscription_ids, process_specials, promo_codes, lead_affiliate_id, sale_affiliate_id)
+ end
+ alias_method :place_order, :order_create_order
+ end
+ end
+end
diff --git a/test/client/order_test.rb b/test/client/order_test.rb
new file mode 100644
index 0000000..53c05f2
--- /dev/null
+++ b/test/client/order_test.rb
@@ -0,0 +1,11 @@
+require_relative('../test_helper')
+
+class OrderTest < Test::Unit::TestCase
+ def test_create_new_order
+ # VCR.use_cassette('order_create') do
+ # result = Infusionsoft.place_order(4095, 0, nil, [1], nil, false, [], 0, 0)
+
+ # assert_instance_of Hash, result
+ # end
+ end
+end
|
nateleavitt/infusionsoft
|
c6f0925077f85d41fde9a1c91e8392258f7361d4
|
Tweaked error log messaging
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d4ee90d..ce33937 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,58 +1,58 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {})
request(:patch, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
- api_logger.error "Infusionsoft API Error: #{err}"
+ api_logger.error "[ERROR]: #{err}"
else
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
end
end
end
|
nateleavitt/infusionsoft
|
a53f69b0acd0eb2ec37e1fffcce4afef5d2c826e
|
Added basic error logging to requests that raise exceptions
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 0c7122c..d4ee90d 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,58 +1,58 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP PATCH request
def patch(path, token, query: {}, payload: {})
request(:patch, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
- # log error?
+ api_logger.error "Infusionsoft API Error: #{err}"
else
return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
end
end
end
|
nateleavitt/infusionsoft
|
4796995596f42d9b5a1e48027cddb1f641c03a03
|
1.3.6 ruby v3
|
diff --git a/.travis.yml b/.travis.yml
index 7151d0d..e5710e0 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,3 @@
language: ruby
rvm:
- 3.0.1
- - 2.3.8
- - 2.4.5
- - 2.5.3
- - 2.6.1
- - jruby-20mode # JRuby in 2.0 mode
diff --git a/README.md b/README.md
index 509ca7f..6b65e46 100644
--- a/README.md
+++ b/README.md
@@ -1,129 +1,130 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* v1.3.6 - Ruby v3 compatibility
* v1.3.5 - Rest API is now supported (documentation incoming)
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
- gem install infusionsoft
+ ruby 3.* gem install infusionsoft
+ ruby 2.* gem install infusionsoft -v 1.3.5
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.3.8
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2019 Nathan Leavitt
See [MIT LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
b650472a5e78096ff60aea0534e530f1382d124f
|
Ruby v3
|
diff --git a/.travis.yml b/.travis.yml
index 22082d6..7151d0d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,8 @@
language: ruby
rvm:
+ - 3.0.1
- 2.3.8
- 2.4.5
- 2.5.3
- 2.6.1
- jruby-20mode # JRuby in 2.0 mode
|
nateleavitt/infusionsoft
|
05b57773145e41860f5a005de6f1965e75516b21
|
Updating for Ruby v3 compat
|
diff --git a/README.md b/README.md
index d3ded26..509ca7f 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,129 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
-* upcoming - Adding support for rest api
+* v1.3.6 - Ruby v3 compatibility
+* v1.3.5 - Rest API is now supported (documentation incoming)
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
-You will need to handle and obtain the access_token on your own.
+You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.3.8
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2019 Nathan Leavitt
See [MIT LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
diff --git a/lib/infusionsoft.rb b/lib/infusionsoft.rb
index d0c420d..923217f 100644
--- a/lib/infusionsoft.rb
+++ b/lib/infusionsoft.rb
@@ -1,28 +1,28 @@
require 'infusionsoft/api'
require 'infusionsoft/client'
require 'infusionsoft/configuration'
require 'infusionsoft/api_logger'
require 'infusionsoft/rest/token'
module Infusionsoft
extend Configuration
class << self
# Alias for Infusionsoft::Client.new
#
# @return [Infusionsoft::Client]
def new(options={})
Infusionsoft::Client.new(options)
end
# Delegate to ApiInfusionsoft::Client
- def method_missing(method, *args, &block)
+ def method_missing(method, *args, **kwargs, &block)
return super unless new.respond_to?(method)
- new.send(method, *args, &block)
+ new.send(method, *args, **kwargs, &block)
end
def respond_to?(method, include_private = false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 050b3ef..46df4b9 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.3.4a'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.6'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
2a88a360cb14043d5ffc961a051596febebcba4f
|
Added patch and checking for response body
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index e771cb0..0c7122c 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,53 +1,58 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
+ # Perform an HTTP PATCH request
+ def patch(path, token, query: {}, payload: {})
+ request(:patch, path, token, query, payload)
+ end
+
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
# log error?
else
- return JSON.parse(resp.body)
+ return JSON.parse(resp.body) if resp.body # Some calls respond w nothing
end
end
end
|
nateleavitt/infusionsoft
|
7a8c1d5feb6b63375ca0b9391acf6608afaea536
|
Updating simplecov and updating test
|
diff --git a/test/client/contact_test.rb b/test/client/contact_test.rb
index 79fdd6c..44e2a38 100644
--- a/test/client/contact_test.rb
+++ b/test/client/contact_test.rb
@@ -1,79 +1,78 @@
require_relative('../test_helper')
class ContactTest < Test::Unit::TestCase
def test_contact_add
data_hash = { Email: '[email protected]', FirstName: 'Severus', LastName: 'Snape' }
VCR.use_cassette('contact_add') do
result = Infusionsoft.contact_add(data_hash)
assert_instance_of Fixnum, result
end
end
def test_contact_merge
VCR.use_cassette('contact_merge') do
result = Infusionsoft.contact_merge(3602, 3604)
assert_true result
end
end
def test_contact_add_dup_check_with_dup
data_hash = { Email: '[email protected]', FirstName: 'Severus',
LastName: 'Snape', Company: 'Test Company' }
VCR.use_cassette('contact_add_dup_check_with_dup') do
existing_contact = Infusionsoft.contact_load(3606, [:Id, :FirstName, :LastName, :Email, :Company])
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndName')
assert_equal result, existing_contact['Id']
- assert_equal Infusionsoft.contact_load(existing_contact['Id'], [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_add_dup_check_no_dup
data_hash = { Email: '[email protected]', FirstName: 'Albus',
LastName: 'Dumbledore', Company: 'Hogwarts' }
VCR.use_cassette('contact_add_dup_check_no_dup') do
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndNameAndCompany')
assert_instance_of Fixnum, result
end
end
def test_contact_load
desired_fields = [:FirstName, :LastName]
expected_fields = desired_fields.map { |f| f.to_s }.sort
VCR.use_cassette('contact_load') do
result = Infusionsoft.contact_load(3606, desired_fields)
assert_equal result.keys.sort, expected_fields
end
end
def test_contact_update
data_hash = { Company: 'Hogwarts' }
VCR.use_cassette('contact_update') do
result = Infusionsoft.contact_update(3606, data_hash)
assert_equal result, 3606
assert_equal Infusionsoft.contact_load(3606, [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_find_by_email
VCR.use_cassette('find_by_email') do
result = Infusionsoft.contact_find_by_email('[email protected]', [:Id])
assert_instance_of Array, result
assert_instance_of Hash, result.first
end
end
def test_contact_add_to_group
VCR.use_cassette('add_to_group') do
result = Infusionsoft.contact_add_to_group(3794, 382)
assert_true result
end
end
def test_contact_remove_from_group
VCR.use_cassette('remove_from_group') do
result = Infusionsoft.contact_remove_from_group(3794, 382)
assert_true result
end
end
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index c1a423d..541b521 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,47 +1,47 @@
require 'coveralls'
Coveralls.wear!
require 'simplecov'
-SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
+SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
-]
+])
SimpleCov.start do
add_filter '/vendor/'
add_filter '/.bundle/'
add_filter '/test'
add_group 'Clients', 'lib/infusionsoft/client'
end
require 'test/unit'
require 'infusionsoft'
require 'vcr'
require 'webmock/test_unit'
require 'mocha/test_unit'
WebMock.disable_net_connect!(allow_localhost: true)
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
c.hook_into :webmock
c.default_cassette_options = { record: :once, match_requests_on: [:method] }
end
class Test::Unit::TestCase
class TestLogger
def info(msg); end
def warn(msg); end
def error(msg); end
def debug(msg); end
def fatal(msg); end
end
def setup
Infusionsoft.configure do |config|
config.api_url = 'test.infusionsoft.com'
config.api_key = 'not_a_real_key'
config.api_logger = TestLogger.new
end
end
end
|
nateleavitt/infusionsoft
|
2de9d9fab6b67c0af72593864845255e8f89a862
|
Updating Simplecov and other dup check test
|
diff --git a/test/client/contact_test.rb b/test/client/contact_test.rb
index 79fdd6c..44e2a38 100644
--- a/test/client/contact_test.rb
+++ b/test/client/contact_test.rb
@@ -1,79 +1,78 @@
require_relative('../test_helper')
class ContactTest < Test::Unit::TestCase
def test_contact_add
data_hash = { Email: '[email protected]', FirstName: 'Severus', LastName: 'Snape' }
VCR.use_cassette('contact_add') do
result = Infusionsoft.contact_add(data_hash)
assert_instance_of Fixnum, result
end
end
def test_contact_merge
VCR.use_cassette('contact_merge') do
result = Infusionsoft.contact_merge(3602, 3604)
assert_true result
end
end
def test_contact_add_dup_check_with_dup
data_hash = { Email: '[email protected]', FirstName: 'Severus',
LastName: 'Snape', Company: 'Test Company' }
VCR.use_cassette('contact_add_dup_check_with_dup') do
existing_contact = Infusionsoft.contact_load(3606, [:Id, :FirstName, :LastName, :Email, :Company])
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndName')
assert_equal result, existing_contact['Id']
- assert_equal Infusionsoft.contact_load(existing_contact['Id'], [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_add_dup_check_no_dup
data_hash = { Email: '[email protected]', FirstName: 'Albus',
LastName: 'Dumbledore', Company: 'Hogwarts' }
VCR.use_cassette('contact_add_dup_check_no_dup') do
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndNameAndCompany')
assert_instance_of Fixnum, result
end
end
def test_contact_load
desired_fields = [:FirstName, :LastName]
expected_fields = desired_fields.map { |f| f.to_s }.sort
VCR.use_cassette('contact_load') do
result = Infusionsoft.contact_load(3606, desired_fields)
assert_equal result.keys.sort, expected_fields
end
end
def test_contact_update
data_hash = { Company: 'Hogwarts' }
VCR.use_cassette('contact_update') do
result = Infusionsoft.contact_update(3606, data_hash)
assert_equal result, 3606
assert_equal Infusionsoft.contact_load(3606, [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_find_by_email
VCR.use_cassette('find_by_email') do
result = Infusionsoft.contact_find_by_email('[email protected]', [:Id])
assert_instance_of Array, result
assert_instance_of Hash, result.first
end
end
def test_contact_add_to_group
VCR.use_cassette('add_to_group') do
result = Infusionsoft.contact_add_to_group(3794, 382)
assert_true result
end
end
def test_contact_remove_from_group
VCR.use_cassette('remove_from_group') do
result = Infusionsoft.contact_remove_from_group(3794, 382)
assert_true result
end
end
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index c1a423d..541b521 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,47 +1,47 @@
require 'coveralls'
Coveralls.wear!
require 'simplecov'
-SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
+SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter
-]
+])
SimpleCov.start do
add_filter '/vendor/'
add_filter '/.bundle/'
add_filter '/test'
add_group 'Clients', 'lib/infusionsoft/client'
end
require 'test/unit'
require 'infusionsoft'
require 'vcr'
require 'webmock/test_unit'
require 'mocha/test_unit'
WebMock.disable_net_connect!(allow_localhost: true)
VCR.configure do |c|
c.cassette_library_dir = 'test/vcr_cassettes'
c.hook_into :webmock
c.default_cassette_options = { record: :once, match_requests_on: [:method] }
end
class Test::Unit::TestCase
class TestLogger
def info(msg); end
def warn(msg); end
def error(msg); end
def debug(msg); end
def fatal(msg); end
end
def setup
Infusionsoft.configure do |config|
config.api_url = 'test.infusionsoft.com'
config.api_key = 'not_a_real_key'
config.api_logger = TestLogger.new
end
end
end
|
nateleavitt/infusionsoft
|
4e7bf496586fe5503390ff498d0e9e86c3b7af1e
|
bumping supported rubies to >= 2.3.8
|
diff --git a/.travis.yml b/.travis.yml
index 1994027..9de527b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,6 @@
language: ruby
rvm:
- - 2.0.0
- - 2.1.5
- - 2.2.2
- - 2.3.4
- # - 2.4.1 need to do more testing
+ - 2.3.8
+ - 2.5.4
+ - 2.6.1
- jruby-20mode # JRuby in 2.0 mode
diff --git a/README.md b/README.md
index 19d29dc..d3ded26 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,128 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* upcoming - Adding support for rest api
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
-* Ruby >= 2.0
+* Ruby >= 2.3.8
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2019 Nathan Leavitt
See [MIT LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
28d29129e24b1e408d34fb618e9cbce1bf28054e
|
Bumping supported rubies to 2.3.8
|
diff --git a/.travis.yml b/.travis.yml
index 1994027..22082d6 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,7 @@
language: ruby
rvm:
- - 2.0.0
- - 2.1.5
- - 2.2.2
- - 2.3.4
- # - 2.4.1 need to do more testing
+ - 2.3.8
+ - 2.4.5
+ - 2.5.3
+ - 2.6.1
- jruby-20mode # JRuby in 2.0 mode
diff --git a/README.md b/README.md
index 19d29dc..d3ded26 100644
--- a/README.md
+++ b/README.md
@@ -1,128 +1,128 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* upcoming - Adding support for rest api
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
-* Ruby >= 2.0
+* Ruby >= 2.3.8
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2019 Nathan Leavitt
See [MIT LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
3f20039791286afcdd854aa01f16cd96b342184e
|
1.3.3 is a bad version history so skipping to 1.3.4
|
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 99b7582..050b3ef 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.3.3d'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.4a'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
0aaa23c698ca6edd3039c53248b2a28e5510fdc5
|
fixing bug with contact using rest instead of xmlrpc
|
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index 605948a..8464a8d 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,208 +1,208 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
# @param [Hash] data contains the mappable contact fields and it's data.
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the newly added contact
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'New Signup'
def contact_add(data, optin_status=nil)
- contact_id = get('ContactService.add', data)
+ contact_id = xmlrpc('ContactService.add', data)
email = data['Email'] || data[:Email]
- if optin_status && email; ::Client::email_optin(email, optin_status); end
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
response = xmlrpc('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] id of the contact added or updated
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'Email', 'New Signup'
def contact_add_with_dup_check(data, check_type, optin_status=nil)
- contact_id = get('ContactService.addWithDupCheck', data, check_type)
+ contact_id = xmlrpc('ContactService.addWithDupCheck', data, check_type)
email = data['Email'] || data[:Email]
- if optin_status && email; ::Client::email_optin(email, optin_status); end
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the contact updated
# @example
# { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }, 'New Signup'
def contact_update(contact_id, data, optin_status=nil)
- contact_id = get('ContactService.update', contact_id, data)
+ contact_id = xmlrpc('ContactService.update', contact_id, data)
email = data['Email'] || data[:Email]
- if optin_status && email; ::Client::email_optin(email, optin_status); end
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
response = xmlrpc('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
response = xmlrpc('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
response = xmlrpc('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
response = xmlrpc('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
response = xmlrpc('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
response = xmlrpc('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
response = xmlrpc('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
response = xmlrpc('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
response = xmlrpc('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
response = xmlrpc('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = xmlrpc('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 204ed43..99b7582 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.3.3a'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.3d'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
030e2d16b783ed851763b9b235ded86f6f3c7781
|
making sure right call is made
|
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index dd14222..605948a 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,208 +1,208 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
# @param [Hash] data contains the mappable contact fields and it's data.
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the newly added contact
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'New Signup'
def contact_add(data, optin_status=nil)
contact_id = get('ContactService.add', data)
email = data['Email'] || data[:Email]
- if optin_status && email; email_optin(email, optin_status); end
+ if optin_status && email; ::Client::email_optin(email, optin_status); end
return contact_id
end
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
response = xmlrpc('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] id of the contact added or updated
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'Email', 'New Signup'
def contact_add_with_dup_check(data, check_type, optin_status=nil)
contact_id = get('ContactService.addWithDupCheck', data, check_type)
email = data['Email'] || data[:Email]
- if optin_status && email; email_optin(email, optin_status); end
+ if optin_status && email; ::Client::email_optin(email, optin_status); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the contact updated
# @example
# { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }, 'New Signup'
def contact_update(contact_id, data, optin_status=nil)
contact_id = get('ContactService.update', contact_id, data)
email = data['Email'] || data[:Email]
- if optin_status && email; email_optin(email, optin_status); end
+ if optin_status && email; ::Client::email_optin(email, optin_status); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
response = xmlrpc('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
response = xmlrpc('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
response = xmlrpc('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
response = xmlrpc('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
response = xmlrpc('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
response = xmlrpc('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
response = xmlrpc('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
response = xmlrpc('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
response = xmlrpc('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
response = xmlrpc('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
response = xmlrpc('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = xmlrpc('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
|
nateleavitt/infusionsoft
|
5f50bcadd51230ff1c6cfc2b26f559b1011e4d2c
|
bumping version 1.3.3a
|
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index c7fb395..204ed43 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,8 +1,4 @@
module Infusionsoft
# The version of the gem
-<<<<<<< HEAD
- VERSION = '1.3.0a'.freeze unless defined?(::Infusionsoft::VERSION)
-=======
- VERSION = '1.3.1a'.freeze unless defined?(::Infusionsoft::VERSION)
->>>>>>> Bumping to 1.3.1a
+ VERSION = '1.3.3a'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
3676afddee82789c6642a6c8fdce9b07bf2b8960
|
fixing typo
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index e5ab912..facd18a 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,77 +1,77 @@
require 'rest-client'
require 'uri'
require 'json'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
@access_token = token_params[:access_token] || token_params["access_token"]
@refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
@expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in] || token_params["expires_in"]
@expiration = Time.now + (token_params[:expires_in] || token_params["expires_in"])
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- rescue RestClient::ExceptionWithRespone => e
+ rescue RestClient::ExceptionWithResponse => e
#TODO what to do here?
false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
-end
\ No newline at end of file
+end
|
nateleavitt/infusionsoft
|
700a84e9a3856200379f8ccf28d27ff24ec4a7cd
|
Bumping to 1.3.1a
|
diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec
index 8e0c2c9..b707244 100644
--- a/infusionsoft.gemspec
+++ b/infusionsoft.gemspec
@@ -1,21 +1,22 @@
# encoding: utf-8
require File.expand_path('../lib/infusionsoft/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'infusionsoft'
gem.summary = %q{Ruby wrapper for the Infusionsoft API}
gem.description = 'A Ruby wrapper written for the Infusionsoft API'
gem.authors = ["Nathan Leavitt"]
gem.email = ['[email protected]']
# gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = 'https://github.com/nateleavitt/infusionsoft'
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6')
gem.add_development_dependency 'rake'
+ gem.add_dependency "xmlrpc"
gem.add_dependency "rest-client"
gem.version = Infusionsoft::VERSION.dup
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 365b8b1..c7fb395 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,8 @@
module Infusionsoft
# The version of the gem
+<<<<<<< HEAD
VERSION = '1.3.0a'.freeze unless defined?(::Infusionsoft::VERSION)
+=======
+ VERSION = '1.3.1a'.freeze unless defined?(::Infusionsoft::VERSION)
+>>>>>>> Bumping to 1.3.1a
end
|
nateleavitt/infusionsoft
|
350d80ed8d5e2fe3bbe6ca4a1c89c68051449075
|
Fix parsing of token
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 428cc14..e5ab912 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,77 @@
require 'rest-client'
require 'uri'
+require 'json'
+
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
- access_token = token_params[:access_token] || token_params["access_token"]
- refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
- expiration = token_params[:expiration] if token_params[:expiration]
+ @access_token = token_params[:access_token] || token_params["access_token"]
+ @refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
+ @expiration = token_params[:expiration] if token_params[:expiration]
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in] || token_params["expires_in"]
+ if token_params[:expires_in] || token_params["expires_in"]
+ @expiration = Time.now + (token_params[:expires_in] || token_params["expires_in"])
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
+ false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
+ false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
54592d955214d97096ff54017246101d1f52298e
|
No symbolize keys method without rails
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index f62d3b5..428cc14 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
+ access_token = token_params[:access_token] || token_params["access_token"]
+ refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in] || token_params["expires_in"]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
- token_params = JSON.parse(response.body).symbolize_keys
+ token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
- token_params = JSON.parse(response.body).symbolize_keys
+ token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
152b32f62c8fa04f7ac15c26b46547f4f7b5df03
|
Fixing service_name call
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d656adc..e771cb0 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,53 +1,53 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
- def xmlrpc(servic_call, *args)
+ def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
# log error?
else
return JSON.parse(resp.body)
end
end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index f97d13d..f62d3b5 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
- class Token
+ class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
access_token = token_params[:access_token]
refresh_token = token_params[:refresh_token]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
expiration = Time.now + token_params[:expires_in]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
end
-
end
+
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
9b283adfb3f6c6c42c5a445bbb9ec4d2b99af802
|
fixing namespace on gem
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 12e6ac6..d656adc 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,52 +1,53 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(servic_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
# log error?
else
return JSON.parse(resp.body)
end
+ end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 95d7f6b..f97d13d 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,74 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
access_token = token_params[:access_token]
refresh_token = token_params[:refresh_token]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
expiration = Time.now + token_params[:expires_in]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
-
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
0a524464e0dd5b0d9f5561e1851bd6c8d18a8021
|
include module rest
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 3dc9148..95d7f6b 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,72 +1,74 @@
require 'rest-client'
require 'uri'
module Infusionsoft
- class Rest::Token
+ module Rest
+ class Token
- attr_accessor :access_token, :refresh_token, :expiration
+ attr_accessor :access_token, :refresh_token, :expiration
- def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
- expiration = token_params[:expiration] if token_params[:expiration]
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
end
- end
- def valid?
- Time.now < expiration
- end
+ def valid?
+ Time.now < expiration
+ end
- class << self
- def auth_url(client_id, redirect_uri)
- params = {
- client_id: client_id,
- redirect_uri: redirect_uri,
- scope: 'full',
- response_type: 'code'
- }
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
- uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
- uri.to_s
- end
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
- def refresh(client_id, client_secret, refresh_token)
- params = {
- grant_type: 'refresh_token',
- refresh_token: refresh_token,
- }
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
- header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
- response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- rescue RestClient::ExceptionWithRespone => e
- #TODO what to do here?
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
- end
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
- def get_token(client_id, client_secret, redirect_uri, code)
- params = {
- client_id: client_id,
- client_secret: client_secret,
- redirect_uri: redirect_uri,
- code: code,
- grant_type: 'authorization_code',
- }
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- response = RestClient.post("https://api.infusionsoft.com/token", params)
- rescue RestClient::ExceptionWithResponse => e
- # TODO: what to do here
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
end
end
-
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
026dc0b2c46396e3e07cf04f7df3db09bf56f959
|
Adding rest/token into base class
|
diff --git a/lib/infusionsoft.rb b/lib/infusionsoft.rb
index b507b13..d0c420d 100644
--- a/lib/infusionsoft.rb
+++ b/lib/infusionsoft.rb
@@ -1,27 +1,28 @@
require 'infusionsoft/api'
require 'infusionsoft/client'
require 'infusionsoft/configuration'
require 'infusionsoft/api_logger'
+require 'infusionsoft/rest/token'
module Infusionsoft
extend Configuration
class << self
# Alias for Infusionsoft::Client.new
#
# @return [Infusionsoft::Client]
def new(options={})
Infusionsoft::Client.new(options)
end
# Delegate to ApiInfusionsoft::Client
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method, include_private = false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
end
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index e3cd302..111ffeb 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,33 +1,31 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
- require 'infusionsoft/rest/token'
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
require 'infusionsoft/client/funnel'
- include Infusionsoft::Rest::Token
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
include Infusionsoft::Client::Funnel
end
end
|
nateleavitt/infusionsoft
|
896274d93f2bba42631d263c300b6f8a51d37176
|
include Infusionsoft module
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index b2ee56b..3dc9148 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,71 +1,72 @@
require 'rest-client'
require 'uri'
+module Infusionsoft
+ class Rest::Token
-class Rest::Token
+ attr_accessor :access_token, :refresh_token, :expiration
- attr_accessor :access_token, :refresh_token, :expiration
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
- def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
- expiration = token_params[:expiration] if token_params[:expiration]
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
+ end
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ def valid?
+ Time.now < expiration
end
- end
- def valid?
- Time.now < expiration
- end
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
- class << self
- def auth_url(client_id, redirect_uri)
- params = {
- client_id: client_id,
- redirect_uri: redirect_uri,
- scope: 'full',
- response_type: 'code'
- }
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
- uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
- uri.to_s
- end
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
- def refresh(client_id, client_secret, refresh_token)
- params = {
- grant_type: 'refresh_token',
- refresh_token: refresh_token,
- }
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
- header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- rescue RestClient::ExceptionWithRespone => e
- #TODO what to do here?
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
- end
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
- def get_token(client_id, client_secret, redirect_uri, code)
- params = {
- client_id: client_id,
- client_secret: client_secret,
- redirect_uri: redirect_uri,
- code: code,
- grant_type: 'authorization_code',
- }
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- response = RestClient.post("https://api.infusionsoft.com/token", params)
- rescue RestClient::ExceptionWithResponse => e
- # TODO: what to do here
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
end
end
-
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
fc9e89e513a9de9940116990280eb3a56c9defef
|
Require Infusionsoft Rest Token in client
|
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index 111ffeb..e3cd302 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,31 +1,33 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
+ require 'infusionsoft/rest/token'
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
require 'infusionsoft/client/funnel'
+ include Infusionsoft::Rest::Token
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
include Infusionsoft::Client::Funnel
end
end
|
nateleavitt/infusionsoft
|
6c4ad3795de25abf7e7394ee09fcb726d0b33236
|
Build out token and request methods
|
diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec
index b5145b8..8e0c2c9 100644
--- a/infusionsoft.gemspec
+++ b/infusionsoft.gemspec
@@ -1,19 +1,21 @@
# encoding: utf-8
require File.expand_path('../lib/infusionsoft/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'infusionsoft'
gem.summary = %q{Ruby wrapper for the Infusionsoft API}
gem.description = 'A Ruby wrapper written for the Infusionsoft API'
gem.authors = ["Nathan Leavitt"]
gem.email = ['[email protected]']
# gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = 'https://github.com/nateleavitt/infusionsoft'
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6')
gem.add_development_dependency 'rake'
+ gem.add_dependency "rest-client"
+
gem.version = Infusionsoft::VERSION.dup
end
diff --git a/lib/infusionsoft/client/affiliate.rb b/lib/infusionsoft/client/affiliate.rb
index a3b8f47..2552829 100644
--- a/lib/infusionsoft/client/affiliate.rb
+++ b/lib/infusionsoft/client/affiliate.rb
@@ -1,62 +1,62 @@
module Infusionsoft
class Client
# The Affiliate service is used to pull commission data and activities for affiliates.
# With this service, you have access to Clawbacks, Commissions, Payouts, Running Totals,
# and the Activity Summary. The methods in the Affiliate service mirror the reports
# produced inside Infusionsoft.
#
# @note To manage affiliate information (ie Name, Phone, etc.) you will need to use the Data service.
module Affiliate
# Used when you need to retrieve all clawed back commissions for a particular affiliate.
#
# @param [Integer] affiliate_id
# @params [Date] start_date
# @end_date [Date] end_date
# @return [Array] all claw backs for the given affiliate that have occurred within the date
# range specified
def affiliate_clawbacks(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date)
end
# Used to retrieve all commissions for a specific affiliate within a date range.
#
# @param [Integer] affiliate_id
# @param [Date] start_date
# @param [Date] end_date
# @return [Array] all sales commissions for the given affiliate earned within the date range
# specified
def affiliate_commissions(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date)
end
# Used to retrieve all payments for a specific affiliate within a date range.
#
# @param [Integer] affiliate_id
# @param [Date] start_date
# @param [Date] end_date
# @return [Array] a list of rows, each row is a single payout
def affiliate_payouts(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date)
end
# This method is used to retrieve all commissions for a specific affiliate within a date range.
#
# @param [Array] affiliate_list
# @return [Array] all sales commissions for the given affiliate earned within the date range
# specified
def affiliate_running_totals(affiliate_list)
- response = get('APIAffiliateService.affRunningTotals', affiliate_list)
+ response = xmlrpc('APIAffiliateService.affRunningTotals', affiliate_list)
end
# Used to retrieve a summary of statistics for a list of affiliates.
#
# @param [Array] affiliate_list
# @param [Date] start_date
# @param [Date] end_date
# @return [Array<Hash>] a summary of the affiliates information for a specified date range
def affiliate_summary(affiliate_list, start_date, end_date)
- response = get('APIAffiliateService.affSummary', affiliate_list, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affSummary', affiliate_list, start_date, end_date)
end
end
end
end
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index 8ba2ff1..dd14222 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,208 +1,208 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
# @param [Hash] data contains the mappable contact fields and it's data.
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the newly added contact
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'New Signup'
def contact_add(data, optin_status=nil)
contact_id = get('ContactService.add', data)
email = data['Email'] || data[:Email]
if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
- response = get('ContactService.merge', contact_id, duplicate_contact_id)
+ response = xmlrpc('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] id of the contact added or updated
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'Email', 'New Signup'
def contact_add_with_dup_check(data, check_type, optin_status=nil)
contact_id = get('ContactService.addWithDupCheck', data, check_type)
email = data['Email'] || data[:Email]
if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
# @param [String] (Optional) email opt in verbiage. The contact will then be
# "Opted in" using the verviage supplied here.
# @return [Integer] the id of the contact updated
# @example
# { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }, 'New Signup'
def contact_update(contact_id, data, optin_status=nil)
contact_id = get('ContactService.update', contact_id, data)
email = data['Email'] || data[:Email]
if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
- response = get('ContactService.load', id, selected_fields)
+ response = xmlrpc('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
- response = get('ContactService.findByEmail', email, selected_fields)
+ response = xmlrpc('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
- response = get('ContactService.addToCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
- response = get('ContactService.getNextCampaignStep', contact_id, campaign_id)
+ response = xmlrpc('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
- response = get('ContactService.pauseCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
- response = get('ContactService.removeFromCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
- response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id)
+ response = xmlrpc('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
- response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
+ response = xmlrpc('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
- response = get('ContactService.removeFromGroup', contact_id, group_id)
+ response = xmlrpc('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
- response = get('ContactService.addToGroup', contact_id, group_id)
+ response = xmlrpc('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
- response = get('ContactService.runActionSequence', contact_id, action_set_id)
+ response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
- response = get('ContactService.linkContact', remoteApp, remoteId, localId)
+ response = xmlrpc('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
- response = get('ContactService.locateContactLink', locate_map_id)
+ response = xmlrpc('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
- response = get('ContactService.markLinkUpdated', locate_map_id)
+ response = xmlrpc('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
- response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
+ response = xmlrpc('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
- response = get('ContactService.runActionSequence', contact_id, action_set_id, data)
+ response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
diff --git a/lib/infusionsoft/client/credit_card.rb b/lib/infusionsoft/client/credit_card.rb
index 502c43d..df3f669 100644
--- a/lib/infusionsoft/client/credit_card.rb
+++ b/lib/infusionsoft/client/credit_card.rb
@@ -1,24 +1,24 @@
module Infusionsoft
class Client
- # CreditCardSubmission service is used to obtain a token that is to be submitted
- # through a form when adding a credit card. In accordance with PCI compliance,
+ # CreditCardSubmission service is used to obtain a token that is to be submitted
+ # through a form when adding a credit card. In accordance with PCI compliance,
# adding credit cards through the API will no longer be supported.
module CreditCard
# This service will request a token that will be used when submitting
# a new credit card through a form
#
# @param [Integer] contact_id of the Infusionsoft contact
# @param [String] url that will be redirected to upon successfully adding card
# @param [String] url that will be redirected to when there is a failure upon adding card
def credit_card_request_token(contact_id, success_url, failure_url)
- response = get('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url)
+ response = xmlrpc('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url)
end
def credit_card_lookup_by_token(token)
- response = get('CreditCardSubmissionService.requestCreditCardId', token)
+ response = xmlrpc('CreditCardSubmissionService.requestCreditCardId', token)
end
end
end
end
diff --git a/lib/infusionsoft/client/data.rb b/lib/infusionsoft/client/data.rb
index e277302..674b00c 100644
--- a/lib/infusionsoft/client/data.rb
+++ b/lib/infusionsoft/client/data.rb
@@ -1,146 +1,146 @@
module Infusionsoft
class Client
# The Data service is used to manipulate most data in Infusionsoft. It permits you to
# work on any available tables and has a wide range of uses.
module Data
# Adds a record with the data provided.
#
# @param [String] table the name of the Infusiosoft database table
# @param [Hash] data the fields and it's data
# @return [Integer] returns the id of the record added
def data_add(table, data)
- response = get('DataService.add', table, data)
+ response = xmlrpc('DataService.add', table, data)
end
# This method will load a record from the database given the primary key.
#
# @param [String] table
# @param [Integer] id
# @param [Array] selected_fields
# @return [Hash] the field names and their data
# @example
# { "FirstName" => "John", "LastName" => "Doe" }
def data_load(table, id, selected_fields)
- response = get('DataService.load', table, id, selected_fields)
+ response = xmlrpc('DataService.load', table, id, selected_fields)
end
# Updates the specified record (indicated by ID) with the data provided.
#
# @param [String] table
# @param [Integer] id
# @param [Hash] data this is the fields and values you would like to update
# @return [Integer] id of the record updated
# @example
# { :FirstName => 'John', :Email => '[email protected]' }
def data_update(table, id, data)
- response = get('DataService.update', table, id, data)
+ response = xmlrpc('DataService.update', table, id, data)
end
# Deletes the record (specified by id) in the given table from the database.
#
# @param [String] table
# @param [Integer] id
# @return [Boolean] returns true/false if the record was successfully deleted
def data_delete(table, id)
- response = get('DataService.delete', table, id)
+ response = xmlrpc('DataService.delete', table, id)
end
# This will locate all records in a given table that match the criteria for a given field.
#
# @param [String] table
# @param [Integer] limit how many records you would like to return (max is 1000)
# @param [Integer] page the page of results (each page is max 1000 records)
# @param [String] field_name
# @param [String, Integer, Date] field_value
# @param [Array] selected_fields
# @return [Array<Hash>] returns the array of records with a hash of the fields and values
def data_find_by_field(table, limit, page, field_name, field_value, selected_fields)
- response = get('DataService.findByField', table, limit, page, field_name,
+ response = xmlrpc('DataService.findByField', table, limit, page, field_name,
field_value, selected_fields)
end
# Queries records in a given table to find matches on certain fields.
#
# @param [String] table
# @param [Integer] limit
# @param [Integer] page
# @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' }
# @param [Array] selected_fields the fields and values you want back
# @return [Array<Hash>] the fields and associated values
def data_query(table, limit, page, data, selected_fields)
- response = get('DataService.query', table, limit, page, data, selected_fields)
+ response = xmlrpc('DataService.query', table, limit, page, data, selected_fields)
end
# Queries records in a given table to find matches on certain fields.
#
# @param [String] table
# @param [Integer] limit
# @param [Integer] page
# @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' }
# @param [Array] selected_fields the fields and values you want back
# @param [String] field by which to order the output results
# @param [Boolean] true ascending, false descending
# @return [Array<Hash>] the fields and associated values
def data_query_order_by(table, limit, page, data, selected_fields, by, ascending)
- response = get('DataService.query', table, limit, page, data, selected_fields, by, ascending)
+ response = xmlrpc('DataService.query', table, limit, page, data, selected_fields, by, ascending)
end
# Adds a custom field to Infusionsoft
#
# @param [String] field_type options include Person, Company, Affiliate, Task/Appt/Note,
# Order, Subscription, or Opportunity
# @param [String] name
# @param [String] data_type the type of field Text, Dropdown, TextArea
# @param [Integer] header_id see notes here
# http://help.infusionsoft.com/developers/services-methods/data/addCustomField
def data_add_custom_field(field_type, name, data_type, header_id)
- response = get('DataService.addCustomField', field_type, name, data_type, header_id)
+ response = xmlrpc('DataService.addCustomField', field_type, name, data_type, header_id)
end
# Authenticate an Infusionsoft username and password(md5 hash). If the credentials match
# it will return back a User ID, if the credentials do not match it will send back an
# error message
#
# @param [String] username
# @param [String] password
# @return [Integer] id of the authenticated user
def data_authenticate_user(username, password)
- response = get('DataService.authenticateUser', username, password)
+ response = xmlrpc('DataService.authenticateUser', username, password)
end
# This method will return back the data currently configured in a user configured
# application setting.
#
# @param [String] module
# @param [String] setting
# @return [String] current values in given application setting
# @note to find the module and option names, view the HTML field name within the Infusionsoft
# settings. You will see something such as name="Contact_WebModule0optiontypes" . The portion
# before the underscore is the module name. "Contact" in this example. The portion after the
# 0 is the setting name, "optiontypes" in this example.
def data_get_app_setting(module_name, setting)
- response = get('DataService.getAppSetting', module_name, setting)
+ response = xmlrpc('DataService.getAppSetting', module_name, setting)
end
# Returns a temporary API key if given a valid Vendor key and user credentials.
#
# @param [String] vendor_key
# @param [String] username
# @param [String] password_hash an md5 hash of users password
# @return [String] temporary API key
def data_get_temporary_key(vendor_key, username, password_hash)
- response = get('DataService.getTemporaryKey', username, password_hash)
+ response = xmlrpc('DataService.getTemporaryKey', username, password_hash)
end
# Updates a custom field. Every field can have itâs display name and group id changed,
# but only certain data types will allow you to change values(dropdown, listbox, radio, etc).
#
# @param [Integer] field_id
# @param [Hash] field_values
# @return [Boolean] returns true/false if it was updated
def data_update_custom_field(field_id, field_values)
- response = get('DataService.updateCustomField', field_id, field_values)
+ response = xmlrpc('DataService.updateCustomField', field_id, field_values)
end
end
end
end
diff --git a/lib/infusionsoft/client/email.rb b/lib/infusionsoft/client/email.rb
index 7f62fda..3b63b12 100644
--- a/lib/infusionsoft/client/email.rb
+++ b/lib/infusionsoft/client/email.rb
@@ -1,152 +1,152 @@
module Infusionsoft
class Client
# The Email service allows you to email your contacts as well as attaching emails sent
# elsewhere (this lets you send email from multiple services and still see all communications
# inside of Infusionsoft).
module Email
# Create a new email template that can be used for future emails
#
# @param [String] title
# @param [String] categories a comma separated list of the categories
# you want this template in Infusionsoft
# @param [String] from the from address format use is 'FirstName LastName <[email protected]>'
# @param [String] to the email address this template is sent to
# @param [String] cc a comma separated list of cc email addresses
# @param [String] bcc a comma separated list of bcc email addresses
# @param [String] subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
def email_add(title, categories, from, to, cc, bcc, subject, text_body, html_body,
content_type, merge_context)
- response = get('APIEmailService.addEmailTemplate', title, categories, from, to,
+ response = xmlrpc('APIEmailService.addEmailTemplate', title, categories, from, to,
cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
# This will create an item in the email history for a contact. This does not actually
# send the email, it only places an item into the email history. Using the API to
# instruct Infusionsoft to send an email will handle this automatically.
#
# @param [Integer] contact_id
# @param [String] from_name the name portion of the from address, not the email
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_addresses
# @param [String] bcc_addresses
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @param [String] header the header info for this email (will be listed in history)
# @param [Date] receive_date
# @param [Date] sent_date
def email_attach(contact_id, from_name, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, txt_body,
header, receive_date, send_date)
- response = get('APIEmailService.attachEmail', contact_id, from_name, from_address,
+ response = xmlrpc('APIEmailService.attachEmail', contact_id, from_name, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, txt_body, header, receive_date, send_date)
end
# This retrieves all possible merge fields for the context provided.
#
# @param [String] merge_context could include Contact, ServiceCall, Opportunity, or CreditCard
# @return [Array] returns the merge fields for the given context
def email_get_available_merge_fields(merge_context)
- response = get('APIEmailService.getAvailableMergeFields', merge_context)
+ response = xmlrpc('APIEmailService.getAvailableMergeFields', merge_context)
end
# Retrieves the details for a particular email template.
#
# @param [Integer] id
# @return [Hash] all data for the email template
def email_get_template(id)
- response = get('APIEmailService.getEmailTemplate', id)
+ response = xmlrpc('APIEmailService.getEmailTemplate', id)
end
# Retrieves the status of the given email address.
#
# @param [String] email_address
# @return [Integer] 0 = opted out, 1 = single opt-in, 2 = double opt-in
def email_get_opt_status(email_address)
- response = get('APIEmailService.getOptStatus', email_address)
+ response = xmlrpc('APIEmailService.getOptStatus', email_address)
end
# This method opts-in an email address. This method only works the first time
# an email address opts-in.
#
# @param [String] email_address
# @param [String] reason
# This is how you can note why/how this email was opted-in. If a blank
# reason is passed the system will default a reason of "API Opt In"
# @return [Boolean]
def email_optin(email_address, reason)
- response = get('APIEmailService.optIn', email_address, reason)
+ response = xmlrpc('APIEmailService.optIn', email_address, reason)
end
# Opts-out an email address. Note that once an address is opt-out,
# the API cannot opt it back in.
#
# @param [String] email_address
# @param [String] reason
# @return [Boolean]
def email_optout(email_address, reason)
- response = get('APIEmailService.optOut', email_address, reason)
+ response = xmlrpc('APIEmailService.optOut', email_address, reason)
end
# This will send an email to a list of contacts, as well as record the email
# in the contacts' email history.
#
# @param [Array<Integer>] contact_list list of contact ids you want to send this email to
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_address
# @param [String] bcc_address
# @param [String] content_type this must be one of the following Text, HTML, or Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @return [Boolean] returns true/false if the email has been sent
def email_send(contact_list, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, text_body)
- response = get('APIEmailService.sendEmail', contact_list, from_address,
+ response = xmlrpc('APIEmailService.sendEmail', contact_list, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, text_body)
end
# This will send an email to a list of contacts, as well as record the email in the
# contacts' email history.
#
# @param [Array<Integer>] contact_list is an array of Contact id numbers you would like to send this email to
# @param [String] The Id of the template to send
- # @return returns true if the email has been sent, an error will be sent back otherwise.
+ # @return returns true if the email has been sent, an error will be sent back otherwise.
def email_send_template(contact_list, template_id)
- response = get('APIEmailService.sendEmail', contact_list, template_id)
+ response = xmlrpc('APIEmailService.sendEmail', contact_list, template_id)
end
# This method is used to update an already existing email template.
#
# @param [Integer] id
# @param [String] title
# @param [String] category
# @param [String] from
# @param [String] to
# @param [String] cc
# @param [String] bcc
# @param [String subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
# @return [Boolean] returns true/false if teamplate was updated successfully
def email_update_template(id, title, category, from, to, cc, bcc, subject,
text_body, html_body, content_type, merge_context)
- response = get('APIEmailService.updateEmailTemplate', id, title, category, from,
+ response = xmlrpc('APIEmailService.updateEmailTemplate', id, title, category, from,
to, cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
end
end
end
diff --git a/lib/infusionsoft/client/file.rb b/lib/infusionsoft/client/file.rb
index 9d83632..3718fca 100644
--- a/lib/infusionsoft/client/file.rb
+++ b/lib/infusionsoft/client/file.rb
@@ -1,26 +1,26 @@
module Infusionsoft
class Client
module File
def file_upload(contact_id, file_name, encoded_file_base64)
- response = get('FileService.uploadFile', contact_id, file_name, encoded_file_base64)
+ response = xmlrpc('FileService.uploadFile', contact_id, file_name, encoded_file_base64)
end
# returns the Base64 encoded file contents
def file_get(id)
- response = get('FileService.getFile', id)
+ response = xmlrpc('FileService.getFile', id)
end
def file_url(id)
- response = get('FileService.getDownloadUrl', id)
+ response = xmlrpc('FileService.getDownloadUrl', id)
end
def file_rename(id, new_name)
- response = get('FileService.renameFile', id, new_name)
+ response = xmlrpc('FileService.renameFile', id, new_name)
end
def file_replace(id, encoded_file_base64)
- response = get('FileService.replaceFile', id, encoded_file_base64)
+ response = xmlrpc('FileService.replaceFile', id, encoded_file_base64)
end
end
end
end
diff --git a/lib/infusionsoft/client/funnel.rb b/lib/infusionsoft/client/funnel.rb
index ab46276..44102dd 100644
--- a/lib/infusionsoft/client/funnel.rb
+++ b/lib/infusionsoft/client/funnel.rb
@@ -1,18 +1,18 @@
module Infusionsoft
class Client
# Funnel Service is used to add contacts to your sequences
module Funnel
# Achieves a goal, Returns the result of a goal being achieved.
- #
+ #
# @param integration, string, The integration name of the goal. This defaults to the name of the app.
# @param call_name, string, The call name of the goal
# @param cid, int, The id of the contact you want to add to a sequence.
- #
+ #
def funnel_achieve_goal(integration, call_name, cid)
- response = get('FunnelService.achieveGoal', integration, call_name, cid)
+ response = xmlrpc('FunnelService.achieveGoal', integration, call_name, cid)
end
-
+
end
end
end
\ No newline at end of file
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 5e60aca..a839390 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,304 +1,304 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
- response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
+ response = xmlrpc('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
- response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
+ response = xmlrpc('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
- response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
+ response = xmlrpc('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
- response = get('InvoiceService.deleteSubscription', cprogram_id)
+ response = xmlrpc('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
api_logger.warn "[DEPRECATION WARNING]: The invoice_add_subscription method more fully complies with Infusionsoft's published API documents. User is advised to review Infusionsoft's API and this gem's documentation for changes in parameters."
- response = get('InvoiceService.addRecurringOrder', contact_id,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
################### This is a replacement method for invoice_add_recurring_order
# in order to fully support and comply with the Infusionsoft API documentation.
#
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_subscription(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
- response = get('InvoiceService.addRecurringOrder', contact_id,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
- response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
+ response = xmlrpc('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
- response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
+ response = xmlrpc('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
- response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
+ response = xmlrpc('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
- response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
+ response = xmlrpc('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
- response = get('InvoiceService.calculateAmountOwed', invoice_id)
+ response = xmlrpc('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
- response = get('InvoiceService.getAllPaymentOptions')
+ response = xmlrpc('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
- response = get('Invoice.getPayments', invoice_id)
+ response = xmlrpc('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
- response = get('InvoiceService.locateExistingCard', contact_id, last_four)
+ response = xmlrpc('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
- response = get('InvoiceService.recalculateTax', invoice_id)
+ response = xmlrpc('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
- response = get('InvoiceService.validateCreditCard', credit_card_id)
+ response = xmlrpc('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
- response = get('InvoiceService.validateCreditCard', data)
+ response = xmlrpc('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
- response = get('Invoice.getAllShippingOptions')
+ response = xmlrpc('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
- response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
+ response = xmlrpc('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
- response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
+ response = xmlrpc('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# adding a manual payment for an invoice.
# This can be useful when the payments are not handled by Infusionsoft
# but you still needs to makethe invoice as paid
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date (time)
# @param [String] payment_type
# - E.g 'Credit Card'
# @param [String] description
# @param [Boolean] bypass_commissions (Whether this payment
# should count towards affiliate commissions.)
def add_manual_payment(invoice_id, amount, date, payment_type, description, bypass_commission)
- response = get('InvoiceService.addManualPayment', invoice_id, amount,
+ response = xmlrpc('InvoiceService.addManualPayment', invoice_id, amount,
date, payment_type, description, bypass_commission)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
- response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
- response = get('InvoiceService.getInvoiceId', order_id)
+ response = xmlrpc('InvoiceService.getInvoiceId', order_id)
end
end
end
end
diff --git a/lib/infusionsoft/client/search.rb b/lib/infusionsoft/client/search.rb
index 7136de0..33be726 100644
--- a/lib/infusionsoft/client/search.rb
+++ b/lib/infusionsoft/client/search.rb
@@ -1,66 +1,66 @@
module Infusionsoft
class Client
- # The SearchService allows you to retrieve the results of saved searches and reports that
- # have been saved within Infusionsoft. Saved searches/reports are tied to the User that
- # created them. This service also allows you to utilize the quick search function found in
+ # The SearchService allows you to retrieve the results of saved searches and reports that
+ # have been saved within Infusionsoft. Saved searches/reports are tied to the User that
+ # created them. This service also allows you to utilize the quick search function found in
# the upper right hand corner of your Infusionsoft application.
- # @note In order to retrieve the id number for saved searches you will need to utilize
- # the data_query method and query the table called SavedFilter based on the user_id
- # you are looking for the saved search Id for. Also note that UserId field on the
- # SavedFilter table can contain multiple userIdâs separated by a comma, so if you are
- # querying for a report created by userId 6, I recommend appending the wildcard to the
+ # @note In order to retrieve the id number for saved searches you will need to utilize
+ # the data_query method and query the table called SavedFilter based on the user_id
+ # you are looking for the saved search Id for. Also note that UserId field on the
+ # SavedFilter table can contain multiple userIdâs separated by a comma, so if you are
+ # querying for a report created by userId 6, I recommend appending the wildcard to the
# end of the userId. Something like $query = array( âUserIdâ => â6%â );
module Search
# Gets all possible fields/columns available for return on a saved search/report.
#
# @param [Integer] saved_search_id
# @param [Integer] user_id the user id who the saved search is assigned to
# @return [Hash]
def search_get_all_report_columns(saved_search_id, user_id)
- response = get('SearchService.getAllReportColumns', saved_search_id, user_id)
+ response = xmlrpc('SearchService.getAllReportColumns', saved_search_id, user_id)
end
# Runs a saved search/report and returns all possible fields.
#
# @param [Integer] saved_search_id
# @param [Integer] user_id the user id who the saved search is assigned to
# @param [Integer] page_number
# @return [Hash]
def search_get_saved_search_results(saved_search_id, user_id, page_number)
- response = get('SearchService.getSavedSearchResultsAllFields', saved_search_id,
+ response = xmlrpc('SearchService.getSavedSearchResultsAllFields', saved_search_id,
user_id, page_number)
end
# This is used to find what possible quick searches the given user has access to.
#
# @param [Integer] user_id
- # @return [Array]
+ # @return [Array]
def search_get_available_quick_searches(user_id)
- response = get('SearchService.getAvailableQuickSearches', user_id)
+ response = xmlrpc('SearchService.getAvailableQuickSearches', user_id)
end
- # This allows you to run a quick search via the API. The quick search is the
+ # This allows you to run a quick search via the API. The quick search is the
# search bar in the upper right hand corner of the Infusionsoft application
#
# @param [String] search_type the type of search (Person, Order, Opportunity, Company, Task,
# Subscription, or Affiliate)
# @param [Integer] user_id
# @param [String] search_data
# @param [Integer] page
# @param [Integer] limit max is 1000
# @return [Array<Hash>]
def search_quick_search(search_type, user_id, search_data, page, limit)
- response = get('SearchService.quickSearch', search_type, user_id, search_data, page, limit)
+ response = xmlrpc('SearchService.quickSearch', search_type, user_id, search_data, page, limit)
end
# Retrieves the quick search type that the given users has set as their default.
#
# @param [Integer] user_id
# @return [String] the quick search type that the given user selected as their default
def search_get_default_search_type(user_id)
- response = get('SearchService.getDefaultQuickSearch', user_id)
+ response = xmlrpc('SearchService.getDefaultQuickSearch', user_id)
end
end
end
end
diff --git a/lib/infusionsoft/client/ticket.rb b/lib/infusionsoft/client/ticket.rb
index 89f3bf0..841ea45 100644
--- a/lib/infusionsoft/client/ticket.rb
+++ b/lib/infusionsoft/client/ticket.rb
@@ -1,18 +1,18 @@
module Infusionsoft
class Client
module Ticket
# add move notes to existing tickets
- def ticket_add_move_notes(ticket_list, move_notes,
+ def ticket_add_move_notes(ticket_list, move_notes,
move_to_stage_id, notify_ids)
- response = get('ServiceCallService.addMoveNotes', ticket_list,
+ response = xmlrpc('ServiceCallService.addMoveNotes', ticket_list,
move_notes, move_to_stage_id, notify_ids)
end
# add move notes to existing tickets
def ticket_move_stage(ticket_id, ticket_stage, move_notes, notify_ids)
- response = get('ServiceCallService.moveTicketStage',
+ response = xmlrpc('ServiceCallService.moveTicketStage',
ticket_id, ticket_stage, move_notes, notify_ids)
end
end
end
end
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d3b95ae..12e6ac6 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,34 +1,52 @@
+require 'rest-client'
+
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
+ def xmlrpc(servic_call, *args)
+ connection(service_call, *args)
+ end
+
# Perform an GET request
- def get(service_call, *args)
- request(:get, service_call, *args)
+ def get(path, token, query: {})
+ request(:get, path, token, query: query )
end
- def post(path, params={}, options={})
- request(:post, path, params, options)
+ def post(path, token, query: {}, payload: {})
+ request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
- def put(path, params={}, options={})
- request(:put, path, params, options)
+ def put(path, token, query: {}, payload: {})
+ request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
- def delete(path, params={}, options={})
- request(:delete, path, params, options)
+ def delete(path, token, query: {})
+ request(:delete, path, token, query)
end
-
private
# Perform request
- def request(method, service_call, *args)
- case method.to_sym
- when :get
- response = connection(service_call, *args)
- end
+ def request(method, path, token, query={}, payload={})
+ path = "/#{path}" unless path.start_with?('/')
+ header = {
+ authorization: "Bearer #{token.access_token}",
+ content_type: :json,
+ accept: :json,
+ params: query
+ }
+ opts = {
+ method: method,
+ url: "https://api.infusionsoft.com/crm/rest/v1" + path,
+ headers: header
+ }
+ opts.merge!( { payload: payload.to_json }) unless payload.empty?
+ resp = RestClient::Request.execute(opts)
+ rescue RestClient::ExceptionWithResponse => err
+ # log error?
+ else
+ return JSON.parse(resp.body)
end
- end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
new file mode 100644
index 0000000..b2ee56b
--- /dev/null
+++ b/lib/infusionsoft/rest/token.rb
@@ -0,0 +1,71 @@
+require 'rest-client'
+require 'uri'
+
+class Rest::Token
+
+ attr_accessor :access_token, :refresh_token, :expiration
+
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
+
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
+ end
+
+ def valid?
+ Time.now < expiration
+ end
+
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
+
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
+
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
+
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
+
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ end
+
+end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
b18f15f6cfb290515558e7eddd2f200e7807f03a
|
Updating some calls to have optional email optin status By default, the gem will no longer blindly opt people in. You must specify the reason for opting in when adding a contact.
|
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index 34db7b2..8ba2ff1 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,197 +1,208 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
- # @param [Hash] data contains the mappable contact fields and it's data
+ # @param [Hash] data contains the mappable contact fields and it's data.
+ # @param [String] (Optional) email opt in verbiage. The contact will then be
+ # "Opted in" using the verviage supplied here.
# @return [Integer] the id of the newly added contact
# @example
- # { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }
- def contact_add(data)
+ # { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'New Signup'
+ def contact_add(data, optin_status=nil)
contact_id = get('ContactService.add', data)
- if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
+ email = data['Email'] || data[:Email]
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
-
+
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
response = get('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
+ # @param [String] (Optional) email opt in verbiage. The contact will then be
+ # "Opted in" using the verviage supplied here.
# @return [Integer] id of the contact added or updated
- def contact_add_with_dup_check(data, check_type)
+ # @example
+ # { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }, 'Email', 'New Signup'
+ def contact_add_with_dup_check(data, check_type, optin_status=nil)
contact_id = get('ContactService.addWithDupCheck', data, check_type)
- if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
+ email = data['Email'] || data[:Email]
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
+ # @param [String] (Optional) email opt in verbiage. The contact will then be
+ # "Opted in" using the verviage supplied here.
# @return [Integer] the id of the contact updated
# @example
- # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }
- def contact_update(contact_id, data)
+ # { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }, 'New Signup'
+ def contact_update(contact_id, data, optin_status=nil)
contact_id = get('ContactService.update', contact_id, data)
- if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
+ email = data['Email'] || data[:Email]
+ if optin_status && email; email_optin(email, optin_status); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
response = get('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
response = get('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
response = get('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
response = get('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
response = get('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
response = get('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
response = get('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
response = get('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
response = get('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
response = get('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
response = get('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
response = get('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
response = get('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 09b6b46..365b8b1 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.2.2'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.0a'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
ebfb4f2d5f8454d9924d6db72ac2287928f6afe3
|
fixing typo
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index e5ab912..facd18a 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,77 +1,77 @@
require 'rest-client'
require 'uri'
require 'json'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
@access_token = token_params[:access_token] || token_params["access_token"]
@refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
@expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in] || token_params["expires_in"]
@expiration = Time.now + (token_params[:expires_in] || token_params["expires_in"])
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- rescue RestClient::ExceptionWithRespone => e
+ rescue RestClient::ExceptionWithResponse => e
#TODO what to do here?
false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
-end
\ No newline at end of file
+end
|
nateleavitt/infusionsoft
|
2a9e8d99731b7b071b5dcd2323c411d1fe1a2af0
|
Bumping to 1.3.1a
|
diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec
index 8e0c2c9..b707244 100644
--- a/infusionsoft.gemspec
+++ b/infusionsoft.gemspec
@@ -1,21 +1,22 @@
# encoding: utf-8
require File.expand_path('../lib/infusionsoft/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'infusionsoft'
gem.summary = %q{Ruby wrapper for the Infusionsoft API}
gem.description = 'A Ruby wrapper written for the Infusionsoft API'
gem.authors = ["Nathan Leavitt"]
gem.email = ['[email protected]']
# gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = 'https://github.com/nateleavitt/infusionsoft'
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6')
gem.add_development_dependency 'rake'
+ gem.add_dependency "xmlrpc"
gem.add_dependency "rest-client"
gem.version = Infusionsoft::VERSION.dup
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 09b6b46..00bdbfa 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.2.2'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.3.1a'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
bc136c4e530768a7a506624d50e359fc61617bd8
|
Fix parsing of token
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 428cc14..e5ab912 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,77 @@
require 'rest-client'
require 'uri'
+require 'json'
+
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
- access_token = token_params[:access_token] || token_params["access_token"]
- refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
- expiration = token_params[:expiration] if token_params[:expiration]
+ @access_token = token_params[:access_token] || token_params["access_token"]
+ @refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
+ @expiration = token_params[:expiration] if token_params[:expiration]
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in] || token_params["expires_in"]
+ if token_params[:expires_in] || token_params["expires_in"]
+ @expiration = Time.now + (token_params[:expires_in] || token_params["expires_in"])
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
+ false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
+ false
else
token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
92151e88c22b2cf58795c7647d79f0ef33aa8ab8
|
No symbolize keys method without rails
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index f62d3b5..428cc14 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
+ access_token = token_params[:access_token] || token_params["access_token"]
+ refresh_token = token_params[:refresh_token] || token_params["refresh_token"]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in] || token_params["expires_in"]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
- token_params = JSON.parse(response.body).symbolize_keys
+ token_params = JSON.parse(response.body)
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
- token_params = JSON.parse(response.body).symbolize_keys
+ token_params = JSON.parse(response.body)
self.new(token_params)
end
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
d3f60ee060f0f4a6a43d5f127ee06a063cd782d9
|
Fixing service_name call
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d656adc..e771cb0 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,53 +1,53 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
- def xmlrpc(servic_call, *args)
+ def xmlrpc(service_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
# log error?
else
return JSON.parse(resp.body)
end
end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index f97d13d..f62d3b5 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,73 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
- class Token
+ class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
access_token = token_params[:access_token]
refresh_token = token_params[:refresh_token]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
expiration = Time.now + token_params[:expires_in]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
end
-
end
+
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
667d9fb085bb088b4005d1eed1a12344aee64a76
|
fixing namespace on gem
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 12e6ac6..d656adc 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,52 +1,53 @@
require 'rest-client'
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
def xmlrpc(servic_call, *args)
connection(service_call, *args)
end
# Perform an GET request
def get(path, token, query: {})
request(:get, path, token, query: query )
end
def post(path, token, query: {}, payload: {})
request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
def put(path, token, query: {}, payload: {})
request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
def delete(path, token, query: {})
request(:delete, path, token, query)
end
private
# Perform request
def request(method, path, token, query={}, payload={})
path = "/#{path}" unless path.start_with?('/')
header = {
authorization: "Bearer #{token.access_token}",
content_type: :json,
accept: :json,
params: query
}
opts = {
method: method,
url: "https://api.infusionsoft.com/crm/rest/v1" + path,
headers: header
}
opts.merge!( { payload: payload.to_json }) unless payload.empty?
resp = RestClient::Request.execute(opts)
rescue RestClient::ExceptionWithResponse => err
# log error?
else
return JSON.parse(resp.body)
end
+ end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 95d7f6b..f97d13d 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,74 +1,73 @@
require 'rest-client'
require 'uri'
module Infusionsoft
module Rest
class Token
attr_accessor :access_token, :refresh_token, :expiration
def initialize(token_params)
access_token = token_params[:access_token]
refresh_token = token_params[:refresh_token]
expiration = token_params[:expiration] if token_params[:expiration]
if token_params[:expires_in]
expiration = Time.now + token_params[:expires_in]
end
end
def valid?
Time.now < expiration
end
class << self
def auth_url(client_id, redirect_uri)
params = {
client_id: client_id,
redirect_uri: redirect_uri,
scope: 'full',
response_type: 'code'
}
uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
uri.to_s
end
def refresh(client_id, client_secret, refresh_token)
params = {
grant_type: 'refresh_token',
refresh_token: refresh_token,
}
header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
response = RestClient.post("https://api.infusionsoft.com/token", params, header)
rescue RestClient::ExceptionWithRespone => e
#TODO what to do here?
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
def get_token(client_id, client_secret, redirect_uri, code)
params = {
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirect_uri,
code: code,
grant_type: 'authorization_code',
}
response = RestClient.post("https://api.infusionsoft.com/token", params)
rescue RestClient::ExceptionWithResponse => e
# TODO: what to do here
else
token_params = JSON.parse(response.body).symbolize_keys
self.new(token_params)
end
-
end
end
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
19c87a80daa6d2bca7201b4eb5ae031ebf56f73a
|
include module rest
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index 3dc9148..95d7f6b 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,72 +1,74 @@
require 'rest-client'
require 'uri'
module Infusionsoft
- class Rest::Token
+ module Rest
+ class Token
- attr_accessor :access_token, :refresh_token, :expiration
+ attr_accessor :access_token, :refresh_token, :expiration
- def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
- expiration = token_params[:expiration] if token_params[:expiration]
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
end
- end
- def valid?
- Time.now < expiration
- end
+ def valid?
+ Time.now < expiration
+ end
- class << self
- def auth_url(client_id, redirect_uri)
- params = {
- client_id: client_id,
- redirect_uri: redirect_uri,
- scope: 'full',
- response_type: 'code'
- }
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
- uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
- uri.to_s
- end
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
- def refresh(client_id, client_secret, refresh_token)
- params = {
- grant_type: 'refresh_token',
- refresh_token: refresh_token,
- }
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
- header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
- response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- rescue RestClient::ExceptionWithRespone => e
- #TODO what to do here?
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
- end
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
- def get_token(client_id, client_secret, redirect_uri, code)
- params = {
- client_id: client_id,
- client_secret: client_secret,
- redirect_uri: redirect_uri,
- code: code,
- grant_type: 'authorization_code',
- }
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- response = RestClient.post("https://api.infusionsoft.com/token", params)
- rescue RestClient::ExceptionWithResponse => e
- # TODO: what to do here
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
end
end
-
end
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
65c01a84e4c3b3ab594c430177f1ea614a0b538f
|
Adding rest/token into base class
|
diff --git a/lib/infusionsoft.rb b/lib/infusionsoft.rb
index b507b13..d0c420d 100644
--- a/lib/infusionsoft.rb
+++ b/lib/infusionsoft.rb
@@ -1,27 +1,28 @@
require 'infusionsoft/api'
require 'infusionsoft/client'
require 'infusionsoft/configuration'
require 'infusionsoft/api_logger'
+require 'infusionsoft/rest/token'
module Infusionsoft
extend Configuration
class << self
# Alias for Infusionsoft::Client.new
#
# @return [Infusionsoft::Client]
def new(options={})
Infusionsoft::Client.new(options)
end
# Delegate to ApiInfusionsoft::Client
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method, include_private = false)
new.respond_to?(method, include_private) || super(method, include_private)
end
end
end
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index e3cd302..111ffeb 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,33 +1,31 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
- require 'infusionsoft/rest/token'
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
require 'infusionsoft/client/funnel'
- include Infusionsoft::Rest::Token
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
include Infusionsoft::Client::Funnel
end
end
|
nateleavitt/infusionsoft
|
54c5aae2c2696afe894a59d66d934c7411fa7d52
|
include Infusionsoft module
|
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
index b2ee56b..3dc9148 100644
--- a/lib/infusionsoft/rest/token.rb
+++ b/lib/infusionsoft/rest/token.rb
@@ -1,71 +1,72 @@
require 'rest-client'
require 'uri'
+module Infusionsoft
+ class Rest::Token
-class Rest::Token
+ attr_accessor :access_token, :refresh_token, :expiration
- attr_accessor :access_token, :refresh_token, :expiration
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
- def initialize(token_params)
- access_token = token_params[:access_token]
- refresh_token = token_params[:refresh_token]
- expiration = token_params[:expiration] if token_params[:expiration]
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
+ end
- if token_params[:expires_in]
- expiration = Time.now + token_params[:expires_in]
+ def valid?
+ Time.now < expiration
end
- end
- def valid?
- Time.now < expiration
- end
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
- class << self
- def auth_url(client_id, redirect_uri)
- params = {
- client_id: client_id,
- redirect_uri: redirect_uri,
- scope: 'full',
- response_type: 'code'
- }
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
- uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
- uri.to_s
- end
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
- def refresh(client_id, client_secret, refresh_token)
- params = {
- grant_type: 'refresh_token',
- refresh_token: refresh_token,
- }
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
- header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
- response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- rescue RestClient::ExceptionWithRespone => e
- #TODO what to do here?
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
- end
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
- def get_token(client_id, client_secret, redirect_uri, code)
- params = {
- client_id: client_id,
- client_secret: client_secret,
- redirect_uri: redirect_uri,
- code: code,
- grant_type: 'authorization_code',
- }
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
- response = RestClient.post("https://api.infusionsoft.com/token", params)
- rescue RestClient::ExceptionWithResponse => e
- # TODO: what to do here
- else
- token_params = JSON.parse(response.body).symbolize_keys
- self.new(token_params)
end
end
-
end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
a707e33e8e513798465bd7b2201a0ede38372939
|
Require Infusionsoft Rest Token in client
|
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index 111ffeb..e3cd302 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,31 +1,33 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
+ require 'infusionsoft/rest/token'
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
require 'infusionsoft/client/funnel'
+ include Infusionsoft::Rest::Token
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
include Infusionsoft::Client::Funnel
end
end
|
nateleavitt/infusionsoft
|
6a32cd22c31608da693b2d7e32811684c80d5d22
|
Build out token and request methods
|
diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec
index b5145b8..8e0c2c9 100644
--- a/infusionsoft.gemspec
+++ b/infusionsoft.gemspec
@@ -1,19 +1,21 @@
# encoding: utf-8
require File.expand_path('../lib/infusionsoft/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'infusionsoft'
gem.summary = %q{Ruby wrapper for the Infusionsoft API}
gem.description = 'A Ruby wrapper written for the Infusionsoft API'
gem.authors = ["Nathan Leavitt"]
gem.email = ['[email protected]']
# gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = 'https://github.com/nateleavitt/infusionsoft'
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6')
gem.add_development_dependency 'rake'
+ gem.add_dependency "rest-client"
+
gem.version = Infusionsoft::VERSION.dup
end
diff --git a/lib/infusionsoft/client/affiliate.rb b/lib/infusionsoft/client/affiliate.rb
index a3b8f47..2552829 100644
--- a/lib/infusionsoft/client/affiliate.rb
+++ b/lib/infusionsoft/client/affiliate.rb
@@ -1,62 +1,62 @@
module Infusionsoft
class Client
# The Affiliate service is used to pull commission data and activities for affiliates.
# With this service, you have access to Clawbacks, Commissions, Payouts, Running Totals,
# and the Activity Summary. The methods in the Affiliate service mirror the reports
# produced inside Infusionsoft.
#
# @note To manage affiliate information (ie Name, Phone, etc.) you will need to use the Data service.
module Affiliate
# Used when you need to retrieve all clawed back commissions for a particular affiliate.
#
# @param [Integer] affiliate_id
# @params [Date] start_date
# @end_date [Date] end_date
# @return [Array] all claw backs for the given affiliate that have occurred within the date
# range specified
def affiliate_clawbacks(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affClawbacks', affiliate_id, start_date, end_date)
end
# Used to retrieve all commissions for a specific affiliate within a date range.
#
# @param [Integer] affiliate_id
# @param [Date] start_date
# @param [Date] end_date
# @return [Array] all sales commissions for the given affiliate earned within the date range
# specified
def affiliate_commissions(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affCommissions', affiliate_id, start_date, end_date)
end
# Used to retrieve all payments for a specific affiliate within a date range.
#
# @param [Integer] affiliate_id
# @param [Date] start_date
# @param [Date] end_date
# @return [Array] a list of rows, each row is a single payout
def affiliate_payouts(affiliate_id, start_date, end_date)
- response = get('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affPayouts', affiliate_id, start_date, end_date)
end
# This method is used to retrieve all commissions for a specific affiliate within a date range.
#
# @param [Array] affiliate_list
# @return [Array] all sales commissions for the given affiliate earned within the date range
# specified
def affiliate_running_totals(affiliate_list)
- response = get('APIAffiliateService.affRunningTotals', affiliate_list)
+ response = xmlrpc('APIAffiliateService.affRunningTotals', affiliate_list)
end
# Used to retrieve a summary of statistics for a list of affiliates.
#
# @param [Array] affiliate_list
# @param [Date] start_date
# @param [Date] end_date
# @return [Array<Hash>] a summary of the affiliates information for a specified date range
def affiliate_summary(affiliate_list, start_date, end_date)
- response = get('APIAffiliateService.affSummary', affiliate_list, start_date, end_date)
+ response = xmlrpc('APIAffiliateService.affSummary', affiliate_list, start_date, end_date)
end
end
end
end
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index 34db7b2..868d972 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,197 +1,197 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
# @param [Hash] data contains the mappable contact fields and it's data
# @return [Integer] the id of the newly added contact
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }
def contact_add(data)
- contact_id = get('ContactService.add', data)
+ contact_id = xmlrpc('ContactService.add', data)
if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
-
+
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
- response = get('ContactService.merge', contact_id, duplicate_contact_id)
+ response = xmlrpc('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
# @return [Integer] id of the contact added or updated
def contact_add_with_dup_check(data, check_type)
- contact_id = get('ContactService.addWithDupCheck', data, check_type)
+ contact_id = xmlrpc('ContactService.addWithDupCheck', data, check_type)
if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
# @return [Integer] the id of the contact updated
# @example
# { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }
def contact_update(contact_id, data)
- contact_id = get('ContactService.update', contact_id, data)
+ contact_id = xmlrpc('ContactService.update', contact_id, data)
if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
- response = get('ContactService.load', id, selected_fields)
+ response = xmlrpc('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
- response = get('ContactService.findByEmail', email, selected_fields)
+ response = xmlrpc('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
- response = get('ContactService.addToCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
- response = get('ContactService.getNextCampaignStep', contact_id, campaign_id)
+ response = xmlrpc('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
- response = get('ContactService.pauseCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
- response = get('ContactService.removeFromCampaign', contact_id, campaign_id)
+ response = xmlrpc('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
- response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id)
+ response = xmlrpc('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
- response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
+ response = xmlrpc('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
- response = get('ContactService.removeFromGroup', contact_id, group_id)
+ response = xmlrpc('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
- response = get('ContactService.addToGroup', contact_id, group_id)
+ response = xmlrpc('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
- response = get('ContactService.runActionSequence', contact_id, action_set_id)
+ response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
- response = get('ContactService.linkContact', remoteApp, remoteId, localId)
+ response = xmlrpc('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
- response = get('ContactService.locateContactLink', locate_map_id)
+ response = xmlrpc('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
- response = get('ContactService.markLinkUpdated', locate_map_id)
+ response = xmlrpc('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
- response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
+ response = xmlrpc('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
- response = get('ContactService.runActionSequence', contact_id, action_set_id, data)
+ response = xmlrpc('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
diff --git a/lib/infusionsoft/client/credit_card.rb b/lib/infusionsoft/client/credit_card.rb
index 502c43d..df3f669 100644
--- a/lib/infusionsoft/client/credit_card.rb
+++ b/lib/infusionsoft/client/credit_card.rb
@@ -1,24 +1,24 @@
module Infusionsoft
class Client
- # CreditCardSubmission service is used to obtain a token that is to be submitted
- # through a form when adding a credit card. In accordance with PCI compliance,
+ # CreditCardSubmission service is used to obtain a token that is to be submitted
+ # through a form when adding a credit card. In accordance with PCI compliance,
# adding credit cards through the API will no longer be supported.
module CreditCard
# This service will request a token that will be used when submitting
# a new credit card through a form
#
# @param [Integer] contact_id of the Infusionsoft contact
# @param [String] url that will be redirected to upon successfully adding card
# @param [String] url that will be redirected to when there is a failure upon adding card
def credit_card_request_token(contact_id, success_url, failure_url)
- response = get('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url)
+ response = xmlrpc('CreditCardSubmissionService.requestSubmissionToken', contact_id, success_url, failure_url)
end
def credit_card_lookup_by_token(token)
- response = get('CreditCardSubmissionService.requestCreditCardId', token)
+ response = xmlrpc('CreditCardSubmissionService.requestCreditCardId', token)
end
end
end
end
diff --git a/lib/infusionsoft/client/data.rb b/lib/infusionsoft/client/data.rb
index e277302..674b00c 100644
--- a/lib/infusionsoft/client/data.rb
+++ b/lib/infusionsoft/client/data.rb
@@ -1,146 +1,146 @@
module Infusionsoft
class Client
# The Data service is used to manipulate most data in Infusionsoft. It permits you to
# work on any available tables and has a wide range of uses.
module Data
# Adds a record with the data provided.
#
# @param [String] table the name of the Infusiosoft database table
# @param [Hash] data the fields and it's data
# @return [Integer] returns the id of the record added
def data_add(table, data)
- response = get('DataService.add', table, data)
+ response = xmlrpc('DataService.add', table, data)
end
# This method will load a record from the database given the primary key.
#
# @param [String] table
# @param [Integer] id
# @param [Array] selected_fields
# @return [Hash] the field names and their data
# @example
# { "FirstName" => "John", "LastName" => "Doe" }
def data_load(table, id, selected_fields)
- response = get('DataService.load', table, id, selected_fields)
+ response = xmlrpc('DataService.load', table, id, selected_fields)
end
# Updates the specified record (indicated by ID) with the data provided.
#
# @param [String] table
# @param [Integer] id
# @param [Hash] data this is the fields and values you would like to update
# @return [Integer] id of the record updated
# @example
# { :FirstName => 'John', :Email => '[email protected]' }
def data_update(table, id, data)
- response = get('DataService.update', table, id, data)
+ response = xmlrpc('DataService.update', table, id, data)
end
# Deletes the record (specified by id) in the given table from the database.
#
# @param [String] table
# @param [Integer] id
# @return [Boolean] returns true/false if the record was successfully deleted
def data_delete(table, id)
- response = get('DataService.delete', table, id)
+ response = xmlrpc('DataService.delete', table, id)
end
# This will locate all records in a given table that match the criteria for a given field.
#
# @param [String] table
# @param [Integer] limit how many records you would like to return (max is 1000)
# @param [Integer] page the page of results (each page is max 1000 records)
# @param [String] field_name
# @param [String, Integer, Date] field_value
# @param [Array] selected_fields
# @return [Array<Hash>] returns the array of records with a hash of the fields and values
def data_find_by_field(table, limit, page, field_name, field_value, selected_fields)
- response = get('DataService.findByField', table, limit, page, field_name,
+ response = xmlrpc('DataService.findByField', table, limit, page, field_name,
field_value, selected_fields)
end
# Queries records in a given table to find matches on certain fields.
#
# @param [String] table
# @param [Integer] limit
# @param [Integer] page
# @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' }
# @param [Array] selected_fields the fields and values you want back
# @return [Array<Hash>] the fields and associated values
def data_query(table, limit, page, data, selected_fields)
- response = get('DataService.query', table, limit, page, data, selected_fields)
+ response = xmlrpc('DataService.query', table, limit, page, data, selected_fields)
end
# Queries records in a given table to find matches on certain fields.
#
# @param [String] table
# @param [Integer] limit
# @param [Integer] page
# @param [Hash] data the data you would like to query on. { :FirstName => 'first_name' }
# @param [Array] selected_fields the fields and values you want back
# @param [String] field by which to order the output results
# @param [Boolean] true ascending, false descending
# @return [Array<Hash>] the fields and associated values
def data_query_order_by(table, limit, page, data, selected_fields, by, ascending)
- response = get('DataService.query', table, limit, page, data, selected_fields, by, ascending)
+ response = xmlrpc('DataService.query', table, limit, page, data, selected_fields, by, ascending)
end
# Adds a custom field to Infusionsoft
#
# @param [String] field_type options include Person, Company, Affiliate, Task/Appt/Note,
# Order, Subscription, or Opportunity
# @param [String] name
# @param [String] data_type the type of field Text, Dropdown, TextArea
# @param [Integer] header_id see notes here
# http://help.infusionsoft.com/developers/services-methods/data/addCustomField
def data_add_custom_field(field_type, name, data_type, header_id)
- response = get('DataService.addCustomField', field_type, name, data_type, header_id)
+ response = xmlrpc('DataService.addCustomField', field_type, name, data_type, header_id)
end
# Authenticate an Infusionsoft username and password(md5 hash). If the credentials match
# it will return back a User ID, if the credentials do not match it will send back an
# error message
#
# @param [String] username
# @param [String] password
# @return [Integer] id of the authenticated user
def data_authenticate_user(username, password)
- response = get('DataService.authenticateUser', username, password)
+ response = xmlrpc('DataService.authenticateUser', username, password)
end
# This method will return back the data currently configured in a user configured
# application setting.
#
# @param [String] module
# @param [String] setting
# @return [String] current values in given application setting
# @note to find the module and option names, view the HTML field name within the Infusionsoft
# settings. You will see something such as name="Contact_WebModule0optiontypes" . The portion
# before the underscore is the module name. "Contact" in this example. The portion after the
# 0 is the setting name, "optiontypes" in this example.
def data_get_app_setting(module_name, setting)
- response = get('DataService.getAppSetting', module_name, setting)
+ response = xmlrpc('DataService.getAppSetting', module_name, setting)
end
# Returns a temporary API key if given a valid Vendor key and user credentials.
#
# @param [String] vendor_key
# @param [String] username
# @param [String] password_hash an md5 hash of users password
# @return [String] temporary API key
def data_get_temporary_key(vendor_key, username, password_hash)
- response = get('DataService.getTemporaryKey', username, password_hash)
+ response = xmlrpc('DataService.getTemporaryKey', username, password_hash)
end
# Updates a custom field. Every field can have itâs display name and group id changed,
# but only certain data types will allow you to change values(dropdown, listbox, radio, etc).
#
# @param [Integer] field_id
# @param [Hash] field_values
# @return [Boolean] returns true/false if it was updated
def data_update_custom_field(field_id, field_values)
- response = get('DataService.updateCustomField', field_id, field_values)
+ response = xmlrpc('DataService.updateCustomField', field_id, field_values)
end
end
end
end
diff --git a/lib/infusionsoft/client/email.rb b/lib/infusionsoft/client/email.rb
index 7f62fda..3b63b12 100644
--- a/lib/infusionsoft/client/email.rb
+++ b/lib/infusionsoft/client/email.rb
@@ -1,152 +1,152 @@
module Infusionsoft
class Client
# The Email service allows you to email your contacts as well as attaching emails sent
# elsewhere (this lets you send email from multiple services and still see all communications
# inside of Infusionsoft).
module Email
# Create a new email template that can be used for future emails
#
# @param [String] title
# @param [String] categories a comma separated list of the categories
# you want this template in Infusionsoft
# @param [String] from the from address format use is 'FirstName LastName <[email protected]>'
# @param [String] to the email address this template is sent to
# @param [String] cc a comma separated list of cc email addresses
# @param [String] bcc a comma separated list of bcc email addresses
# @param [String] subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
def email_add(title, categories, from, to, cc, bcc, subject, text_body, html_body,
content_type, merge_context)
- response = get('APIEmailService.addEmailTemplate', title, categories, from, to,
+ response = xmlrpc('APIEmailService.addEmailTemplate', title, categories, from, to,
cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
# This will create an item in the email history for a contact. This does not actually
# send the email, it only places an item into the email history. Using the API to
# instruct Infusionsoft to send an email will handle this automatically.
#
# @param [Integer] contact_id
# @param [String] from_name the name portion of the from address, not the email
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_addresses
# @param [String] bcc_addresses
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @param [String] header the header info for this email (will be listed in history)
# @param [Date] receive_date
# @param [Date] sent_date
def email_attach(contact_id, from_name, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, txt_body,
header, receive_date, send_date)
- response = get('APIEmailService.attachEmail', contact_id, from_name, from_address,
+ response = xmlrpc('APIEmailService.attachEmail', contact_id, from_name, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, txt_body, header, receive_date, send_date)
end
# This retrieves all possible merge fields for the context provided.
#
# @param [String] merge_context could include Contact, ServiceCall, Opportunity, or CreditCard
# @return [Array] returns the merge fields for the given context
def email_get_available_merge_fields(merge_context)
- response = get('APIEmailService.getAvailableMergeFields', merge_context)
+ response = xmlrpc('APIEmailService.getAvailableMergeFields', merge_context)
end
# Retrieves the details for a particular email template.
#
# @param [Integer] id
# @return [Hash] all data for the email template
def email_get_template(id)
- response = get('APIEmailService.getEmailTemplate', id)
+ response = xmlrpc('APIEmailService.getEmailTemplate', id)
end
# Retrieves the status of the given email address.
#
# @param [String] email_address
# @return [Integer] 0 = opted out, 1 = single opt-in, 2 = double opt-in
def email_get_opt_status(email_address)
- response = get('APIEmailService.getOptStatus', email_address)
+ response = xmlrpc('APIEmailService.getOptStatus', email_address)
end
# This method opts-in an email address. This method only works the first time
# an email address opts-in.
#
# @param [String] email_address
# @param [String] reason
# This is how you can note why/how this email was opted-in. If a blank
# reason is passed the system will default a reason of "API Opt In"
# @return [Boolean]
def email_optin(email_address, reason)
- response = get('APIEmailService.optIn', email_address, reason)
+ response = xmlrpc('APIEmailService.optIn', email_address, reason)
end
# Opts-out an email address. Note that once an address is opt-out,
# the API cannot opt it back in.
#
# @param [String] email_address
# @param [String] reason
# @return [Boolean]
def email_optout(email_address, reason)
- response = get('APIEmailService.optOut', email_address, reason)
+ response = xmlrpc('APIEmailService.optOut', email_address, reason)
end
# This will send an email to a list of contacts, as well as record the email
# in the contacts' email history.
#
# @param [Array<Integer>] contact_list list of contact ids you want to send this email to
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_address
# @param [String] bcc_address
# @param [String] content_type this must be one of the following Text, HTML, or Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @return [Boolean] returns true/false if the email has been sent
def email_send(contact_list, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, text_body)
- response = get('APIEmailService.sendEmail', contact_list, from_address,
+ response = xmlrpc('APIEmailService.sendEmail', contact_list, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, text_body)
end
# This will send an email to a list of contacts, as well as record the email in the
# contacts' email history.
#
# @param [Array<Integer>] contact_list is an array of Contact id numbers you would like to send this email to
# @param [String] The Id of the template to send
- # @return returns true if the email has been sent, an error will be sent back otherwise.
+ # @return returns true if the email has been sent, an error will be sent back otherwise.
def email_send_template(contact_list, template_id)
- response = get('APIEmailService.sendEmail', contact_list, template_id)
+ response = xmlrpc('APIEmailService.sendEmail', contact_list, template_id)
end
# This method is used to update an already existing email template.
#
# @param [Integer] id
# @param [String] title
# @param [String] category
# @param [String] from
# @param [String] to
# @param [String] cc
# @param [String] bcc
# @param [String subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
# @return [Boolean] returns true/false if teamplate was updated successfully
def email_update_template(id, title, category, from, to, cc, bcc, subject,
text_body, html_body, content_type, merge_context)
- response = get('APIEmailService.updateEmailTemplate', id, title, category, from,
+ response = xmlrpc('APIEmailService.updateEmailTemplate', id, title, category, from,
to, cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
end
end
end
diff --git a/lib/infusionsoft/client/file.rb b/lib/infusionsoft/client/file.rb
index 9d83632..3718fca 100644
--- a/lib/infusionsoft/client/file.rb
+++ b/lib/infusionsoft/client/file.rb
@@ -1,26 +1,26 @@
module Infusionsoft
class Client
module File
def file_upload(contact_id, file_name, encoded_file_base64)
- response = get('FileService.uploadFile', contact_id, file_name, encoded_file_base64)
+ response = xmlrpc('FileService.uploadFile', contact_id, file_name, encoded_file_base64)
end
# returns the Base64 encoded file contents
def file_get(id)
- response = get('FileService.getFile', id)
+ response = xmlrpc('FileService.getFile', id)
end
def file_url(id)
- response = get('FileService.getDownloadUrl', id)
+ response = xmlrpc('FileService.getDownloadUrl', id)
end
def file_rename(id, new_name)
- response = get('FileService.renameFile', id, new_name)
+ response = xmlrpc('FileService.renameFile', id, new_name)
end
def file_replace(id, encoded_file_base64)
- response = get('FileService.replaceFile', id, encoded_file_base64)
+ response = xmlrpc('FileService.replaceFile', id, encoded_file_base64)
end
end
end
end
diff --git a/lib/infusionsoft/client/funnel.rb b/lib/infusionsoft/client/funnel.rb
index ab46276..44102dd 100644
--- a/lib/infusionsoft/client/funnel.rb
+++ b/lib/infusionsoft/client/funnel.rb
@@ -1,18 +1,18 @@
module Infusionsoft
class Client
# Funnel Service is used to add contacts to your sequences
module Funnel
# Achieves a goal, Returns the result of a goal being achieved.
- #
+ #
# @param integration, string, The integration name of the goal. This defaults to the name of the app.
# @param call_name, string, The call name of the goal
# @param cid, int, The id of the contact you want to add to a sequence.
- #
+ #
def funnel_achieve_goal(integration, call_name, cid)
- response = get('FunnelService.achieveGoal', integration, call_name, cid)
+ response = xmlrpc('FunnelService.achieveGoal', integration, call_name, cid)
end
-
+
end
end
end
\ No newline at end of file
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 5e60aca..a839390 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,304 +1,304 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
- response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
+ response = xmlrpc('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
- response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
+ response = xmlrpc('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
- response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
+ response = xmlrpc('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
- response = get('InvoiceService.deleteSubscription', cprogram_id)
+ response = xmlrpc('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
api_logger.warn "[DEPRECATION WARNING]: The invoice_add_subscription method more fully complies with Infusionsoft's published API documents. User is advised to review Infusionsoft's API and this gem's documentation for changes in parameters."
- response = get('InvoiceService.addRecurringOrder', contact_id,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
################### This is a replacement method for invoice_add_recurring_order
# in order to fully support and comply with the Infusionsoft API documentation.
#
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_subscription(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
- response = get('InvoiceService.addRecurringOrder', contact_id,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
- response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
+ response = xmlrpc('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
- response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
+ response = xmlrpc('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
- response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
+ response = xmlrpc('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
- response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
+ response = xmlrpc('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
- response = get('InvoiceService.calculateAmountOwed', invoice_id)
+ response = xmlrpc('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
- response = get('InvoiceService.getAllPaymentOptions')
+ response = xmlrpc('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
- response = get('Invoice.getPayments', invoice_id)
+ response = xmlrpc('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
- response = get('InvoiceService.locateExistingCard', contact_id, last_four)
+ response = xmlrpc('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
- response = get('InvoiceService.recalculateTax', invoice_id)
+ response = xmlrpc('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
- response = get('InvoiceService.validateCreditCard', credit_card_id)
+ response = xmlrpc('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
- response = get('InvoiceService.validateCreditCard', data)
+ response = xmlrpc('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
- response = get('Invoice.getAllShippingOptions')
+ response = xmlrpc('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
- response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
+ response = xmlrpc('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
- response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
+ response = xmlrpc('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# adding a manual payment for an invoice.
# This can be useful when the payments are not handled by Infusionsoft
# but you still needs to makethe invoice as paid
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date (time)
# @param [String] payment_type
# - E.g 'Credit Card'
# @param [String] description
# @param [Boolean] bypass_commissions (Whether this payment
# should count towards affiliate commissions.)
def add_manual_payment(invoice_id, amount, date, payment_type, description, bypass_commission)
- response = get('InvoiceService.addManualPayment', invoice_id, amount,
+ response = xmlrpc('InvoiceService.addManualPayment', invoice_id, amount,
date, payment_type, description, bypass_commission)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
- response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
+ response = xmlrpc('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
- response = get('InvoiceService.getInvoiceId', order_id)
+ response = xmlrpc('InvoiceService.getInvoiceId', order_id)
end
end
end
end
diff --git a/lib/infusionsoft/client/search.rb b/lib/infusionsoft/client/search.rb
index 7136de0..33be726 100644
--- a/lib/infusionsoft/client/search.rb
+++ b/lib/infusionsoft/client/search.rb
@@ -1,66 +1,66 @@
module Infusionsoft
class Client
- # The SearchService allows you to retrieve the results of saved searches and reports that
- # have been saved within Infusionsoft. Saved searches/reports are tied to the User that
- # created them. This service also allows you to utilize the quick search function found in
+ # The SearchService allows you to retrieve the results of saved searches and reports that
+ # have been saved within Infusionsoft. Saved searches/reports are tied to the User that
+ # created them. This service also allows you to utilize the quick search function found in
# the upper right hand corner of your Infusionsoft application.
- # @note In order to retrieve the id number for saved searches you will need to utilize
- # the data_query method and query the table called SavedFilter based on the user_id
- # you are looking for the saved search Id for. Also note that UserId field on the
- # SavedFilter table can contain multiple userIdâs separated by a comma, so if you are
- # querying for a report created by userId 6, I recommend appending the wildcard to the
+ # @note In order to retrieve the id number for saved searches you will need to utilize
+ # the data_query method and query the table called SavedFilter based on the user_id
+ # you are looking for the saved search Id for. Also note that UserId field on the
+ # SavedFilter table can contain multiple userIdâs separated by a comma, so if you are
+ # querying for a report created by userId 6, I recommend appending the wildcard to the
# end of the userId. Something like $query = array( âUserIdâ => â6%â );
module Search
# Gets all possible fields/columns available for return on a saved search/report.
#
# @param [Integer] saved_search_id
# @param [Integer] user_id the user id who the saved search is assigned to
# @return [Hash]
def search_get_all_report_columns(saved_search_id, user_id)
- response = get('SearchService.getAllReportColumns', saved_search_id, user_id)
+ response = xmlrpc('SearchService.getAllReportColumns', saved_search_id, user_id)
end
# Runs a saved search/report and returns all possible fields.
#
# @param [Integer] saved_search_id
# @param [Integer] user_id the user id who the saved search is assigned to
# @param [Integer] page_number
# @return [Hash]
def search_get_saved_search_results(saved_search_id, user_id, page_number)
- response = get('SearchService.getSavedSearchResultsAllFields', saved_search_id,
+ response = xmlrpc('SearchService.getSavedSearchResultsAllFields', saved_search_id,
user_id, page_number)
end
# This is used to find what possible quick searches the given user has access to.
#
# @param [Integer] user_id
- # @return [Array]
+ # @return [Array]
def search_get_available_quick_searches(user_id)
- response = get('SearchService.getAvailableQuickSearches', user_id)
+ response = xmlrpc('SearchService.getAvailableQuickSearches', user_id)
end
- # This allows you to run a quick search via the API. The quick search is the
+ # This allows you to run a quick search via the API. The quick search is the
# search bar in the upper right hand corner of the Infusionsoft application
#
# @param [String] search_type the type of search (Person, Order, Opportunity, Company, Task,
# Subscription, or Affiliate)
# @param [Integer] user_id
# @param [String] search_data
# @param [Integer] page
# @param [Integer] limit max is 1000
# @return [Array<Hash>]
def search_quick_search(search_type, user_id, search_data, page, limit)
- response = get('SearchService.quickSearch', search_type, user_id, search_data, page, limit)
+ response = xmlrpc('SearchService.quickSearch', search_type, user_id, search_data, page, limit)
end
# Retrieves the quick search type that the given users has set as their default.
#
# @param [Integer] user_id
# @return [String] the quick search type that the given user selected as their default
def search_get_default_search_type(user_id)
- response = get('SearchService.getDefaultQuickSearch', user_id)
+ response = xmlrpc('SearchService.getDefaultQuickSearch', user_id)
end
end
end
end
diff --git a/lib/infusionsoft/client/ticket.rb b/lib/infusionsoft/client/ticket.rb
index 89f3bf0..841ea45 100644
--- a/lib/infusionsoft/client/ticket.rb
+++ b/lib/infusionsoft/client/ticket.rb
@@ -1,18 +1,18 @@
module Infusionsoft
class Client
module Ticket
# add move notes to existing tickets
- def ticket_add_move_notes(ticket_list, move_notes,
+ def ticket_add_move_notes(ticket_list, move_notes,
move_to_stage_id, notify_ids)
- response = get('ServiceCallService.addMoveNotes', ticket_list,
+ response = xmlrpc('ServiceCallService.addMoveNotes', ticket_list,
move_notes, move_to_stage_id, notify_ids)
end
# add move notes to existing tickets
def ticket_move_stage(ticket_id, ticket_stage, move_notes, notify_ids)
- response = get('ServiceCallService.moveTicketStage',
+ response = xmlrpc('ServiceCallService.moveTicketStage',
ticket_id, ticket_stage, move_notes, notify_ids)
end
end
end
end
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index d3b95ae..12e6ac6 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,34 +1,52 @@
+require 'rest-client'
+
module Infusionsoft
# Incase Infusionsoft ever creates a restful API :)
module Request
+ def xmlrpc(servic_call, *args)
+ connection(service_call, *args)
+ end
+
# Perform an GET request
- def get(service_call, *args)
- request(:get, service_call, *args)
+ def get(path, token, query: {})
+ request(:get, path, token, query: query )
end
- def post(path, params={}, options={})
- request(:post, path, params, options)
+ def post(path, token, query: {}, payload: {})
+ request(:post, path, token, query, payload)
end
# Perform an HTTP PUT request
- def put(path, params={}, options={})
- request(:put, path, params, options)
+ def put(path, token, query: {}, payload: {})
+ request(:put, path, token, query, payload)
end
# Perform an HTTP DELETE request
- def delete(path, params={}, options={})
- request(:delete, path, params, options)
+ def delete(path, token, query: {})
+ request(:delete, path, token, query)
end
-
private
# Perform request
- def request(method, service_call, *args)
- case method.to_sym
- when :get
- response = connection(service_call, *args)
- end
+ def request(method, path, token, query={}, payload={})
+ path = "/#{path}" unless path.start_with?('/')
+ header = {
+ authorization: "Bearer #{token.access_token}",
+ content_type: :json,
+ accept: :json,
+ params: query
+ }
+ opts = {
+ method: method,
+ url: "https://api.infusionsoft.com/crm/rest/v1" + path,
+ headers: header
+ }
+ opts.merge!( { payload: payload.to_json }) unless payload.empty?
+ resp = RestClient::Request.execute(opts)
+ rescue RestClient::ExceptionWithResponse => err
+ # log error?
+ else
+ return JSON.parse(resp.body)
end
- end
end
diff --git a/lib/infusionsoft/rest/token.rb b/lib/infusionsoft/rest/token.rb
new file mode 100644
index 0000000..b2ee56b
--- /dev/null
+++ b/lib/infusionsoft/rest/token.rb
@@ -0,0 +1,71 @@
+require 'rest-client'
+require 'uri'
+
+class Rest::Token
+
+ attr_accessor :access_token, :refresh_token, :expiration
+
+ def initialize(token_params)
+ access_token = token_params[:access_token]
+ refresh_token = token_params[:refresh_token]
+ expiration = token_params[:expiration] if token_params[:expiration]
+
+ if token_params[:expires_in]
+ expiration = Time.now + token_params[:expires_in]
+ end
+ end
+
+ def valid?
+ Time.now < expiration
+ end
+
+ class << self
+ def auth_url(client_id, redirect_uri)
+ params = {
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ scope: 'full',
+ response_type: 'code'
+ }
+
+ uri = URI::HTTPS.build({host: "signin.infusionsoft.com", path: "/app/oauth/authorize", query: URI.encode_www_form(params)})
+ uri.to_s
+ end
+
+ def refresh(client_id, client_secret, refresh_token)
+ params = {
+ grant_type: 'refresh_token',
+ refresh_token: refresh_token,
+ }
+
+ header = { "Authorization": "Basic " + Base64.urlsafe_encode64("#{client_id}:#{client_secret}")}
+
+ response = RestClient.post("https://api.infusionsoft.com/token", params, header)
+
+ rescue RestClient::ExceptionWithRespone => e
+ #TODO what to do here?
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ def get_token(client_id, client_secret, redirect_uri, code)
+ params = {
+ client_id: client_id,
+ client_secret: client_secret,
+ redirect_uri: redirect_uri,
+ code: code,
+ grant_type: 'authorization_code',
+ }
+
+ response = RestClient.post("https://api.infusionsoft.com/token", params)
+ rescue RestClient::ExceptionWithResponse => e
+ # TODO: what to do here
+ else
+ token_params = JSON.parse(response.body).symbolize_keys
+ self.new(token_params)
+ end
+
+ end
+
+end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
91e2117bd59940d7d6f9ae8e0275df2aae1aab2b
|
Updating readme
|
diff --git a/README.md b/README.md
index 4aedc98..99c5f62 100644
--- a/README.md
+++ b/README.md
@@ -1,129 +1,128 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
-Update - Adding support for Rest in an upcoming release
-
**update notes**
+* upcoming - Adding support for rest api
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2017 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
825b8a1f240d9119d3849b0c714e1de72bbeb321
|
Updating readme
|
diff --git a/README.md b/README.md
index a32d778..4aedc98 100644
--- a/README.md
+++ b/README.md
@@ -1,127 +1,129 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
+Update - Adding support for Rest in an upcoming release
+
**update notes**
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2017 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
098aa949752815cdc7b07fe5201934df6d6e08e7
|
updating how to obtain the api key
|
diff --git a/README.md b/README.md
index 743caec..a32d778 100644
--- a/README.md
+++ b/README.md
@@ -1,127 +1,127 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
-2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](http://ug.infusionsoft.com/article/AA-00442/0/How-do-I-enable-the-Infusionsoft-API-and-generate-an-API-Key.html)
+2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](https://classic-infusionsoft.knowledgeowl.com/help/api-key)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2017 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
e890c687579ff6f8faeddac71cc1c18300df70bd
|
Updating version to 1.2.2 and updating readme
|
diff --git a/README.md b/README.md
index 40e8387..743caec 100644
--- a/README.md
+++ b/README.md
@@ -1,126 +1,127 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
+* v1.2.2 - Catching Infusionsoft API SSL handshake issues
* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](http://ug.infusionsoft.com/article/AA-00442/0/How-do-I-enable-the-Infusionsoft-API-and-generate-an-API-Key.html)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
```ruby
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## OAUTH 2.0
You will need to handle and obtain the access_token on your own.
```ruby
# You will need to attain the access_token first, then do the config like so:
Infusionsoft.configure do |config|
config.use_oauth = true
config.api_url = 'api.infusionsoft.com' # do not include https://
config.api_key = 'ACCESS_TOKEN' # access_token
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
```
## <a name="examples">Usage Examples</a>
```ruby
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2017 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index ed9d5df..09b6b46 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.2.1-a3'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.2.2'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
14308a224ddaff2ad5327169dbee6fd9e0980366
|
adding connection retries on SSL::SSLError for handshake issues w Infusionsoft
|
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index 567ba5f..a73552e 100755
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,45 +1,48 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
path = use_oauth ? "/crm/xmlrpc/v1?access_token=#{api_key}" : "/api/xmlrpc"
client = XMLRPC::Client.new3({
'host' => api_url,
'path' => path,
'port' => 443,
'use_ssl' => true
})
client.http_header_extra = {'User-Agent' => user_agent}
begin
api_logger.info "CALL: #{service_call} api_url: #{api_url} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
+ rescue OpenSSL::SSL::SSLError => ssl_error
+ # Retry up to 5 times on a SSL Handshake issue w Infusionsoft
+ ok_to_retry(ssl_error) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
05117fb611d406eecce57b1adfd38e97205499a0
|
removing api_key from logs
|
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
old mode 100644
new mode 100755
index 7cd8781..567ba5f
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,45 +1,45 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
path = use_oauth ? "/crm/xmlrpc/v1?access_token=#{api_key}" : "/api/xmlrpc"
client = XMLRPC::Client.new3({
'host' => api_url,
'path' => path,
'port' => 443,
'use_ssl' => true
})
client.http_header_extra = {'User-Agent' => user_agent}
begin
- api_logger.info "CALL: #{service_call} api_url: #{api_url} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
+ api_logger.info "CALL: #{service_call} api_url: #{api_url} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
1c1901834e0f419ddd4b898c723a190b1e5603e3
|
getInvoiceId spelling correction - fix
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 374afc9..5e60aca 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,304 +1,304 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
api_logger.warn "[DEPRECATION WARNING]: The invoice_add_subscription method more fully complies with Infusionsoft's published API documents. User is advised to review Infusionsoft's API and this gem's documentation for changes in parameters."
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
################### This is a replacement method for invoice_add_recurring_order
# in order to fully support and comply with the Infusionsoft API documentation.
#
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_subscription(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# adding a manual payment for an invoice.
# This can be useful when the payments are not handled by Infusionsoft
# but you still needs to makethe invoice as paid
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date (time)
# @param [String] payment_type
# - E.g 'Credit Card'
# @param [String] description
# @param [Boolean] bypass_commissions (Whether this payment
# should count towards affiliate commissions.)
def add_manual_payment(invoice_id, amount, date, payment_type, description, bypass_commission)
response = get('InvoiceService.addManualPayment', invoice_id, amount,
date, payment_type, description, bypass_commission)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
- response = get('InvoiceService.getinvoice_id', order_id)
+ response = get('InvoiceService.getInvoiceId', order_id)
end
end
end
end
|
nateleavitt/infusionsoft
|
3cb4f421e187ada702619bf77a524eb524ab5d40
|
Fixes nateleavitt/infusionsoft#63
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 9d4b13e..374afc9 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,286 +1,304 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
api_logger.warn "[DEPRECATION WARNING]: The invoice_add_subscription method more fully complies with Infusionsoft's published API documents. User is advised to review Infusionsoft's API and this gem's documentation for changes in parameters."
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
################### This is a replacement method for invoice_add_recurring_order
# in order to fully support and comply with the Infusionsoft API documentation.
#
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_subscription(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
+ # adding a manual payment for an invoice.
+ # This can be useful when the payments are not handled by Infusionsoft
+ # but you still needs to makethe invoice as paid
+ #
+ # @param [Integer] invoice_id
+ # @param [Float] amount
+ # @param [Date] date (time)
+ # @param [String] payment_type
+ # - E.g 'Credit Card'
+ # @param [String] description
+ # @param [Boolean] bypass_commissions (Whether this payment
+ # should count towards affiliate commissions.)
+
+ def add_manual_payment(invoice_id, amount, date, payment_type, description, bypass_commission)
+ response = get('InvoiceService.addManualPayment', invoice_id, amount,
+ date, payment_type, description, bypass_commission)
+ end
+
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
response = get('InvoiceService.getinvoice_id', order_id)
end
end
end
end
diff --git a/test/client/invoice_test.rb b/test/client/invoice_test.rb
index 423ed0e..f6fba44 100644
--- a/test/client/invoice_test.rb
+++ b/test/client/invoice_test.rb
@@ -1,21 +1,32 @@
require_relative('../test_helper')
class InvoiceTest < Test::Unit::TestCase
def test_invoice_add_recurring_order
VCR.use_cassette('invoice_add_recurring_order') do
result = Infusionsoft.invoice_add_recurring_order(4095, true, 19, 4, 9957, 0, 0)
assert_instance_of Fixnum, result
end
end
def test_invoice_add_subscription
VCR.use_cassette('invoice_add_subscription') do
result = Infusionsoft.invoice_add_subscription(4095, true, 19, 1, 27.0, false, 4, 9957, 0, 0)
assert_instance_of Fixnum, result
end
end
+ def test_add_manual_payment
+ VCR.use_cassette('invoice_add_manual_payment') do
+ result = Infusionsoft.invoice_add_manual_payment(60, 199.00, Time.now, 'Credit Card', 'Paid in full', false)
+
+ assert_instance_of TrueClass, result
+ end
+ end
+
+
+
+
end
diff --git a/test/vcr_cassettes/invoice_add_manual_payment.yml b/test/vcr_cassettes/invoice_add_manual_payment.yml
new file mode 100644
index 0000000..4d5cd72
--- /dev/null
+++ b/test/vcr_cassettes/invoice_add_manual_payment.yml
@@ -0,0 +1,60 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: '<?xml version="1.0" ?><methodCall><methodName>InvoiceService.addManualPayment</methodName><params><param><value><string>13bd0f9f842441fb2c2bef3e9ca18db6</string></value></param><param><value><i4>60</i4></value></param><param><value><double>199.0</double></value></param><param><value><dateTime.iso8601>20171208T11:56:04</dateTime.iso8601></value></param><param><value><string>Credit
+ Card</string></value></param><param><value><string>Paid in full</string></value></param><param><value><boolean>0</boolean></value></param></params></methodCall>
+
+'
+ headers:
+ User-Agent:
+ - Infusionsoft-1.2.0-a1 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '544'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Cache-Control:
+ - no-cache, no-store
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Date:
+ - Fri, 08 Dec 2017 00:56:04 GMT
+ Expires:
+ - Fri, 08 Dec 2017 00:56:04 GMT
+ Pragma:
+ - no-cache
+ Server:
+ - Apache-Coyote
+ Set-Cookie:
+ - app-lb=!1NeLgEHXoumXOZ8vitCrYAxHQKcFLkyPXQbfrmps12iyapGnRjSDeX5+2MdcUx5kfspdV8ro+yAUMGMLC3IEKvrhF0QxV5BcT0mgXbNhhtUux37hZ8c2Y5cFymncwqosTT0bkq8fi2k7eHm/zSy/JfE0oeJI4BY=;
+ path=/; Httponly; Secure
+ Strict-Transport-Security:
+ - max-age=31536000; includeSubDomains
+ Vary:
+ - Accept-Encoding
+ X-Frame-Options:
+ - SAMEORIGIN
+ X-Robots-Tag:
+ - noindex, nofollow
+ Transfer-Encoding:
+ - chunked
+ body:
+ encoding: ASCII-8BIT
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 08 Dec 2017 00:56:05 GMT
+recorded_with: VCR 4.0.0
|
nateleavitt/infusionsoft
|
71da449909f97f0bc15a2d5f10b537f2a8953c47
|
adding oauth support
|
diff --git a/README.md b/README.md
index e610e87..40e8387 100644
--- a/README.md
+++ b/README.md
@@ -1,110 +1,126 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
+* v1.2.1 - Added OAuth support
* v1.2.0 - Added `invoice_add_subscription` call to mirror Infusionsoft API parameters to eventually replace `invoice_add_recurring_order`
* maybe?? - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](http://ug.infusionsoft.com/article/AA-00442/0/How-do-I-enable-the-Infusionsoft-API-and-generate-an-API-Key.html)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
-<b></b>
-
- # Added to your config\initializers file
- Infusionsoft.configure do |config|
- config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
- config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
- config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
- end
+```ruby
+# Added to your config\initializers file
+Infusionsoft.configure do |config|
+ config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
+ config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
+ config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
+end
+```
+## OAUTH 2.0
+
+You will need to handle and obtain the access_token on your own.
+
+```ruby
+# You will need to attain the access_token first, then do the config like so:
+Infusionsoft.configure do |config|
+ config.use_oauth = true
+ config.api_url = 'api.infusionsoft.com' # do not include https://
+ config.api_key = 'ACCESS_TOKEN' # access_token
+ config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
+end
+```
## <a name="examples">Usage Examples</a>
- # Get a users first and last name using the DataService
- Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
+```ruby
+# Get a users first and last name using the DataService
+Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
- # Get a list of custom fields
- Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
- # Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
+# Get a list of custom fields
+Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
+# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
- # Update a contact with specific field values
- Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
+# Update a contact with specific field values
+Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
- # Add a new Contact
- Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
+# Add a new Contact
+Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
- # Create a blank Invoice
- invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
+# Create a blank Invoice
+invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
- # Then add item to invoice
- Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
+# Then add item to invoice
+Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
- # Then charge the invoice
- Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
+# Then charge the invoice
+Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
+```
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2017 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
diff --git a/lib/infusionsoft/configuration.rb b/lib/infusionsoft/configuration.rb
index e1cdb43..790e242 100644
--- a/lib/infusionsoft/configuration.rb
+++ b/lib/infusionsoft/configuration.rb
@@ -1,48 +1,53 @@
require 'infusionsoft/version'
module Infusionsoft
module Configuration
# The list of available options
VALID_OPTION_KEYS = [
:api_url,
:api_key,
:api_logger,
+ :use_oauth,
:user_agent # allows you to change the User-Agent of the request headers
].freeze
# @private
attr_accessor *VALID_OPTION_KEYS
# When this module is extended, set all configuration options to their default values
#def self.extended(base)
#base.reset
#end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
options = {}
VALID_OPTION_KEYS.each{|k| options[k] = send(k)}
options
end
#def reset
#self.url = ''
#self.api_key = 'na'
#end
+ def use_oauth
+ @use_oauth || false
+ end
+
def user_agent
@user_agent ||= "Infusionsoft-#{VERSION} (RubyGem)"
end
def api_logger
@api_logger || Infusionsoft::APILogger.new
end
end
end
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index 234a904..7cd8781 100644
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,43 +1,45 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
+ path = use_oauth ? "/crm/xmlrpc/v1?access_token=#{api_key}" : "/api/xmlrpc"
+
client = XMLRPC::Client.new3({
'host' => api_url,
- 'path' => "/api/xmlrpc",
+ 'path' => path,
'port' => 443,
'use_ssl' => true
})
client.http_header_extra = {'User-Agent' => user_agent}
begin
api_logger.info "CALL: #{service_call} api_url: #{api_url} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 912327c..ed9d5df 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.2.0'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.2.1-a3'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
950443d931b9c8f5edec656520827e2f8f51d6ce
|
updating docs link
|
diff --git a/README.md b/README.md
index 3c69a60..a1dacae 100644
--- a/README.md
+++ b/README.md
@@ -1,109 +1,109 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* Currently - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
-[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
+[http://rubydoc.info/gems/infusionsoft](http://rubydoc.info/gems/infusionsoft)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](http://ug.infusionsoft.com/article/AA-00442/0/How-do-I-enable-the-Infusionsoft-API-and-generate-an-API-Key.html)
3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby >= 2.0
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2015 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
46455e871c7e7def5958c64d6b8d1dcfa9dc82c1
|
building gem v 1.2.0
|
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 84b58bd..912327c 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.1.9'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.2.0'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
6406f41296af8896238a4eff6a55e76d4ce03c71
|
adding replacement method for invoice_add_recurring_order
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 17e3668..9d4b13e 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,258 +1,286 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
+ # @param [Integer] merchant_account_id
+ # @param [Integer] credit_card_id
+ # @param [Integer] affiliate_id
+ # @param [Integer] days_till_charge number of days you want to wait till it's charged
+ def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
+ merchant_account_id, credit_card_id, affiliate_id,
+ days_till_charge)
+
+ api_logger.warn "[DEPRECATION WARNING]: The invoice_add_subscription method more fully complies with Infusionsoft's published API documents. User is advised to review Infusionsoft's API and this gem's documentation for changes in parameters."
+
+ response = get('InvoiceService.addRecurringOrder', contact_id,
+ allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
+ affiliate_id, days_till_charge)
+ end
+
+
+
+ ################### This is a replacement method for invoice_add_recurring_order
+ # in order to fully support and comply with the Infusionsoft API documentation.
+ #
+ #
+ # @param [Integer] contact_id
+ # @param [Boolean] allow_duplicate
+ # @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
- def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
+
+ def invoice_add_subscription(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
+
+
+
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
response = get('InvoiceService.getinvoice_id', order_id)
end
end
end
end
diff --git a/test/client/invoice_test.rb b/test/client/invoice_test.rb
index 7c3c167..423ed0e 100644
--- a/test/client/invoice_test.rb
+++ b/test/client/invoice_test.rb
@@ -1,14 +1,21 @@
require_relative('../test_helper')
class InvoiceTest < Test::Unit::TestCase
-
def test_invoice_add_recurring_order
VCR.use_cassette('invoice_add_recurring_order') do
- result = Infusionsoft.invoice_add_recurring_order(1, true, 1, 1, 10.0, true, 1, 1, 0, 0)
+ result = Infusionsoft.invoice_add_recurring_order(4095, true, 19, 4, 9957, 0, 0)
+
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_invoice_add_subscription
+ VCR.use_cassette('invoice_add_subscription') do
+ result = Infusionsoft.invoice_add_subscription(4095, true, 19, 1, 27.0, false, 4, 9957, 0, 0)
assert_instance_of Fixnum, result
end
end
end
diff --git a/test/vcr_cassettes/invoice_add_recurring_order.yml b/test/vcr_cassettes/invoice_add_recurring_order.yml
new file mode 100644
index 0000000..355ec70
--- /dev/null
+++ b/test/vcr_cassettes/invoice_add_recurring_order.yml
@@ -0,0 +1,55 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://jj1641.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: '<?xml version="1.0" ?><methodCall><methodName>InvoiceService.addRecurringOrder</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>9999</i4></value></param><param><value><boolean>1</boolean></value></param><param><value><i4>99</i4></value></param><param><value><i4>9</i4></value></param><param><value><i4>9999</i4></value></param><param><value><i4>0</i4></value></param><param><value><i4>0</i4></value></param></params></methodCall>
+
+'
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '498'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Cache-Control:
+ - no-cache, no-store
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Date:
+ - Tue, 02 May 2017 05:19:58 GMT
+ Expires:
+ - Tue, 02 May 2017 05:19:58 GMT
+ Pragma:
+ - no-cache
+ Server:
+ - Apache-Coyote/1.1
+ Set-Cookie:
+ - app-lb=!cUikj+k8HKXBdH1+PjA2WRnGtDEWJbE7XZ9YL6pt5yl0LGmznUJFvHlFJzYyIt6AFSc/BsMiohUVlS1XrBv5bqVlULoWq6qFxOlhbGK6CzXZtrUrJz8dZERhP/ef7JfEdsO6E+ARnUn2v/9Hd3nRaWwaBWTl7k4=;
+ path=/; Httponly; Secure
+ Vary:
+ - Accept-Encoding
+ X-Frame-Options:
+ - SAMEORIGIN
+ Transfer-Encoding:
+ - chunked
+ body:
+ encoding: ASCII-8BIT
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>9999</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Tue, 02 May 2017 05:19:59 GMT
+recorded_with: VCR 3.0.3
diff --git a/test/vcr_cassettes/invoice_add_subscription.yml b/test/vcr_cassettes/invoice_add_subscription.yml
new file mode 100644
index 0000000..a858919
--- /dev/null
+++ b/test/vcr_cassettes/invoice_add_subscription.yml
@@ -0,0 +1,55 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://jj1641.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: '<?xml version="1.0" ?><methodCall><methodName>InvoiceService.addRecurringOrder</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>9999</i4></value></param><param><value><boolean>1</boolean></value></param><param><value><i4>99</i4></value></param><param><value><i4>1</i4></value></param><param><value><double>27.0</double></value></param><param><value><boolean>0</boolean></value></param><param><value><i4>9</i4></value></param><param><value><i4>9999</i4></value></param><param><value><i4>0</i4></value></param><param><value><i4>0</i4></value></param></params></methodCall>
+
+'
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '639'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Cache-Control:
+ - no-cache, no-store
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Date:
+ - Tue, 02 May 2017 05:10:07 GMT
+ Expires:
+ - Tue, 02 May 2017 05:10:07 GMT
+ Pragma:
+ - no-cache
+ Server:
+ - Apache-Coyote/1.1
+ Set-Cookie:
+ - app-lb=!ETsv4rM6FKdOg2R+PjA2WRnGtDEWJYEgTX9VcfOrT9pRJfJ9gtNVbF/QowPzaPUCvzImMyGJpOQVb1+LfGogVlbLZUmJZLHpU57EP9prAVn06cOhYo+eDAudMRGqKuJXDzX8VLc4bBMlQDcLpoV4aibJNtuIR4I=;
+ path=/; Httponly; Secure
+ Vary:
+ - Accept-Encoding
+ X-Frame-Options:
+ - SAMEORIGIN
+ Transfer-Encoding:
+ - chunked
+ body:
+ encoding: ASCII-8BIT
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>9999</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Tue, 02 May 2017 05:10:07 GMT
+recorded_with: VCR 3.0.3
|
nateleavitt/infusionsoft
|
46c00655c9c9069b4ebd1ff9bb465f46f03c6ff7
|
adding test for invoice
|
diff --git a/test/client/invoice_test.rb b/test/client/invoice_test.rb
new file mode 100644
index 0000000..7c3c167
--- /dev/null
+++ b/test/client/invoice_test.rb
@@ -0,0 +1,14 @@
+require_relative('../test_helper')
+
+class InvoiceTest < Test::Unit::TestCase
+
+
+ def test_invoice_add_recurring_order
+ VCR.use_cassette('invoice_add_recurring_order') do
+ result = Infusionsoft.invoice_add_recurring_order(1, true, 1, 1, 10.0, true, 1, 1, 0, 0)
+
+ assert_instance_of Fixnum, result
+ end
+ end
+
+end
|
nateleavitt/infusionsoft
|
2fc2936a5be623aa32713b15ea934a5381a6172c
|
fixed typo
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index f79cf79..17e3668 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,258 +1,258 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] qty
# @param [Float] price
# @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
- allow_duplicate, cprogram_id, qty, price, alllow_tax, merchant_account_id, credit_card_id,
+ allow_duplicate, cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
response = get('InvoiceService.getinvoice_id', order_id)
end
end
end
end
|
nateleavitt/infusionsoft
|
9c3f8e3c83afe905336cc8a771e531ce6ad639f5
|
FIX: added parameters qty, price, and allow_tax
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index fbfaa86..f79cf79 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,254 +1,258 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
# @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
+ # @param [Integer] qty
+ # @param [Float] price
+ # @param [Boolean] allow_tax
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
+ qty, price, allow_tax,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
- allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
+ allow_duplicate, cprogram_id, qty, price, alllow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
response = get('InvoiceService.getinvoice_id', order_id)
end
end
end
end
|
nateleavitt/infusionsoft
|
eb0ec12f7e0529ef1177763f1813cbee4e6f46e0
|
Add 'Infusionsoft API Setup' doc link to README
|
diff --git a/README.md b/README.md
index da9bbd6..a694dd2 100644
--- a/README.md
+++ b/README.md
@@ -1,109 +1,110 @@
[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* Currently - Going to add Infusionsoft API authentication Oauth flow. Also, I'm thinking of rewriting parts of it to make the calls more user friendly and adding some convenience methods. If you have any suggestions, let me know.
* 07/21/2015 - Implementation of tests and build/coverage (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
-2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
+2. Enable the API on your Infusionsoft account (if you haven't already) and generate your API Key: [See Infusionsoft Doc](http://ug.infusionsoft.com/article/AA-00442/0/How-do-I-enable-the-Infusionsoft-API-and-generate-an-API-Key.html)
+3. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7 (It will work, but tests require Ruby >= 1.9)
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2015 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
5cae2ebdcf728e375b28c55e60cb4bea459218c8
|
adding some additional loggging
|
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index 5590e92..234a904 100644
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,43 +1,43 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
client = XMLRPC::Client.new3({
'host' => api_url,
'path' => "/api/xmlrpc",
'port' => 443,
'use_ssl' => true
})
client.http_header_extra = {'User-Agent' => user_agent}
begin
- api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
+ api_logger.info "CALL: #{service_call} api_url: #{api_url} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
d0061aa3bed33193b0219e1fcc123c1eff1826e6
|
fix email optin bug
|
diff --git a/lib/infusionsoft/client/contact.rb b/lib/infusionsoft/client/contact.rb
index f273a3e..34db7b2 100644
--- a/lib/infusionsoft/client/contact.rb
+++ b/lib/infusionsoft/client/contact.rb
@@ -1,197 +1,197 @@
module Infusionsoft
class Client
# Contact service is used to manage contacts. You can add, update and find contacts in
# addition to managing follow up sequences, tags and action sets.
module Contact
# Creates a new contact record from the data passed in the associative array.
#
# @param [Hash] data contains the mappable contact fields and it's data
# @return [Integer] the id of the newly added contact
# @example
# { :Email => '[email protected]', :FirstName => 'first_name', :LastName => 'last_name' }
def contact_add(data)
contact_id = get('ContactService.add', data)
- if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end
+ if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
# Merge two contacts together.
#
# @param [Integer] contact_id
# @param [Integer] duplicate_contact_id
def contact_merge(contact_id, duplicate_contact_id)
response = get('ContactService.merge', contact_id, duplicate_contact_id)
end
# Adds or updates a contact record based on matching data
#
# @param [Array<Hash>] data the contact data you want added
# @param [String] check_type available options are 'Email', 'EmailAndName',
# 'EmailAndNameAndCompany'
# @return [Integer] id of the contact added or updated
def contact_add_with_dup_check(data, check_type)
contact_id = get('ContactService.addWithDupCheck', data, check_type)
- if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end
+ if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
# Updates a contact in the database.
#
# @param [Integer] contact_id
# @param [Hash] data contains the mappable contact fields and it's data
# @return [Integer] the id of the contact updated
# @example
# { :FirstName => 'first_name', :StreetAddress1 => '123 N Street' }
def contact_update(contact_id, data)
contact_id = get('ContactService.update', contact_id, data)
- if data.has_key?("Email"); email_optin(data["Email"], "requested information"); end
+ if data.has_key?(:Email); email_optin(data[:Email], "requested information"); end
return contact_id
end
# Loads a contact from the database
#
# @param [Integer] id
# @param [Array] selected_fields the list of fields you want back
# @return [Array] the fields returned back with it's data
# @example this is what you would get back
# { "FirstName" => "John", "LastName" => "Doe" }
def contact_load(id, selected_fields)
response = get('ContactService.load', id, selected_fields)
end
# Finds all contacts with the supplied email address in any of the three contact record email
# addresses.
#
# @param [String] email
# @param [Array] selected_fields the list of fields you want with it's data
# @return [Array<Hash>] the list of contacts with it's fields and data
def contact_find_by_email(email, selected_fields)
response = get('ContactService.findByEmail', email, selected_fields)
end
# Adds a contact to a follow-up sequence (campaigns were the original name of follow-up sequences).
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the contact was added to the follow-up sequence
# successfully
def contact_add_to_campaign(contact_id, campaign_id)
response = get('ContactService.addToCampaign', contact_id, campaign_id)
end
# Returns the Id number of the next follow-up sequence step for the given contact.
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Integer] id number of the next unfishished step in the given follow up sequence
# for the given contact
def contact_get_next_campaign_step(contact_id, campaign_id)
response = get('ContactService.getNextCampaignStep', contact_id, campaign_id)
end
# Pauses a follow-up sequence for the given contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if the sequence was paused
def contact_pause_campaign(contact_id, campaign_id)
response = get('ContactService.pauseCampaign', contact_id, campaign_id)
end
# Removes a follow-up sequence from a contact record
#
# @param [Integer] contact_id
# @param [Integer] campaign_id
# @return [Boolean] returns true/false if removed
def contact_remove_from_campaign(contact_id, campaign_id)
response = get('ContactService.removeFromCampaign', contact_id, campaign_id)
end
# Resumes a follow-up sequence that has been stopped/paused for a given contact.
#
# @param [Integer] contact_id
# @param [Ingeger] campaign_id
# @return [Boolean] returns true/false if sequence was resumed
def contact_resume_campaign(contact_id, campaign_id)
response = get('ConactService.resumeCampaignForContact', contact_id, campaign_id)
end
# Immediately performs the given follow-up sequence step_id for the given contacts.
#
# @param [Array<Integer>] list_of_contacts
# @param [Integer] ) step_id
# @return [Boolean] returns true/false if the step was rescheduled
def contact_reschedule_campaign_step(list_of_contacts, step_id)
response = get('ContactService.reschedulteCampaignStep', list_of_contacts, step_id)
end
# Removes a tag from a contact (groups were the original name of tags).
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if tag was removed successfully
def contact_remove_from_group(contact_id, group_id)
response = get('ContactService.removeFromGroup', contact_id, group_id)
end
# Adds a tag to a contact
#
# @param [Integer] contact_id
# @param [Integer] group_id
# @return [Boolean] returns true/false if the tag was added successfully
def contact_add_to_group(contact_id, group_id)
response = get('ContactService.addToGroup', contact_id, group_id)
end
# Runs an action set on a given contact record
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @return [Array<Hash>] A list of details on each action run
# @example here is a list of what you get back
# [{ 'Action' => 'Create Task', 'Message' => 'task1 (Task) sent successfully', 'isError' =>
# nil }]
def contact_run_action_set(contact_id, action_set_id)
response = get('ContactService.runActionSequence', contact_id, action_set_id)
end
def contact_link_contact(remoteApp, remoteId, localId)
response = get('ContactService.linkContact', remoteApp, remoteId, localId)
end
def contact_locate_contact_link(locate_map_id)
response = get('ContactService.locateContactLink', locate_map_id)
end
def contact_mark_link_updated(locate_map_id)
response = get('ContactService.markLinkUpdated', locate_map_id)
end
# Creates a new recurring order for a contact.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
def contact_add_recurring_order(contact_id, allow_duplicate, cprogram_id, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('ContactService.addRecurringOrder', contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id, days_till_charge)
end
# Executes an action sequence for a given contact, passing in runtime params
# for running affiliate signup actions, etc
#
# @param [Integer] contact_id
# @param [Integer] action_set_id
# @param [Hash] data
def contact_run_action_set_with_params(contact_id, action_set_id, data)
response = get('ContactService.runActionSequence', contact_id, action_set_id, data)
end
end
end
end
diff --git a/test/vcr_cassettes/contact_add.yml b/test/vcr_cassettes/contact_add.yml
index 3782c4e..63e1d71 100644
--- a/test/vcr_cassettes/contact_add.yml
+++ b/test/vcr_cassettes/contact_add.yml
@@ -1,49 +1,93 @@
---
http_interactions:
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>ContactService.add</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Severus</string></value></member><member><name>LastName</name><value><string>Snape</string></value></member></struct></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '469'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Thu, 09 Apr 2015 19:14:00 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '131'
Date:
- Thu, 09 Apr 2015 07:14:00 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3602</i4></value></param></params></methodResponse>
http_version:
recorded_at: Thu, 09 Apr 2015 07:14:00 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.optIn</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>requested information</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '321'
+ Connection:
+ - keep-alive
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 31 Jul 2015 11:55:20 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Thu, 30 Jul 2015 23:55:20 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: US-ASCII
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Thu, 30 Jul 2015 23:55:21 GMT
recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_add_dup_check_no_dup.yml b/test/vcr_cassettes/contact_add_dup_check_no_dup.yml
index c416f81..74e13df 100644
--- a/test/vcr_cassettes/contact_add_dup_check_no_dup.yml
+++ b/test/vcr_cassettes/contact_add_dup_check_no_dup.yml
@@ -1,49 +1,93 @@
---
http_interactions:
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>ContactService.addWithDupCheck</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Albus</string></value></member><member><name>LastName</name><value><string>Dumbledore</string></value></member><member><name>Company</name><value><string>Hogwarts</string></value></member></struct></value></param><param><value><string>EmailAndNameAndCompany</string></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '629'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Fri, 10 Apr 2015 20:13:43 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '131'
Date:
- Fri, 10 Apr 2015 08:13:43 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3612</i4></value></param></params></methodResponse>
http_version:
recorded_at: Fri, 10 Apr 2015 08:13:43 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.optIn</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>requested information</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '321'
+ Connection:
+ - keep-alive
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 31 Jul 2015 11:55:20 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Thu, 30 Jul 2015 23:55:20 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: US-ASCII
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Thu, 30 Jul 2015 23:55:21 GMT
recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_add_dup_check_with_dup.yml b/test/vcr_cassettes/contact_add_dup_check_with_dup.yml
index 6affee3..636d3cd 100644
--- a/test/vcr_cassettes/contact_add_dup_check_with_dup.yml
+++ b/test/vcr_cassettes/contact_add_dup_check_with_dup.yml
@@ -1,142 +1,186 @@
---
http_interactions:
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>Id</string></value><value><string>FirstName</string></value><value><string>LastName</string></value><value><string>Email</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '480'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Fri, 10 Apr 2015 19:15:07 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '379'
Date:
- Fri, 10 Apr 2015 07:15:06 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Email</name><value>[email protected]</value></member><member><name>FirstName</name><value>Severus</value></member><member><name>Id</name><value><i4>3606</i4></value></member><member><name>LastName</name><value>Snape</value></member></struct></value></param></params></methodResponse>
http_version:
recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>ContactService.addWithDupCheck</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Severus</string></value></member><member><name>LastName</name><value><string>Snape</string></value></member><member><name>Company</name><value><string>Test Company</string></value></member></struct></value></param><param><value><string>EmailAndName</string></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '621'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Fri, 10 Apr 2015 19:15:07 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '131'
Date:
- Fri, 10 Apr 2015 07:15:06 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3606</i4></value></param></params></methodResponse>
http_version:
recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.optIn</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>requested information</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '321'
+ Connection:
+ - keep-alive
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 31 Jul 2015 11:55:20 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Thu, 30 Jul 2015 23:55:20 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: US-ASCII
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Thu, 30 Jul 2015 23:55:21 GMT
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>Company</string></value></data></array></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '328'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Fri, 10 Apr 2015 19:15:07 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '199'
Date:
- Fri, 10 Apr 2015 07:15:07 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Company</name><value>Test
Company</value></member></struct></value></param></params></methodResponse>
http_version:
recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
8556e4d462ebefeb0b7bb7493f0235566b7a4705
|
So manually adjusting content length in the cassette fixes it...the real question is why...
|
diff --git a/test/vcr_cassettes/data_get_app_setting.yml b/test/vcr_cassettes/data_get_app_setting.yml
index d20c3dc..dfcdee7 100644
--- a/test/vcr_cassettes/data_get_app_setting.yml
+++ b/test/vcr_cassettes/data_get_app_setting.yml
@@ -1,50 +1,50 @@
---
http_interactions:
- request:
method: post
uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
<?xml version="1.0" ?><methodCall><methodName>DataService.getAppSetting</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Contact</string></value></param><param><value><string>optiontitles</string></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.9 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '307'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Sun, 26 Jul 2015 11:52:30 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- - '291'
+ - '143'
Date:
- Sat, 25 Jul 2015 23:52:30 GMT
Set-Cookie:
- app-lb=!A/bDQyH+Uv/89StgcOos6QUUDc5trcDedgnc0I05zDPSlaHoDsjbvNjsryPmsEC6yQnCa2V/k60YWTM=;
path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value>Sir Madam Sith Lord Darth</value></param></params></methodResponse>
http_version:
recorded_at: Sat, 25 Jul 2015 23:52:35 GMT
recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
1e02aafdaffce70ab9b9f60888e9b5038913a69d
|
Covering email endpoints with tests
|
diff --git a/test/client/contact_test.rb b/test/client/contact_test.rb
index 73f3454..79fdd6c 100644
--- a/test/client/contact_test.rb
+++ b/test/client/contact_test.rb
@@ -1,79 +1,79 @@
require_relative('../test_helper')
class ContactTest < Test::Unit::TestCase
def test_contact_add
data_hash = { Email: '[email protected]', FirstName: 'Severus', LastName: 'Snape' }
VCR.use_cassette('contact_add') do
result = Infusionsoft.contact_add(data_hash)
assert_instance_of Fixnum, result
end
end
def test_contact_merge
VCR.use_cassette('contact_merge') do
result = Infusionsoft.contact_merge(3602, 3604)
assert_true result
end
end
def test_contact_add_dup_check_with_dup
data_hash = { Email: '[email protected]', FirstName: 'Severus',
LastName: 'Snape', Company: 'Test Company' }
VCR.use_cassette('contact_add_dup_check_with_dup') do
existing_contact = Infusionsoft.contact_load(3606, [:Id, :FirstName, :LastName, :Email, :Company])
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndName')
assert_equal result, existing_contact['Id']
assert_equal Infusionsoft.contact_load(existing_contact['Id'], [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_add_dup_check_no_dup
data_hash = { Email: '[email protected]', FirstName: 'Albus',
LastName: 'Dumbledore', Company: 'Hogwarts' }
VCR.use_cassette('contact_add_dup_check_no_dup') do
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndNameAndCompany')
assert_instance_of Fixnum, result
end
end
def test_contact_load
desired_fields = [:FirstName, :LastName]
expected_fields = desired_fields.map { |f| f.to_s }.sort
VCR.use_cassette('contact_load') do
result = Infusionsoft.contact_load(3606, desired_fields)
assert_equal result.keys.sort, expected_fields
end
end
def test_contact_update
data_hash = { Company: 'Hogwarts' }
VCR.use_cassette('contact_update') do
result = Infusionsoft.contact_update(3606, data_hash)
assert_equal result, 3606
assert_equal Infusionsoft.contact_load(3606, [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_find_by_email
VCR.use_cassette('find_by_email') do
result = Infusionsoft.contact_find_by_email('[email protected]', [:Id])
assert_instance_of Array, result
assert_instance_of Hash, result.first
end
end
def test_contact_add_to_group
VCR.use_cassette('add_to_group') do
result = Infusionsoft.contact_add_to_group(3794, 382)
- assert_equal result, true
+ assert_true result
end
end
def test_contact_remove_from_group
VCR.use_cassette('remove_from_group') do
result = Infusionsoft.contact_remove_from_group(3794, 382)
- assert_equal result, true
+ assert_true result
end
end
-end
\ No newline at end of file
+end
diff --git a/test/client/email_test.rb b/test/client/email_test.rb
new file mode 100644
index 0000000..5a0f73d
--- /dev/null
+++ b/test/client/email_test.rb
@@ -0,0 +1,89 @@
+require_relative('../test_helper')
+
+class EmailTest < Test::Unit::TestCase
+
+ def test_email_add
+ VCR.use_cassette('email_add') do
+ result = Infusionsoft.email_add('Test Via API', 'test,api', '[email protected]',
+ '[email protected]', '[email protected]', '[email protected]',
+ 'Test Subject', 'Text Body', '<p> HTML body',
+ 'Multipart', 'Contact')
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_email_attach
+ VCR.use_cassette('email_attach') do
+ result = Infusionsoft.email_attach(304, 'The Dude', '[email protected]',
+ '[email protected]', '[email protected]',
+ '[email protected]', 'Multipart', 'Question',
+ "<em>Where's the money?</em>", "Where's the money?",
+ 'Test Header', DateTime.now.to_s, DateTime.now.to_s)
+ assert_true result
+ end
+ end
+
+ def test_email_get_available_merge_fields
+ VCR.use_cassette('email_get_available_merge_fields') do
+ result = Infusionsoft.email_get_available_merge_fields('Contact')
+ assert_instance_of Array, result
+ end
+ end
+
+ def test_email_get_template
+ VCR.use_cassette('email_get_template') do
+ result = Infusionsoft.email_get_template(3649)
+ assert_instance_of Hash, result
+ end
+ end
+
+ def test_email_get_opt_status
+ VCR.use_cassette('email_get_opt_status') do
+ result = Infusionsoft.email_get_opt_status('[email protected]')
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_email_optin
+ VCR.use_cassette('email_optin') do
+ result = Infusionsoft.email_optin('[email protected]', 'because i said so')
+ assert_true [true, false].include? result
+ end
+ end
+
+ def test_email_optout
+ VCR.use_cassette('email_optout') do
+ result = Infusionsoft.email_optout('[email protected]', 'because i said so')
+ assert_true [true, false].include? result
+ end
+ end
+
+ def test_email_send
+ VCR.use_cassette('email_send') do
+ result = Infusionsoft.email_send([304], '[email protected]',
+ '[email protected]', '[email protected]',
+ '[email protected]', 'Multipart', 'Question',
+ "<em>Where's the money?</em>", "Where's the money?")
+ assert_true [true, false].include? result
+ end
+ end
+
+ def test_email_send_template
+ VCR.use_cassette('email_send_template') do
+ result = Infusionsoft.email_send_template([304], '3649')
+ assert_true [true, false].include? result
+ end
+ end
+
+ def test_email_update_template
+ VCR.use_cassette('email_update_template') do
+ result = Infusionsoft.email_update_template(3649, 'Testingness Testagram', '', '',
+ '[email protected]',
+ '[email protected]',
+ '[email protected]',
+ 'Testingness Testagrams', 'Stuff',
+ '<em>Stuff</em>', 'Multipart', 'Contact')
+ assert_true [true, false].include? result
+ end
+ end
+end
\ No newline at end of file
diff --git a/test/vcr_cassettes/email_add.yml b/test/vcr_cassettes/email_add.yml
new file mode 100644
index 0000000..5f4a3ad
--- /dev/null
+++ b/test/vcr_cassettes/email_add.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.addEmailTemplate</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Test Via API</string></value></param><param><value><string>test,api</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>Test Subject</string></value></param><param><value><string>Text Body</string></value></param><param><value><string><p> HTML body</string></value></param><param><value><string>Multipart</string></value></param><param><value><string>Contact</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '851'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 13:26:12 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Sun, 26 Jul 2015 01:26:12 GMT
+ Set-Cookie:
+ - app-lb=!5OL9Klm4DZcqS1VgcOos6QUUDc5trfa0TqBXLOnV/wMidbuidkvEoEoBb7TTtatlKJx1PPPRuT7rgCk=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3651</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 01:26:17 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_attach.yml b/test/vcr_cassettes/email_attach.yml
new file mode 100644
index 0000000..70ea04d
--- /dev/null
+++ b/test/vcr_cassettes/email_attach.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.attachEmail</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>304</i4></value></param><param><value><string>The Dude</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>Multipart</string></value></param><param><value><string>Question</string></value></param><param><value><string><em>Where's the money?</em></string></value></param><param><value><string>Where's the money?</string></value></param><param><value><string>Test Header</string></value></param><param><value><string>2015-07-25T23:02:51-07:00</string></value></param><param><value><string>2015-07-25T23:02:51-07:00</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '1039'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 18:02:46 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 06:02:46 GMT
+ Set-Cookie:
+ - app-lb=!+GwQkGtMYPo0RM1gcOos6QUUDc5trQEOJ6uXXbzsQOq4PPARvRWsStemzx8XeHl2sfU5v2CqVXMhh/4=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 06:02:51 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_get_available_merge_fields.yml b/test/vcr_cassettes/email_get_available_merge_fields.yml
new file mode 100644
index 0000000..7f096eb
--- /dev/null
+++ b/test/vcr_cassettes/email_get_available_merge_fields.yml
@@ -0,0 +1,52 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.getAvailableMergeFields</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Contact</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '262'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 13:07:41 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Vary:
+ - Accept-Encoding
+ Date:
+ - Sun, 26 Jul 2015 01:07:41 GMT
+ Connection:
+ - close
+ Set-Cookie:
+ - app-lb=!eTyx0NRCU0EQYlNgcOos6QUUDc5trbQorGipa7K5SmDW4P3aScIkbcKFmJz1ILgT+ygT3zUerhKiIcE=;
+ path=/
+ body:
+ encoding: ASCII-8BIT
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value>~LoggedInUser.LastName~</value><value>~Contact.Address2Street1~</value><value>~Contact.ZipFour2~</value><value>~Contact.StreetAddress2~</value><value>~Contact.Username~</value><value>~Contact.EmailAddress2~</value><value>~Contact.Phone2~</value><value>~Contact.PostalCode3~</value><value>~Owner.EmailAddress2~</value><value>~Owner.Fax1Type~</value><value>~Owner.Phone1Ext~</value><value>~LoggedInUser.Fax1~</value><value>~Owner.PostalCode~</value><value>~EmailSent.PartialHash~</value><value>~Company.Website~</value><value>~Contact.Address3Street2~</value><value>~LoggedInUser.Phone3Type~</value><value>~EmailSent.PublicPartialHash~</value><value>~Owner.Fax2~</value><value>~Contact._WeeklyAttendance~</value><value>~Contact.SpouseName~</value><value>~LoggedInUser.Signature~</value><value>~Contact._Aretheyinacampaign~</value><value>~Company.City~</value><value>~Owner.Phone3Ext~</value><value>~Contact.Address2Street2~</value><value>~Contact._CustomerNotes~</value><value>~Contact.Phone4Type~</value><value>~Contact.StreetAddress1~</value><value>~Contact.EmailHash~</value><value>~Contact.Phone1~</value><value>~Contact.JobTitle~</value><value>~Owner.FirstName~</value><value>~LoggedInUser.Fax2~</value><value>~Contact.ZipFour1~</value><value>~Contact.LastName~</value><value>~Contact.MiddleName~</value><value>~Contact.Address3Street1~</value><value>~LoggedInUser.Phone1Ext~</value><value>~Contact.EmailAddress3~</value><value>~LoggedInUser.Phone3Ext~</value><value>~Contact.Fax1~</value><value>~Contact.Phone4Ext~</value><value>~Owner.Fax1~</value><value>~Contact._Pricing~</value><value>~Contact._ConsultingCompany~</value><value>~LoggedInUser.Phone1Type~</value><value>~Owner.State~</value><value>~Contact.Title~</value><value>~Contact.Phone5Ext~</value><value>~LoggedInUser.StreetAddress1~</value><value>~Contact._Goals~</value><value>~Company.HTMLMailingAddressBlock~</value><value>~Contact.Phone4~</value><value>~Owner.Email~</value><value>~Owner.StreetAddress1~</value><value>~Contact.Password~</value><value>~Contact.Phone3Type~</value><value>~Contact._ResetPasswordURL~</value><value>~Contact.City2~</value><value>~Company.PostalCode~</value><value>~LoggedInUser.StreetAddress2~</value><value>~Contact.Country~</value><value>~Contact.FirstName~</value><value>~LoggedInUser.Id~</value><value>~Contact.State~</value><value>~Contact.ReferralCode~</value><value>~Contact._ChMS~</value><value>~Contact.Company~</value><value>~LoggedInUser.Website~</value><value>~Contact.Fax2Type~</value><value>~LoggedInUser.City~</value><value>~Owner.Phone3Type~</value><value>~Contact.Phone3~</value><value>~Contact.PostalCode2~</value><value>~LoggedInUser.Fax2Type~</value><value>~Owner.Phone1Type~</value><value>~Contact.City3~</value><value>~Contact._Budget~</value><value>~LoggedInUser.Phone1~</value><value>~Contact._Aretheyworkingwithaconsultant~</value><value>~Contact.AssistantName~</value><value>~Contact.City~</value><value>~Contact._Budget0~</value><value>~Contact.Website~</value><value>~LoggedInUser.Country~</value><value>~LoggedInUser.Phone2Type~</value><value>~Owner.Country~</value><value>~Contact.ContactNotes~</value><value>~LoggedInUser.Phone2Ext~</value><value>~Contact.Anniversary~</value><value>~Owner.Fax2Type~</value><value>~Company.StreetAddress1~</value><value>~Owner.Phone2~</value><value>~Contact.Email~</value><value>~LoggedInUser.Phone2~</value><value>~Contact.Phone5~</value><value>~LoggedInUser.Email~</value><value>~Owner.City~</value><value>~Owner.Website~</value><value>~Contact.Phone2Ext~</value><value>~Company.Email~</value><value>~LoggedInUser.PostalCode~</value><value>~LoggedInUser.Company~</value><value>~Contact.Phone1Type~</value><value>~Company.Phone1~</value><value>~EmailSent.Id~</value><value>~Company.TaxId~</value><value>~Owner.Phone3~</value><value>~Owner.StreetAddress2~</value><value>~Contact.Fax1Type~</value><value>~Contact.Phone2Type~</value><value>~Company.Company~</value><value>~Contact.Leadsource~</value><value>~Contact.Birthday~</value><value>~Contact.Country3~</value><value>~Contact.Phone3Ext~</value><value>~Contact.Fax2~</value><value>~Contact.Phone5Type~</value><value>~Owner.Company~</value><value>~LoggedInUser.Phone3~</value><value>~LoggedInUser.State~</value><value>~App.Name~</value><value>~Contact.Nickname~</value><value>~Contact.PostalCode~</value><value>~Contact.State2~</value><value>~Owner.Phone2Type~</value><value>~Contact.Suffix~</value><value>~LoggedInUser.FirstName~</value><value>~Contact.Phone1Ext~</value><value>~Company.State~</value><value>~Contact.AssistantPhone~</value><value>~Contact.SSN~</value><value>~Owner.LastName~</value><value>~Contact.Id~</value><value>~Company.MailingAddressBlock~</value><value>~LoggedInUser.Title~</value><value>~Owner.Id~</value><value>~LoggedInUser.Fax1Type~</value><value>~Contact.Country2~</value><value>~Contact.AccountId~</value><value>~Contact._TypeofOrganization~</value><value>~Contact._ChMS0~</value><value>~LoggedInUser.HTMLSignature~</value><value>~Owner.Phone2Ext~</value><value>~Owner.Title~</value><value>~Contact.ZipFour3~</value><value>~Contact.State3~</value><value>~Owner.Signature~</value><value>~Contact.EditPage~</value><value>~Company.HTMLCanSpamAddressBlock~</value><value>~LoggedInUser.EmailAddress2~</value><value>~Company.Country~</value><value>~Owner.HTMLSignature~</value><value>~Company.StreetAddress2~</value><value>~Owner.Phone1~</value><value>~Company.CanSpamAddressBlock~</value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 01:07:46 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_get_opt_status.yml b/test/vcr_cassettes/email_get_opt_status.yml
new file mode 100644
index 0000000..57b18d9
--- /dev/null
+++ b/test/vcr_cassettes/email_get_opt_status.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.getOptStatus</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '266'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 12:58:44 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '128'
+ Date:
+ - Sun, 26 Jul 2015 00:58:43 GMT
+ Set-Cookie:
+ - app-lb=!bJjMumCYTheHPB1gcOos6QUUDc5trevd9zS0Fif3gxvA9Zs4zIBIqoXD62DMB7wqCMKf8zFJLdL9rbM=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>1</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 00:58:49 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_get_template.yml b/test/vcr_cassettes/email_get_template.yml
new file mode 100644
index 0000000..cc69307
--- /dev/null
+++ b/test/vcr_cassettes/email_get_template.yml
@@ -0,0 +1,118 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.getEmailTemplate</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3649</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '244'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 13:17:06 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Vary:
+ - Accept-Encoding
+ Date:
+ - Sun, 26 Jul 2015 01:17:06 GMT
+ Connection:
+ - close
+ Set-Cookie:
+ - app-lb=!Flm102Q1X/paEH1gcOos6QUUDc5trRdQIdihKTUs5MfQrp4SjjTU2MPK3UBq8D4ZANIGn0BKhPrj7Nw=;
+ path=/
+ body:
+ encoding: ASCII-8BIT
+ string: "<?xml version=\"1.0\" encoding=\"utf-8\"?><methodResponse><params><param><value><struct><member><name>pieceTitle</name><value>Test
+ Email Template</value></member><member><name>categories</name><value></value></member><member><name>fromAddress</name><value>\"~Owner.FirstName~
+ ~Owner.LastName~\" <~Owner.Email~></value></member><member><name>toAddress</name><value>~Contact.Email~</value></member><member><name>ccAddress</name><value></value></member><member><name>bccAddress</name><value></value></member><member><name>subject</name><value>Test
+ Testing</value></member><member><name>textBody</name><value>This email was
+ sent as HTML-only. To view it, please visit:\r\n~HostedEmail.Url~</value></member><member><name>htmlBody</name><value><div
+ id=\"mainContent\" style=\"text-align: left;\">\n<table cellpadding=\"10\"
+ cellspacing=\"0\" style=\"background-color: rgb(204,204,204); width: 100%;
+ height: 100%;\">\n<tbody>\n<tr>\n<td valign=\"top\">\n<table
+ align=\"center\" cellpadding=\"0\" cellspacing=\"0\">\n<tbody>\n<tr>\n<td>\n<table
+ cellpadding=\"0\" cellspacing=\"0\" style=\"width: 600px;\">\n<tbody>\n<tr>\n<td
+ sectionid=\"preheader\" style=\"text-align: left; margin: 0; padding: 10px
+ 0; border: none; white-space: normal; line-height: normal;\">\n<div>\n<div>\n<div
+ style=\"font-size: 11px; font-family: arial; color: rgb(42,41,40); margin:
+ 0; padding: 0; background: none; border: none; white-space: normal; line-height:
+ normal; overflow: visible; text-align: center;\">\n<div contentid=\"preheader\"
+ style=\"font-size: 11px; font-family: arial; color: rgb(42,41,40); margin:
+ 0; padding: 0; background: none; border: none; white-space: normal; line-height:
+ normal; overflow: visible; text-align: center;\">\n<div>\nHaving
+ trouble viewing this email? <a href=\"~Link-1911~\" shape=\"rect\" style=\"color:
+ rgb(42,41,40);\">Click here</a>\n</div>\n</div>\n</div>\n</div>\n</div>\n</td>\n</tr>\n<tr>\n<td
+ sectionid=\"header\" style=\"background-color: rgb(255,255,255); text-align:
+ left; margin: 0; padding: 0; border: none; white-space: normal; line-height:
+ normal; height: 30px;\">\n<div>\n<div style=\"height: 15px; line-height:
+ 15px;\">\n&nbsp;\n</div>\n</div>\n<div>\n<div>\n<div
+ style=\"font-size: 20px; font-weight: bold; font-family: arial; color: rgb(102,153,64);
+ margin: 0; padding: 0; background: none; border: none; white-space: normal;
+ line-height: normal; overflow: visible; text-align: left;\">\n<div contentid=\"title\"
+ style=\"font-size: 20px; font-weight: bold; font-family: arial; color: rgb(102,153,64);
+ margin: 0; padding: 0; background: none; border: none; white-space: normal;
+ line-height: normal; overflow: visible; text-align: left;\">\n<div>\n&nbsp;&nbsp;&nbsp;~Company.Company~\n</div>\n</div>\n</div>\n</div>\n</div>\n<div>\n<div
+ style=\"height: 15px; line-height: 15px;\">\n&nbsp;\n</div>\n</div>\n</td>\n</tr>\n</tbody>\n</table>\n</td>\n</tr>\n<tr>\n<td>\n<table
+ bgcolor=\"#FFFFFF\" cellpadding=\"20\" cellspacing=\"0\" style=\"width: 600px;
+ background-color: rgb(255,255,255);\">\n<tbody>\n<tr>\n<td
+ sectionid=\"body\" style=\"background-color: rgb(255,255,255); text-align:
+ left; margin: 0; padding: 20px; border: none; white-space: normal; line-height:
+ normal;\" valign=\"top\">\n<div>\n<div>\n<div style=\"font-size:
+ 20px; font-weight: bold; font-family: arial; color: rgb(102,153,64); margin:
+ 0; padding: 0; background: none; border: none; white-space: normal; line-height:
+ normal; overflow: visible; text-align: left;\">\n<div contentid=\"title\"
+ style=\"font-size: 20px; font-weight: bold; font-family: arial; color: rgb(102,153,64);
+ margin: 0; padding: 0; background: none; border: none; white-space: normal;
+ line-height: normal; overflow: visible; text-align: left;\">\n<div>\nHi
+ ~Contact.FirstName~\n</div>\n</div>\n</div>\n</div>\n</div>\n<div>\n<div
+ style=\"height: 15px; line-height: 15px;\">\n&nbsp;\n</div>\n</div>\n<div>\n<div
+ style=\"font-size: 12px; font-family: arial; color: rgb(120,120,120); margin:
+ 0; padding: 0; background: none; border: none; white-space: normal; line-height:
+ normal; overflow: visible;\">\n<div contentid=\"paragraph\" style=\"font-size:
+ 12px; font-family: arial; color: rgb(120,120,120); margin: 0; padding: 0;
+ background: none; border: none; white-space: normal; line-height: normal;
+ overflow: visible;\">\n<div style=\"overflow: visible;\">\nThank
+ you for doing business with ~Company.Company~. \n<br clear=\"none\" />\n<br
+ clear=\"none\" />\n Sincerely,\n</div>\n</div>\n</div>\n</div>\n<div>\n<div
+ style=\"height: 15px; line-height: 15px;\">\n&nbsp;\n</div>\n</div>\n<div>\n<div>\n~Owner.HTMLSignature~\n</div>\n</div>\n</td>\n</tr>\n<tr>\n<td
+ sectionid=\"footer\" style=\"background-color: rgb(122,193,67); text-align:
+ left; margin: 0; padding: 20px; border: none; white-space: normal; line-height:
+ normal;\" valign=\"top\">\n<div>\n<div style=\"font-size: 10px;
+ font-family: verdana; color: rgb(42,41,40); margin: 0; padding: 0; background:
+ none; border: none; white-space: normal; line-height: normal; overflow: visible;\">\n<div
+ contentid=\"paragraph\" style=\"font-size: 10px; font-family: verdana; color:
+ rgb(42,41,40); margin: 0; padding: 0; background: none; border: none; white-space:
+ normal; line-height: normal; overflow: visible;\">\n<div>\nIf you
+ no longer wish to receive our emails, click the link below: \n<br clear=\"none\"
+ />\n<a href=\"~Link-1909~\" shape=\"rect\" style=\"font-size: 11px;
+ font-family: arial; color: rgb(0,114,143);\">Unsubscribe</a>\n</div>\n</div>\n</div>\n</div>\n<div>\n<div
+ style=\"font-size: 10px; font-family: verdana; color: rgb(42,41,40); margin:
+ 0; padding: 0; background: none; border: none; white-space: normal; line-height:
+ normal; overflow: visible;\">\n~Company.HTMLCanSpamAddressBlock~\n</div>\n</div>\n</td>\n</tr>\n</tbody>\n</table>\n</td>\n</tr>\n</tbody>\n</table>\n</td>\n</tr>\n</tbody>\n</table>\n</div></value></member><member><name>contentType</name><value>Multipart</value></member><member><name>mergeContext</name><value>Contact</value></member></struct></value></param></params></methodResponse>"
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 01:17:11 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_optin.yml b/test/vcr_cassettes/email_optin.yml
new file mode 100644
index 0000000..57a492f
--- /dev/null
+++ b/test/vcr_cassettes/email_optin.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.optIn</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>because i said so</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '323'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 13:00:39 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 01:00:39 GMT
+ Set-Cookie:
+ - app-lb=!5nxnGxdkuCJtM2BgcOos6QUUDc5trelc3pZ1XtQ72kFVpkCp+niAF9aoUCBrjjwP2VweA972axXQuEc=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>0</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 01:00:44 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_optout.yml b/test/vcr_cassettes/email_optout.yml
new file mode 100644
index 0000000..02f0ed9
--- /dev/null
+++ b/test/vcr_cassettes/email_optout.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.optOut</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>because i said so</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '321'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 13:05:25 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 01:05:24 GMT
+ Set-Cookie:
+ - app-lb=!3RnJnFp8A8IWSIFgcOos6QUUDc5trZenL7ZhuhfLaqlXlu8/iD7MpacOZatIh1OUrHb1O/dXS9zFAEc=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 01:05:30 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_send.yml b/test/vcr_cassettes/email_send.yml
new file mode 100644
index 0000000..76b1358
--- /dev/null
+++ b/test/vcr_cassettes/email_send.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.sendEmail</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><array><data><value><i4>304</i4></value></data></array></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>Multipart</string></value></param><param><value><string>Question</string></value></param><param><value><string><em>Where's the money?</em></string></value></param><param><value><string>Where's the money?</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '823'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 18:12:41 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 06:12:41 GMT
+ Set-Cookie:
+ - app-lb=!oBOEXJjuJBkLy25gcOos6QUUDc5trTU8mWclXgkxITEmdEgR2ryRhepGolGaYggEokUho52K+zQFJRY=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>0</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 06:12:46 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_send_template.yml b/test/vcr_cassettes/email_send_template.yml
new file mode 100644
index 0000000..3fa67a2
--- /dev/null
+++ b/test/vcr_cassettes/email_send_template.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.sendEmail</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><array><data><value><i4>304</i4></value></data></array></value></param><param><value><string>3649</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '330'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 18:21:45 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 06:21:45 GMT
+ Set-Cookie:
+ - app-lb=!DgCMPFLPwsRrJ7FgcOos6QUUDc5trW40eacyVJiXX9ivZvIUPj3Z1Vq2QHpBKKIGpIHZuWRMPAxjDss=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 06:21:50 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/email_update_template.yml b/test/vcr_cassettes/email_update_template.yml
new file mode 100644
index 0000000..bf149ed
--- /dev/null
+++ b/test/vcr_cassettes/email_update_template.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>APIEmailService.updateEmailTemplate</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3649</i4></value></param><param><value><string>Testingness Testagram</string></value></param><param><value><string></string></value></param><param><value><string></string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>Testingness Testagrams</string></value></param><param><value><string>Stuff</string></value></param><param><value><string><em>Stuff</em></string></value></param><param><value><string>Multipart</string></value></param><param><value><string>Contact</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '927'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 18:34:08 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sun, 26 Jul 2015 06:34:08 GMT
+ Set-Cookie:
+ - app-lb=!NORea5udHdc0/nBgcOos6QUUDc5trboDiqGn/2sseBn/yrXkGUYRZI/tjRKQhFWGZqtX4qFzm40307M=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sun, 26 Jul 2015 06:34:13 GMT
+recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
fe368f5b328fe0f40083264be2a7c29a3b72c1fd
|
Up the cov on data client a bit
|
diff --git a/test/client/data_test.rb b/test/client/data_test.rb
index 530ee0e..035acb5 100644
--- a/test/client/data_test.rb
+++ b/test/client/data_test.rb
@@ -1,95 +1,102 @@
require_relative('../test_helper')
class DataTest < Test::Unit::TestCase
def test_data_add
data_hash = { Company: 'Hogwarts of America', Phone1: '123-456-7899',
Website: 'http://hogwarts-usa.com', StreetAddress1: '123 Wizard Ave.',
City: 'Redmond', State: 'WA', PostalCode: '98052',
Country: 'United States' }
VCR.use_cassette('data_add') do
result = Infusionsoft.data_add('Company', data_hash)
assert_instance_of Fixnum, result
end
end
def test_data_load
desired_fields = [:Company, :StreetAddress1, :City, :State, :PostalCode, :Country]
expected_fields = desired_fields.map { |f| f.to_s }.sort
VCR.use_cassette('data_load') do
result = Infusionsoft.data_load('Company', 3618, desired_fields)
assert_equal result.keys.sort, expected_fields
end
end
def test_data_update
update_hash = { Phone1: '(987) 654-3211' }
VCR.use_cassette('data_update') do
result = Infusionsoft.data_update('Company', 3618, update_hash)
assert_equal result, 3618
assert_equal Infusionsoft.data_load('Company', 3618, [:Phone1])['Phone1'], update_hash[:Phone1]
end
end
def test_data_delete
VCR.use_cassette('data_delete') do
result = Infusionsoft.data_delete('Company', 3618)
assert_true result
end
end
def test_data_find_by_field
VCR.use_cassette('data_find_by_field') do
result = Infusionsoft.data_find_by_field('Company', 5, 0, :Company, 'Hogwarts of America', [:Id, :Company])
assert_instance_of Array, result
assert_compare result.size, :>, 0
end
end
def test_data_query
VCR.use_cassette('data_query') do
result = Infusionsoft.data_query('Company', 5, 0, { :Company => 'Hogwarts of America' }, [:Id, :Company])
assert_instance_of Array, result
assert_compare result.size, :>, 0
end
end
def test_data_query_order_by
VCR.use_cassette('data_query_order_by') do
result = Infusionsoft.data_query_order_by('Company', 5, 0, { :Company => 'Hogwarts of America' }, [:Id, :Company], :Id, false)
assert_instance_of Array, result
assert_compare result.size, :>, 0
assert_compare result.first['Id'].to_i, :>, result.last['Id'].to_i
end
end
def test_data_add_custom_field
VCR.use_cassette('data_add_custom_field') do
result = Infusionsoft.data_add_custom_field('Company', 'Awesomeness Level', 'Text', 4)
assert_instance_of Fixnum, result
end
end
def test_data_auth_user_success
password = Digest::MD5.new.hexdigest 'good_pass'
VCR.use_cassette('data_auth_user_success') do
result = Infusionsoft.data_authenticate_user('[email protected]', password)
assert_instance_of Fixnum, result
end
end
def test_data_auth_user_failure
VCR.use_cassette('data_auth_user_failure') do
assert_raise_kind_of Infusionsoft::FailedLoginAttemptError do
Infusionsoft.data_authenticate_user('[email protected]', 'bad_pass')
end
end
end
def test_data_update_custom_field
VCR.use_cassette('data_update_custom_field') do
result = Infusionsoft.data_update_custom_field(16, {:Label => 'Stuff'} )
assert_true result
end
end
+
+ def test_data_get_app_setting
+ VCR.use_cassette('data_get_app_setting') do
+ result = Infusionsoft.data_get_app_setting('Contact', 'optiontitles')
+ assert_not_nil result
+ end
+ end
end
\ No newline at end of file
diff --git a/test/vcr_cassettes/data_get_app_setting.yml b/test/vcr_cassettes/data_get_app_setting.yml
new file mode 100644
index 0000000..d20c3dc
--- /dev/null
+++ b/test/vcr_cassettes/data_get_app_setting.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.getAppSetting</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Contact</string></value></param><param><value><string>optiontitles</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.9 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '307'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 26 Jul 2015 11:52:30 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '291'
+ Date:
+ - Sat, 25 Jul 2015 23:52:30 GMT
+ Set-Cookie:
+ - app-lb=!A/bDQyH+Uv/89StgcOos6QUUDc5trcDedgnc0I05zDPSlaHoDsjbvNjsryPmsEC6yQnCa2V/k60YWTM=;
+ path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value>Sir Madam Sith Lord Darth</value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 25 Jul 2015 23:52:35 GMT
+recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
55bb738847c24c510d81c996052964ba170233e0
|
Move to ruby 2.2.2
|
diff --git a/.travis.yml b/.travis.yml
index 9d00fe4..a6b45fb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,9 +1,9 @@
language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.5
- - 2.2.1
+ - 2.2.2
- jruby-19mode # JRuby in 1.9 mode
- jruby-20mode # JRuby in 2.0 mode
- rbx-2.5.2
|
nateleavitt/infusionsoft
|
8b3b47b0c14912de16262bfd0ef11778b9abc00d
|
Removing copyright
|
diff --git a/LICENSE.md b/LICENSE.md
index c7febe1..061bdc4 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,22 +1,20 @@
The MIT License (MIT)
-Copyright (c) 2013 Nathan Leavitt
-
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
nateleavitt/infusionsoft
|
178ae096216bd49b41b5c381d92e0d3eddb85352
|
adding travis ci coverage
|
diff --git a/README.md b/README.md
index 0863461..128d076 100644
--- a/README.md
+++ b/README.md
@@ -1,109 +1,109 @@
-[](https://travis-ci.org/TheMetalCode/infusionsoft)
+[](https://travis-ci.org/nateleavitt/infusionsoft)
[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* 07/08/2015 - I am currently rewriting this gem to use the latest Infusionsoft API authentication Oauth flow. Also, I'm in the process of thinking about the best implementation for the gem. I would like to separate out the objects. For example make calls like so: Infusionsoft::Contact.add. If you have any suggestions, let me know.
* v1.1.9 - Implementation of tests (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7 (It will work, but tests require Ruby >= 1.9)
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2015 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
d77033b97edbdbbbf3743ed0441c54451e068fa5
|
adding coverage status to readme
|
diff --git a/README.md b/README.md
index 5349a08..0863461 100644
--- a/README.md
+++ b/README.md
@@ -1,108 +1,109 @@
[](https://travis-ci.org/TheMetalCode/infusionsoft)
-[](https://coveralls.io/r/TheMetalCode/infusionsoft?branch=master)
+[](https://coveralls.io/github/nateleavitt/infusionsoft?branch=master)
+
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* 07/08/2015 - I am currently rewriting this gem to use the latest Infusionsoft API authentication Oauth flow. Also, I'm in the process of thinking about the best implementation for the gem. I would like to separate out the objects. For example make calls like so: Infusionsoft::Contact.add. If you have any suggestions, let me know.
* v1.1.9 - Implementation of tests (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7 (It will work, but tests require Ruby >= 1.9)
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2015 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
537d8422109607e9a7137658a7545dc4ca5b4e2e
|
updating readme for v1.1.9 gem updates
|
diff --git a/README.md b/README.md
index ca0d437..5349a08 100644
--- a/README.md
+++ b/README.md
@@ -1,107 +1,108 @@
[](https://travis-ci.org/TheMetalCode/infusionsoft)
[](https://coveralls.io/r/TheMetalCode/infusionsoft?branch=master)
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* 07/08/2015 - I am currently rewriting this gem to use the latest Infusionsoft API authentication Oauth flow. Also, I'm in the process of thinking about the best implementation for the gem. I would like to separate out the objects. For example make calls like so: Infusionsoft::Contact.add. If you have any suggestions, let me know.
+* v1.1.9 - Implementation of tests (Thanks! @TheMetalCode)
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails >= 3** - add `'infusionsoft'` to your `Gemfile`
2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7 (It will work, but tests require Ruby >= 1.9)
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2015 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
1227ae210f61be64b95b471cf0a90e5176107161
|
moving to gem 1.1.9 with tests included
|
diff --git a/infusionsoft.gemspec b/infusionsoft.gemspec
index a67e298..b5145b8 100644
--- a/infusionsoft.gemspec
+++ b/infusionsoft.gemspec
@@ -1,19 +1,19 @@
# encoding: utf-8
require File.expand_path('../lib/infusionsoft/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'infusionsoft'
gem.summary = %q{Ruby wrapper for the Infusionsoft API}
gem.description = 'A Ruby wrapper written for the Infusionsoft API'
gem.authors = ["Nathan Leavitt"]
- gem.email = ['[email protected]']
- gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
+ gem.email = ['[email protected]']
+ # gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)}
gem.files = `git ls-files`.split("\n")
gem.homepage = 'https://github.com/nateleavitt/infusionsoft'
gem.require_paths = ['lib']
gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6')
gem.add_development_dependency 'rake'
gem.version = Infusionsoft::VERSION.dup
end
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 96592c8..84b58bd 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.1.8'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.1.9'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
nateleavitt/infusionsoft
|
721849d1b40101d4211f4c82d4d3dcb48f10bffe
|
adding comments to explain why other rest methods are here
|
diff --git a/lib/infusionsoft/request.rb b/lib/infusionsoft/request.rb
index 661154d..d3b95ae 100644
--- a/lib/infusionsoft/request.rb
+++ b/lib/infusionsoft/request.rb
@@ -1,33 +1,34 @@
module Infusionsoft
+ # Incase Infusionsoft ever creates a restful API :)
module Request
# Perform an GET request
def get(service_call, *args)
request(:get, service_call, *args)
end
def post(path, params={}, options={})
request(:post, path, params, options)
end
# Perform an HTTP PUT request
def put(path, params={}, options={})
request(:put, path, params, options)
end
# Perform an HTTP DELETE request
def delete(path, params={}, options={})
request(:delete, path, params, options)
end
private
# Perform request
def request(method, service_call, *args)
case method.to_sym
when :get
response = connection(service_call, *args)
end
end
end
end
|
nateleavitt/infusionsoft
|
d85f9e22d9c813cc9de138b68098f4e076972bf7
|
Get the real data out
|
diff --git a/test/vcr_cassettes/add_to_group.yml b/test/vcr_cassettes/add_to_group.yml
index 20eae6f..9861cf2 100644
--- a/test/vcr_cassettes/add_to_group.yml
+++ b/test/vcr_cassettes/add_to_group.yml
@@ -1,49 +1,49 @@
---
http_interactions:
- request:
method: post
- uri: https://yi226.infusionsoft.com/api/xmlrpc
+ uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
- <?xml version="1.0" ?><methodCall><methodName>ContactService.addToGroup</methodName><params><param><value><string>84f119a62b3d8b3e0ece196184e8f0f5</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.addToGroup</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '279'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Sat, 30 May 2015 19:30:00 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '138'
Date:
- Sat, 30 May 2015 07:29:59 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
http_version:
recorded_at: Sat, 30 May 2015 07:30:00 GMT
recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/remove_from_group.yml b/test/vcr_cassettes/remove_from_group.yml
index 1869f55..0d0122d 100644
--- a/test/vcr_cassettes/remove_from_group.yml
+++ b/test/vcr_cassettes/remove_from_group.yml
@@ -1,49 +1,49 @@
---
http_interactions:
- request:
method: post
- uri: https://yi226.infusionsoft.com/api/xmlrpc
+ uri: https://test.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
- <?xml version="1.0" ?><methodCall><methodName>ContactService.removeFromGroup</methodName><params><param><value><string>84f119a62b3d8b3e0ece196184e8f0f5</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.removeFromGroup</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '284'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- Sat, 30 May 2015 19:31:42 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '138'
Date:
- Sat, 30 May 2015 07:31:42 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
http_version:
recorded_at: Sat, 30 May 2015 07:31:42 GMT
recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
d3cdcc9e30440be321e1ac7cbeedb8e98c1d50ca
|
Adding a couple more tests, getting rid of .orig cassettes
|
diff --git a/test/client/contact_test.rb b/test/client/contact_test.rb
index 3cb8b4e..73f3454 100644
--- a/test/client/contact_test.rb
+++ b/test/client/contact_test.rb
@@ -1,65 +1,79 @@
require_relative('../test_helper')
class ContactTest < Test::Unit::TestCase
def test_contact_add
data_hash = { Email: '[email protected]', FirstName: 'Severus', LastName: 'Snape' }
VCR.use_cassette('contact_add') do
result = Infusionsoft.contact_add(data_hash)
assert_instance_of Fixnum, result
end
end
def test_contact_merge
VCR.use_cassette('contact_merge') do
result = Infusionsoft.contact_merge(3602, 3604)
assert_true result
end
end
def test_contact_add_dup_check_with_dup
data_hash = { Email: '[email protected]', FirstName: 'Severus',
LastName: 'Snape', Company: 'Test Company' }
VCR.use_cassette('contact_add_dup_check_with_dup') do
existing_contact = Infusionsoft.contact_load(3606, [:Id, :FirstName, :LastName, :Email, :Company])
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndName')
assert_equal result, existing_contact['Id']
assert_equal Infusionsoft.contact_load(existing_contact['Id'], [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_add_dup_check_no_dup
data_hash = { Email: '[email protected]', FirstName: 'Albus',
LastName: 'Dumbledore', Company: 'Hogwarts' }
VCR.use_cassette('contact_add_dup_check_no_dup') do
result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndNameAndCompany')
assert_instance_of Fixnum, result
end
end
def test_contact_load
desired_fields = [:FirstName, :LastName]
expected_fields = desired_fields.map { |f| f.to_s }.sort
VCR.use_cassette('contact_load') do
result = Infusionsoft.contact_load(3606, desired_fields)
assert_equal result.keys.sort, expected_fields
end
end
def test_contact_update
data_hash = { Company: 'Hogwarts' }
VCR.use_cassette('contact_update') do
result = Infusionsoft.contact_update(3606, data_hash)
assert_equal result, 3606
assert_equal Infusionsoft.contact_load(3606, [:Company])['Company'], data_hash[:Company]
end
end
def test_contact_find_by_email
VCR.use_cassette('find_by_email') do
result = Infusionsoft.contact_find_by_email('[email protected]', [:Id])
assert_instance_of Array, result
assert_instance_of Hash, result.first
end
end
+
+ def test_contact_add_to_group
+ VCR.use_cassette('add_to_group') do
+ result = Infusionsoft.contact_add_to_group(3794, 382)
+ assert_equal result, true
+ end
+ end
+
+ def test_contact_remove_from_group
+ VCR.use_cassette('remove_from_group') do
+ result = Infusionsoft.contact_remove_from_group(3794, 382)
+ assert_equal result, true
+ end
+ end
end
\ No newline at end of file
diff --git a/test/vcr_cassettes/data_update_custom_field.yml.orig b/test/vcr_cassettes/add_to_group.yml
similarity index 64%
rename from test/vcr_cassettes/data_update_custom_field.yml.orig
rename to test/vcr_cassettes/add_to_group.yml
index 67201bf..20eae6f 100644
--- a/test/vcr_cassettes/data_update_custom_field.yml.orig
+++ b/test/vcr_cassettes/add_to_group.yml
@@ -1,49 +1,49 @@
---
http_interactions:
- request:
method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
+ uri: https://yi226.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.updateCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>16</i4></value></param><param><value><struct><member><name>Label</name><value><string>Stuff</string></value></member></struct></value></param></params></methodCall>
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.addToGroup</methodName><params><param><value><string>84f119a62b3d8b3e0ece196184e8f0f5</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- - '358'
+ - '279'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- - Sun, 12 Apr 2015 11:12:51 GMT
+ - Sat, 30 May 2015 19:30:00 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '138'
Date:
- - Sat, 11 Apr 2015 23:12:51 GMT
+ - Sat, 30 May 2015 07:29:59 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
http_version:
- recorded_at: Sat, 11 Apr 2015 23:12:51 GMT
+ recorded_at: Sat, 30 May 2015 07:30:00 GMT
recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add.yml.orig b/test/vcr_cassettes/data_add.yml.orig
deleted file mode 100644
index cd066e2..0000000
--- a/test/vcr_cassettes/data_add.yml.orig
+++ /dev/null
@@ -1,49 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.add</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member><member><name>Phone1</name><value><string>123-456-7899</string></value></member><member><name>Website</name><value><string>http://hogwarts-usa.com</string></value></member><member><name>StreetAddress1</name><value><string>123 Wizard Ave.</string></value></member><member><name>City</name><value><string>Redmond</string></value></member><member><name>State</name><value><string>WA</string></value></member><member><name>PostalCode</name><value><string>98052</string></value></member><member><name>Country</name><value><string>United States</string></value></member></struct></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '937'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 05:34:01 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '131'
- Date:
- - Sat, 11 Apr 2015 17:34:00 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3620</i4></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 17:34:00 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add_custom_field.yml.orig b/test/vcr_cassettes/data_add_custom_field.yml.orig
deleted file mode 100644
index 4af76cb..0000000
--- a/test/vcr_cassettes/data_add_custom_field.yml.orig
+++ /dev/null
@@ -1,49 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.addCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><string>Awesomeness Level</string></value></param><param><value><string>Text</string></value></param><param><value><i4>4</i4></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '404'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 11:09:25 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '129'
- Date:
- - Sat, 11 Apr 2015 23:09:25 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>16</i4></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 23:09:25 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_failure.yml.orig b/test/vcr_cassettes/data_auth_user_failure.yml.orig
deleted file mode 100644
index 0d78a29..0000000
--- a/test/vcr_cassettes/data_auth_user_failure.yml.orig
+++ /dev/null
@@ -1,50 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>bad_pass</string></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '312'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 05:46:13 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '292'
- Date:
- - Sat, 11 Apr 2015 17:46:13 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: '<?xml version="1.0" encoding="utf-8"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><i4>13</i4></value></member><member><name>faultString</name><value>[FailedLoginAttempt]username
- not found: [email protected]</value></member></struct></value></fault></methodResponse>'
- http_version:
- recorded_at: Sat, 11 Apr 2015 17:46:13 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_success.yml.orig b/test/vcr_cassettes/data_auth_user_success.yml.orig
deleted file mode 100644
index d91a697..0000000
--- a/test/vcr_cassettes/data_auth_user_success.yml.orig
+++ /dev/null
@@ -1,49 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>4ac7729fa5d0c8b58a90b6ee97ab8bea</string></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '342'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 05:54:14 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '128'
- Date:
- - Sat, 11 Apr 2015 17:54:13 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>4</i4></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 17:54:14 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_find_by_field.yml.orig b/test/vcr_cassettes/data_find_by_field.yml.orig
deleted file mode 100644
index b3c0208..0000000
--- a/test/vcr_cassettes/data_find_by_field.yml.orig
+++ /dev/null
@@ -1,51 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.findByField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><string>Company</string></value></param><param><value><string>Hogwarts of America</string></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '577'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 10:37:52 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '472'
- Date:
- - Sat, 11 Apr 2015 22:37:52 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value></data></array></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 22:37:52 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_load.yml.orig b/test/vcr_cassettes/data_load.yml.orig
deleted file mode 100644
index f94b4a4..0000000
--- a/test/vcr_cassettes/data_load.yml.orig
+++ /dev/null
@@ -1,51 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Company</string></value><value><string>StreetAddress1</string></value><value><string>City</string></value><value><string>State</string></value><value><string>PostalCode</string></value><value><string>Country</string></value></data></array></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '579'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 05:34:01 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '513'
- Date:
- - Sat, 11 Apr 2015 17:34:01 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>PostalCode</name><value>98052</value></member><member><name>State</name><value>WA</value></member><member><name>Country</name><value>United
- States</value></member><member><name>Company</name><value>Hogwarts of America</value></member><member><name>StreetAddress1</name><value>123
- Wizard Ave.</value></member><member><name>City</name><value>Redmond</value></member></struct></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 17:34:01 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query.yml.orig b/test/vcr_cassettes/data_query.yml.orig
deleted file mode 100644
index 97bc37b..0000000
--- a/test/vcr_cassettes/data_query.yml.orig
+++ /dev/null
@@ -1,51 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '586'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 10:40:04 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '472'
- Date:
- - Sat, 11 Apr 2015 22:40:03 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value></data></array></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 22:40:04 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query_order_by.yml.orig b/test/vcr_cassettes/data_query_order_by.yml.orig
deleted file mode 100644
index 101e6f4..0000000
--- a/test/vcr_cassettes/data_query_order_by.yml.orig
+++ /dev/null
@@ -1,51 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param><param><value><string>Id</string></value></param><param><value><boolean>0</boolean></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '685'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 10:42:00 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '472'
- Date:
- - Sat, 11 Apr 2015 22:41:59 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
- of America</value></member></struct></value></data></array></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 22:42:00 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_update.yml.orig b/test/vcr_cassettes/data_update.yml.orig
deleted file mode 100644
index 7e0abc5..0000000
--- a/test/vcr_cassettes/data_update.yml.orig
+++ /dev/null
@@ -1,96 +0,0 @@
----
-http_interactions:
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.update</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><struct><member><name>Phone1</name><value><string>987-654-3211</string></value></member></struct></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '411'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 10:13:28 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '131'
- Date:
- - Sat, 11 Apr 2015 22:13:28 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3618</i4></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 22:13:28 GMT
-- request:
- method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
- body:
- encoding: UTF-8
- string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Phone1</string></value></data></array></value></param></params></methodCall>
- headers:
- User-Agent:
- - Infusionsoft-1.1.8 (RubyGem)
- Content-Type:
- - text/xml; charset=utf-8
- Content-Length:
- - '378'
- Connection:
- - keep-alive
- Accept-Encoding:
- - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
- Accept:
- - "*/*"
- response:
- status:
- code: 200
- message: OK
- headers:
- Server:
- - Apache-Coyote/1.1
- Pragma:
- - no-cache
- Cache-Control:
- - no-cache, no-store
- Expires:
- - Sun, 12 Apr 2015 10:13:29 GMT
- Content-Type:
- - text/xml;charset=UTF-8
- Content-Length:
- - '200'
- Date:
- - Sat, 11 Apr 2015 22:13:28 GMT
- Set-Cookie:
- - app-lb=2466578442.20480.0000; path=/
- body:
- encoding: UTF-8
- string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Phone1</name><value>(987)
- 654-3211</value></member></struct></value></param></params></methodResponse>
- http_version:
- recorded_at: Sat, 11 Apr 2015 22:13:29 GMT
-recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_delete.yml.orig b/test/vcr_cassettes/remove_from_group.yml
similarity index 68%
rename from test/vcr_cassettes/data_delete.yml.orig
rename to test/vcr_cassettes/remove_from_group.yml
index 91c3ae1..1869f55 100644
--- a/test/vcr_cassettes/data_delete.yml.orig
+++ b/test/vcr_cassettes/remove_from_group.yml
@@ -1,49 +1,49 @@
---
http_interactions:
- request:
method: post
- uri: https://test.infusionsoft.com/api/xmlrpc
+ uri: https://yi226.infusionsoft.com/api/xmlrpc
body:
encoding: UTF-8
string: |
- <?xml version="1.0" ?><methodCall><methodName>DataService.delete</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param></params></methodCall>
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.removeFromGroup</methodName><params><param><value><string>84f119a62b3d8b3e0ece196184e8f0f5</string></value></param><param><value><i4>3794</i4></value></param><param><value><i4>382</i4></value></param></params></methodCall>
headers:
User-Agent:
- Infusionsoft-1.1.8 (RubyGem)
Content-Type:
- text/xml; charset=utf-8
Content-Length:
- '284'
Connection:
- keep-alive
Accept-Encoding:
- gzip;q=1.0,deflate;q=0.6,identity;q=0.3
Accept:
- "*/*"
response:
status:
code: 200
message: OK
headers:
Server:
- Apache-Coyote/1.1
Pragma:
- no-cache
Cache-Control:
- no-cache, no-store
Expires:
- - Sun, 12 Apr 2015 11:14:53 GMT
+ - Sat, 30 May 2015 19:31:42 GMT
Content-Type:
- text/xml;charset=UTF-8
Content-Length:
- '138'
Date:
- - Sat, 11 Apr 2015 23:14:52 GMT
+ - Sat, 30 May 2015 07:31:42 GMT
Set-Cookie:
- app-lb=2466578442.20480.0000; path=/
body:
encoding: UTF-8
string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
http_version:
- recorded_at: Sat, 11 Apr 2015 23:14:53 GMT
+ recorded_at: Sat, 30 May 2015 07:31:42 GMT
recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
a5618604a87aba2dd340a7917b1c56fb43b6f85d
|
Trigger build, get coverage badge to work
|
diff --git a/.gitignore b/.gitignore
index 751ccef..1e9a872 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,11 @@
*.gem
log/*.log
tmp/**/*
.DS_Store
rdoc/
coverage
.idea
.bundle
.ruby-gemset
.ruby-version
-Gemfile.lock
\ No newline at end of file
+Gemfile.lock
|
nateleavitt/infusionsoft
|
c6894fcf2f84b979fbdaebc32158016c81e5ab29
|
Travis, coverage, refactored exceptions test, stubbed contact and data client tests
|
diff --git a/.gitignore b/.gitignore
index 2ac39bf..751ccef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,11 @@
*.gem
log/*.log
tmp/**/*
.DS_Store
rdoc/
+coverage
+.idea
+.bundle
+.ruby-gemset
+.ruby-version
+Gemfile.lock
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..9d00fe4
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,9 @@
+language: ruby
+rvm:
+ - 1.9.3
+ - 2.0.0
+ - 2.1.5
+ - 2.2.1
+ - jruby-19mode # JRuby in 1.9 mode
+ - jruby-20mode # JRuby in 2.0 mode
+ - rbx-2.5.2
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..b4f4066
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,12 @@
+source 'https://rubygems.org'
+
+gemspec
+
+group :test do
+ gem 'coveralls', :require => false
+ gem 'mocha'
+ gem 'simplecov', :require => false
+ gem 'test-unit'
+ gem 'vcr'
+ gem 'webmock'
+end
\ No newline at end of file
diff --git a/README.md b/README.md
index 751cfba..0e6cc36 100644
--- a/README.md
+++ b/README.md
@@ -1,104 +1,107 @@
+[](https://travis-ci.org/TheMetalCode/infusionsoft)
+[](https://coveralls.io/r/TheMetalCode/infusionsoft?branch=master)
+
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
* v1.1.8 - Added a default user-agent in the headers. Also, give the
ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails 3** - add `'infusionsoft'` to your `Gemfile`
2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
- config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com
+ config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com DO NOT INCLUDE https://
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
Copyright (c) 2014 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
diff --git a/Rakefile b/Rakefile
index 639ef53..1a8e987 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,3 +1,13 @@
-require 'rake/testtask'
+begin
+ require 'rake/testtask'
-Rake::TestTask.new
+ Rake::TestTask.new do |t|
+ t.libs << 'test'
+ t.test_files = FileList['test/*_test.rb', 'test/**/*_test.rb']
+ t.verbose = true
+ end
+rescue LoadError
+ #no test-unit available
+end
+
+task default: [:test]
diff --git a/test/api_infusion_test.rb b/test/api_infusion_test.rb
deleted file mode 100644
index 30a7288..0000000
--- a/test/api_infusion_test.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'test/unit'
-
-class ApiInfusionTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk # will implement later :(
- end
-end
diff --git a/test/client/contact_test.rb b/test/client/contact_test.rb
new file mode 100644
index 0000000..3cb8b4e
--- /dev/null
+++ b/test/client/contact_test.rb
@@ -0,0 +1,65 @@
+require_relative('../test_helper')
+
+class ContactTest < Test::Unit::TestCase
+
+ def test_contact_add
+ data_hash = { Email: '[email protected]', FirstName: 'Severus', LastName: 'Snape' }
+ VCR.use_cassette('contact_add') do
+ result = Infusionsoft.contact_add(data_hash)
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_contact_merge
+ VCR.use_cassette('contact_merge') do
+ result = Infusionsoft.contact_merge(3602, 3604)
+ assert_true result
+ end
+ end
+
+ def test_contact_add_dup_check_with_dup
+ data_hash = { Email: '[email protected]', FirstName: 'Severus',
+ LastName: 'Snape', Company: 'Test Company' }
+ VCR.use_cassette('contact_add_dup_check_with_dup') do
+ existing_contact = Infusionsoft.contact_load(3606, [:Id, :FirstName, :LastName, :Email, :Company])
+ result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndName')
+ assert_equal result, existing_contact['Id']
+ assert_equal Infusionsoft.contact_load(existing_contact['Id'], [:Company])['Company'], data_hash[:Company]
+ end
+ end
+
+ def test_contact_add_dup_check_no_dup
+ data_hash = { Email: '[email protected]', FirstName: 'Albus',
+ LastName: 'Dumbledore', Company: 'Hogwarts' }
+ VCR.use_cassette('contact_add_dup_check_no_dup') do
+ result = Infusionsoft.contact_add_with_dup_check(data_hash, 'EmailAndNameAndCompany')
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_contact_load
+ desired_fields = [:FirstName, :LastName]
+ expected_fields = desired_fields.map { |f| f.to_s }.sort
+ VCR.use_cassette('contact_load') do
+ result = Infusionsoft.contact_load(3606, desired_fields)
+ assert_equal result.keys.sort, expected_fields
+ end
+ end
+
+ def test_contact_update
+ data_hash = { Company: 'Hogwarts' }
+ VCR.use_cassette('contact_update') do
+ result = Infusionsoft.contact_update(3606, data_hash)
+ assert_equal result, 3606
+ assert_equal Infusionsoft.contact_load(3606, [:Company])['Company'], data_hash[:Company]
+ end
+ end
+
+ def test_contact_find_by_email
+ VCR.use_cassette('find_by_email') do
+ result = Infusionsoft.contact_find_by_email('[email protected]', [:Id])
+ assert_instance_of Array, result
+ assert_instance_of Hash, result.first
+ end
+ end
+end
\ No newline at end of file
diff --git a/test/client/data_test.rb b/test/client/data_test.rb
new file mode 100644
index 0000000..530ee0e
--- /dev/null
+++ b/test/client/data_test.rb
@@ -0,0 +1,95 @@
+require_relative('../test_helper')
+
+class DataTest < Test::Unit::TestCase
+
+ def test_data_add
+ data_hash = { Company: 'Hogwarts of America', Phone1: '123-456-7899',
+ Website: 'http://hogwarts-usa.com', StreetAddress1: '123 Wizard Ave.',
+ City: 'Redmond', State: 'WA', PostalCode: '98052',
+ Country: 'United States' }
+ VCR.use_cassette('data_add') do
+ result = Infusionsoft.data_add('Company', data_hash)
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_data_load
+ desired_fields = [:Company, :StreetAddress1, :City, :State, :PostalCode, :Country]
+ expected_fields = desired_fields.map { |f| f.to_s }.sort
+ VCR.use_cassette('data_load') do
+ result = Infusionsoft.data_load('Company', 3618, desired_fields)
+ assert_equal result.keys.sort, expected_fields
+ end
+ end
+
+ def test_data_update
+ update_hash = { Phone1: '(987) 654-3211' }
+ VCR.use_cassette('data_update') do
+ result = Infusionsoft.data_update('Company', 3618, update_hash)
+ assert_equal result, 3618
+ assert_equal Infusionsoft.data_load('Company', 3618, [:Phone1])['Phone1'], update_hash[:Phone1]
+ end
+ end
+
+ def test_data_delete
+ VCR.use_cassette('data_delete') do
+ result = Infusionsoft.data_delete('Company', 3618)
+ assert_true result
+ end
+ end
+
+ def test_data_find_by_field
+ VCR.use_cassette('data_find_by_field') do
+ result = Infusionsoft.data_find_by_field('Company', 5, 0, :Company, 'Hogwarts of America', [:Id, :Company])
+ assert_instance_of Array, result
+ assert_compare result.size, :>, 0
+ end
+ end
+
+ def test_data_query
+ VCR.use_cassette('data_query') do
+ result = Infusionsoft.data_query('Company', 5, 0, { :Company => 'Hogwarts of America' }, [:Id, :Company])
+ assert_instance_of Array, result
+ assert_compare result.size, :>, 0
+ end
+ end
+
+ def test_data_query_order_by
+ VCR.use_cassette('data_query_order_by') do
+ result = Infusionsoft.data_query_order_by('Company', 5, 0, { :Company => 'Hogwarts of America' }, [:Id, :Company], :Id, false)
+ assert_instance_of Array, result
+ assert_compare result.size, :>, 0
+ assert_compare result.first['Id'].to_i, :>, result.last['Id'].to_i
+ end
+ end
+
+ def test_data_add_custom_field
+ VCR.use_cassette('data_add_custom_field') do
+ result = Infusionsoft.data_add_custom_field('Company', 'Awesomeness Level', 'Text', 4)
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_data_auth_user_success
+ password = Digest::MD5.new.hexdigest 'good_pass'
+ VCR.use_cassette('data_auth_user_success') do
+ result = Infusionsoft.data_authenticate_user('[email protected]', password)
+ assert_instance_of Fixnum, result
+ end
+ end
+
+ def test_data_auth_user_failure
+ VCR.use_cassette('data_auth_user_failure') do
+ assert_raise_kind_of Infusionsoft::FailedLoginAttemptError do
+ Infusionsoft.data_authenticate_user('[email protected]', 'bad_pass')
+ end
+ end
+ end
+
+ def test_data_update_custom_field
+ VCR.use_cassette('data_update_custom_field') do
+ result = Infusionsoft.data_update_custom_field(16, {:Label => 'Stuff'} )
+ assert_true result
+ end
+ end
+end
\ No newline at end of file
diff --git a/test/exceptions_test.rb b/test/exceptions_test.rb
new file mode 100644
index 0000000..b70b34a
--- /dev/null
+++ b/test/exceptions_test.rb
@@ -0,0 +1,131 @@
+require_relative('test_helper')
+
+class ExceptionsTest < Test::Unit::TestCase
+
+ def setup
+ super
+ @test_exc_msg = 'Some error message'
+ end
+
+ def test_should_raise_invalid_config
+ stub_client_call(1)
+ assert_raise_kind_of Infusionsoft::InvalidConfigError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_invalid_key
+ stub_client_call(2)
+ assert_raise_kind_of Infusionsoft::InvalidKeyError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_unexpected_error
+ stub_client_call(3)
+ assert_raise_kind_of Infusionsoft::UnexpectedError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_database_error
+ stub_client_call(4)
+ assert_raise_kind_of Infusionsoft::DatabaseError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_record_not_found
+ stub_client_call(5)
+ assert_raise_kind_of Infusionsoft::RecordNotFoundError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_loading_error
+ stub_client_call(6)
+ assert_raise_kind_of Infusionsoft::LoadingError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_table_access
+ stub_client_call(7)
+ assert_raise_kind_of Infusionsoft::NoTableAccessError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_field_access
+ stub_client_call(8)
+ assert_raise_kind_of Infusionsoft::NoFieldAccessError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_table_found
+ stub_client_call(9)
+ assert_raise_kind_of Infusionsoft::NoTableFoundError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_field_found
+ stub_client_call(10)
+ assert_raise_kind_of Infusionsoft::NoFieldFoundError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_fields_error
+ stub_client_call(11)
+ assert_raise_kind_of Infusionsoft::NoFieldsError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_invalid_parameter_error
+ stub_client_call(12)
+ assert_raise_kind_of Infusionsoft::InvalidParameterError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_failed_login_attempt
+ stub_client_call(13)
+ assert_raise_kind_of Infusionsoft::FailedLoginAttemptError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_no_access_error
+ stub_client_call(14)
+ assert_raise_kind_of Infusionsoft::NoAccessError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_failed_login_attempt_password_expired
+ stub_client_call(15)
+ assert_raise_kind_of Infusionsoft::FailedLoginAttemptPasswordExpiredError do
+ run_exceptional_data_query
+ end
+ end
+
+ def test_should_raise_infusionapierror_when_fault_code_unknown
+ stub_client_call(42)
+ assert_raise_kind_of InfusionAPIError do
+ run_exceptional_data_query
+ end
+ end
+
+ private
+
+ def stub_client_call(exception_num)
+ XMLRPC::Client.any_instance.stubs(:call).raises(XMLRPC::FaultException.new(exception_num, @test_exc_msg))
+ end
+
+ def run_exceptional_data_query
+ Infusionsoft.data_query(:Contact, 1, 0, {}, [:BlahdyDah])
+ end
+end
diff --git a/test/test_exceptions.rb b/test/test_exceptions.rb
deleted file mode 100644
index 530e275..0000000
--- a/test/test_exceptions.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-require 'test/unit'
-require 'infusionsoft'
-
-
-# override XMLRPC call method
-class XMLRPC::Client
-
- def call(method, *args)
- raise XMLRPC::FaultException.new(@@code, @@message)
- end
-
- def self.set_fault_response(code, message)
- @@code = code
- @@message = message
- end
-end
-
-class TestLogger
- def info(msg); end
- def warn(msg); end
- def error(msg); end
- def debug(msg); end
- def fatal(msg); end
-end
-
-
-class TestExceptions < Test::Unit::TestCase
-
- def setup
- Infusionsoft.configure do |c|
- c.api_logger = TestLogger.new()
- end
- end
-
- def test_should_raise_invalid_config
- exception_test(Infusionsoft::InvalidConfigError, 1, 'The configuration for the application is invalid. Usually this is because there has not been a passphrase entered to generate an encrypted key.')
- end
-
- def test_should_raise_invalid_key
- exception_test(Infusionsoft::InvalidKeyError, 2, "The key passed up for authentication was not valid. It was either empty or didn't match.")
- end
-
- def test_should_raise_unexpected_error
- exception_test(Infusionsoft::UnexpectedError, 3, "An unexpected error has occurred. There was either an error in the data you passed up or there was an unknown error on")
- end
-
- def test_should_raise_database_error
- exception_test(Infusionsoft::DatabaseError, 4, "There was an error in the database access")
- end
-
- def test_should_raise_record_not_found
- exception_test(Infusionsoft::RecordNotFoundError, 5, "A requested record was not found in the database.")
- end
-
- def test_should_raise_loading_error
- exception_test(Infusionsoft::LoadingError, 6, "There was a problem loading a record from the database.")
- end
-
- def test_should_raise_no_table_access
- exception_test(Infusionsoft::NoTableAccessError, 7, "A table was accessed without the proper permission")
- end
-
- def test_should_raise_no_field_access
- exception_test(Infusionsoft::NoFieldAccessError, 8, "A field was accessed without the proper permission.")
- end
-
- def test_should_raise_no_table_found
- exception_test(Infusionsoft::NoTableFoundError, 9, "A table was accessed that doesn't exist in the Data Spec.")
- end
-
- def test_should_raise_no_field_found
- exception_test(Infusionsoft::NoFieldFoundError, 10, "A field was accessed that doesn't exist in the Data Spec.")
- end
-
- def test_should_raise_no_fields_error
- exception_test(Infusionsoft::NoFieldsError, 11, "An update or add operation was attempted with no valid fields to update or add.")
- end
-
- def test_should_raise_invalid_parameter_error
- exception_test(Infusionsoft::InvalidParameterError, 12, "Data sent into the call was invalid.")
- end
-
- def test_should_raise_failed_login_attempt
- exception_test(Infusionsoft::FailedLoginAttemptError, 13, "Someone attempted to authenticate a user and failed.")
- end
-
- def test_should_raise_no_access_error
- exception_test(Infusionsoft::NoAccessError, 14, "Someone attempted to access a plugin they are not paying for.")
- end
-
- def test_should_raise_failed_login_attempt_password_expired
- exception_test(Infusionsoft::FailedLoginAttemptPasswordExpiredError, 15, "Someone attempted to authenticate a user and the password is expired.")
- end
-
- def test_should_raise_infusionapierror_when_fault_code_unknown
- exception_test(InfusionAPIError, 42, "Some random error occurred")
- end
-
-
- private
- def exception_test(exception, code, message)
- XMLRPC::Client.set_fault_response(code, message)
- caught = false
- begin
- Infusionsoft.data_query(:Contact, 1, 0, {}, [:BlahdyDah])
- rescue exception => e
- caught = true
- assert_equal message, e.message
- end
- assert_equal true, caught
- end
-
-end
diff --git a/test/test_helper.rb b/test/test_helper.rb
new file mode 100644
index 0000000..c1a423d
--- /dev/null
+++ b/test/test_helper.rb
@@ -0,0 +1,47 @@
+require 'coveralls'
+Coveralls.wear!
+
+require 'simplecov'
+SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
+ SimpleCov::Formatter::HTMLFormatter,
+ Coveralls::SimpleCov::Formatter
+]
+SimpleCov.start do
+ add_filter '/vendor/'
+ add_filter '/.bundle/'
+ add_filter '/test'
+ add_group 'Clients', 'lib/infusionsoft/client'
+end
+
+require 'test/unit'
+require 'infusionsoft'
+
+require 'vcr'
+require 'webmock/test_unit'
+require 'mocha/test_unit'
+
+WebMock.disable_net_connect!(allow_localhost: true)
+
+VCR.configure do |c|
+ c.cassette_library_dir = 'test/vcr_cassettes'
+ c.hook_into :webmock
+ c.default_cassette_options = { record: :once, match_requests_on: [:method] }
+end
+
+class Test::Unit::TestCase
+ class TestLogger
+ def info(msg); end
+ def warn(msg); end
+ def error(msg); end
+ def debug(msg); end
+ def fatal(msg); end
+ end
+
+ def setup
+ Infusionsoft.configure do |config|
+ config.api_url = 'test.infusionsoft.com'
+ config.api_key = 'not_a_real_key'
+ config.api_logger = TestLogger.new
+ end
+ end
+end
diff --git a/test/vcr_cassettes/contact_add.yml b/test/vcr_cassettes/contact_add.yml
new file mode 100644
index 0000000..3782c4e
--- /dev/null
+++ b/test/vcr_cassettes/contact_add.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.add</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Severus</string></value></member><member><name>LastName</name><value><string>Snape</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '469'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Thu, 09 Apr 2015 19:14:00 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Thu, 09 Apr 2015 07:14:00 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3602</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Thu, 09 Apr 2015 07:14:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_add_dup_check_no_dup.yml b/test/vcr_cassettes/contact_add_dup_check_no_dup.yml
new file mode 100644
index 0000000..c416f81
--- /dev/null
+++ b/test/vcr_cassettes/contact_add_dup_check_no_dup.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.addWithDupCheck</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Albus</string></value></member><member><name>LastName</name><value><string>Dumbledore</string></value></member><member><name>Company</name><value><string>Hogwarts</string></value></member></struct></value></param><param><value><string>EmailAndNameAndCompany</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '629'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 20:13:43 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Fri, 10 Apr 2015 08:13:43 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3612</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 08:13:43 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_add_dup_check_with_dup.yml b/test/vcr_cassettes/contact_add_dup_check_with_dup.yml
new file mode 100644
index 0000000..6affee3
--- /dev/null
+++ b/test/vcr_cassettes/contact_add_dup_check_with_dup.yml
@@ -0,0 +1,142 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>Id</string></value><value><string>FirstName</string></value><value><string>LastName</string></value><value><string>Email</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '480'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 19:15:07 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '379'
+ Date:
+ - Fri, 10 Apr 2015 07:15:06 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Email</name><value>[email protected]</value></member><member><name>FirstName</name><value>Severus</value></member><member><name>Id</name><value><i4>3606</i4></value></member><member><name>LastName</name><value>Snape</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.addWithDupCheck</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><struct><member><name>Email</name><value><string>[email protected]</string></value></member><member><name>FirstName</name><value><string>Severus</string></value></member><member><name>LastName</name><value><string>Snape</string></value></member><member><name>Company</name><value><string>Test Company</string></value></member></struct></value></param><param><value><string>EmailAndName</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '621'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 19:15:07 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Fri, 10 Apr 2015 07:15:06 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3606</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '328'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 19:15:07 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '199'
+ Date:
+ - Fri, 10 Apr 2015 07:15:07 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Company</name><value>Test
+ Company</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 07:15:07 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_load.yml b/test/vcr_cassettes/contact_load.yml
new file mode 100644
index 0000000..d029991
--- /dev/null
+++ b/test/vcr_cassettes/contact_load.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>FirstName</string></value><value><string>LastName</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '370'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 20:24:44 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '254'
+ Date:
+ - Fri, 10 Apr 2015 08:24:44 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>FirstName</name><value>Severus</value></member><member><name>LastName</name><value>Snape</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 08:24:44 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_merge.yml b/test/vcr_cassettes/contact_merge.yml
new file mode 100644
index 0000000..2006533
--- /dev/null
+++ b/test/vcr_cassettes/contact_merge.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.merge</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3602</i4></value></param><param><value><i4>3604</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '275'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Thu, 09 Apr 2015 19:22:17 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Thu, 09 Apr 2015 07:22:16 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Thu, 09 Apr 2015 07:22:17 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/contact_update.yml b/test/vcr_cassettes/contact_update.yml
new file mode 100644
index 0000000..5e439f8
--- /dev/null
+++ b/test/vcr_cassettes/contact_update.yml
@@ -0,0 +1,95 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.update</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '357'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 20:18:59 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Fri, 10 Apr 2015 08:18:59 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3606</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 08:18:59 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>3606</i4></value></param><param><value><array><data><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '328'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 20:19:00 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '195'
+ Date:
+ - Fri, 10 Apr 2015 08:18:59 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Company</name><value>Hogwarts</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 08:19:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add.yml b/test/vcr_cassettes/data_add.yml
new file mode 100644
index 0000000..cd066e2
--- /dev/null
+++ b/test/vcr_cassettes/data_add.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.add</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member><member><name>Phone1</name><value><string>123-456-7899</string></value></member><member><name>Website</name><value><string>http://hogwarts-usa.com</string></value></member><member><name>StreetAddress1</name><value><string>123 Wizard Ave.</string></value></member><member><name>City</name><value><string>Redmond</string></value></member><member><name>State</name><value><string>WA</string></value></member><member><name>PostalCode</name><value><string>98052</string></value></member><member><name>Country</name><value><string>United States</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '937'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:34:01 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Sat, 11 Apr 2015 17:34:00 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3620</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:34:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add.yml.orig b/test/vcr_cassettes/data_add.yml.orig
new file mode 100644
index 0000000..cd066e2
--- /dev/null
+++ b/test/vcr_cassettes/data_add.yml.orig
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.add</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member><member><name>Phone1</name><value><string>123-456-7899</string></value></member><member><name>Website</name><value><string>http://hogwarts-usa.com</string></value></member><member><name>StreetAddress1</name><value><string>123 Wizard Ave.</string></value></member><member><name>City</name><value><string>Redmond</string></value></member><member><name>State</name><value><string>WA</string></value></member><member><name>PostalCode</name><value><string>98052</string></value></member><member><name>Country</name><value><string>United States</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '937'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:34:01 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Sat, 11 Apr 2015 17:34:00 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3620</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:34:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add_custom_field.yml b/test/vcr_cassettes/data_add_custom_field.yml
new file mode 100644
index 0000000..4af76cb
--- /dev/null
+++ b/test/vcr_cassettes/data_add_custom_field.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.addCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><string>Awesomeness Level</string></value></param><param><value><string>Text</string></value></param><param><value><i4>4</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '404'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:09:25 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '129'
+ Date:
+ - Sat, 11 Apr 2015 23:09:25 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>16</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:09:25 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_add_custom_field.yml.orig b/test/vcr_cassettes/data_add_custom_field.yml.orig
new file mode 100644
index 0000000..4af76cb
--- /dev/null
+++ b/test/vcr_cassettes/data_add_custom_field.yml.orig
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.addCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><string>Awesomeness Level</string></value></param><param><value><string>Text</string></value></param><param><value><i4>4</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '404'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:09:25 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '129'
+ Date:
+ - Sat, 11 Apr 2015 23:09:25 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>16</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:09:25 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_failure.yml b/test/vcr_cassettes/data_auth_user_failure.yml
new file mode 100644
index 0000000..0d78a29
--- /dev/null
+++ b/test/vcr_cassettes/data_auth_user_failure.yml
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>bad_pass</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '312'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:46:13 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '292'
+ Date:
+ - Sat, 11 Apr 2015 17:46:13 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: '<?xml version="1.0" encoding="utf-8"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><i4>13</i4></value></member><member><name>faultString</name><value>[FailedLoginAttempt]username
+ not found: [email protected]</value></member></struct></value></fault></methodResponse>'
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:46:13 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_failure.yml.orig b/test/vcr_cassettes/data_auth_user_failure.yml.orig
new file mode 100644
index 0000000..0d78a29
--- /dev/null
+++ b/test/vcr_cassettes/data_auth_user_failure.yml.orig
@@ -0,0 +1,50 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>bad_pass</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '312'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:46:13 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '292'
+ Date:
+ - Sat, 11 Apr 2015 17:46:13 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: '<?xml version="1.0" encoding="utf-8"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><i4>13</i4></value></member><member><name>faultString</name><value>[FailedLoginAttempt]username
+ not found: [email protected]</value></member></struct></value></fault></methodResponse>'
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:46:13 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_success.yml b/test/vcr_cassettes/data_auth_user_success.yml
new file mode 100644
index 0000000..d91a697
--- /dev/null
+++ b/test/vcr_cassettes/data_auth_user_success.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>4ac7729fa5d0c8b58a90b6ee97ab8bea</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '342'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:54:14 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '128'
+ Date:
+ - Sat, 11 Apr 2015 17:54:13 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>4</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:54:14 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_auth_user_success.yml.orig b/test/vcr_cassettes/data_auth_user_success.yml.orig
new file mode 100644
index 0000000..d91a697
--- /dev/null
+++ b/test/vcr_cassettes/data_auth_user_success.yml.orig
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.authenticateUser</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><string>4ac7729fa5d0c8b58a90b6ee97ab8bea</string></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '342'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:54:14 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '128'
+ Date:
+ - Sat, 11 Apr 2015 17:54:13 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>4</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:54:14 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_delete.yml b/test/vcr_cassettes/data_delete.yml
new file mode 100644
index 0000000..91c3ae1
--- /dev/null
+++ b/test/vcr_cassettes/data_delete.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.delete</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '284'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:14:53 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sat, 11 Apr 2015 23:14:52 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:14:53 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_delete.yml.orig b/test/vcr_cassettes/data_delete.yml.orig
new file mode 100644
index 0000000..91c3ae1
--- /dev/null
+++ b/test/vcr_cassettes/data_delete.yml.orig
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.delete</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '284'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:14:53 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sat, 11 Apr 2015 23:14:52 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:14:53 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_find_by_field.yml b/test/vcr_cassettes/data_find_by_field.yml
new file mode 100644
index 0000000..b3c0208
--- /dev/null
+++ b/test/vcr_cassettes/data_find_by_field.yml
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.findByField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><string>Company</string></value></param><param><value><string>Hogwarts of America</string></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '577'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:37:52 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:37:52 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:37:52 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_find_by_field.yml.orig b/test/vcr_cassettes/data_find_by_field.yml.orig
new file mode 100644
index 0000000..b3c0208
--- /dev/null
+++ b/test/vcr_cassettes/data_find_by_field.yml.orig
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.findByField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><string>Company</string></value></param><param><value><string>Hogwarts of America</string></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '577'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:37:52 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:37:52 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:37:52 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_load.yml b/test/vcr_cassettes/data_load.yml
new file mode 100644
index 0000000..f94b4a4
--- /dev/null
+++ b/test/vcr_cassettes/data_load.yml
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Company</string></value><value><string>StreetAddress1</string></value><value><string>City</string></value><value><string>State</string></value><value><string>PostalCode</string></value><value><string>Country</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '579'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:34:01 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '513'
+ Date:
+ - Sat, 11 Apr 2015 17:34:01 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>PostalCode</name><value>98052</value></member><member><name>State</name><value>WA</value></member><member><name>Country</name><value>United
+ States</value></member><member><name>Company</name><value>Hogwarts of America</value></member><member><name>StreetAddress1</name><value>123
+ Wizard Ave.</value></member><member><name>City</name><value>Redmond</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:34:01 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_load.yml.orig b/test/vcr_cassettes/data_load.yml.orig
new file mode 100644
index 0000000..f94b4a4
--- /dev/null
+++ b/test/vcr_cassettes/data_load.yml.orig
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Company</string></value><value><string>StreetAddress1</string></value><value><string>City</string></value><value><string>State</string></value><value><string>PostalCode</string></value><value><string>Country</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '579'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 05:34:01 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '513'
+ Date:
+ - Sat, 11 Apr 2015 17:34:01 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>PostalCode</name><value>98052</value></member><member><name>State</name><value>WA</value></member><member><name>Country</name><value>United
+ States</value></member><member><name>Company</name><value>Hogwarts of America</value></member><member><name>StreetAddress1</name><value>123
+ Wizard Ave.</value></member><member><name>City</name><value>Redmond</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 17:34:01 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query.yml b/test/vcr_cassettes/data_query.yml
new file mode 100644
index 0000000..97bc37b
--- /dev/null
+++ b/test/vcr_cassettes/data_query.yml
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '586'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:40:04 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:40:03 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:40:04 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query.yml.orig b/test/vcr_cassettes/data_query.yml.orig
new file mode 100644
index 0000000..97bc37b
--- /dev/null
+++ b/test/vcr_cassettes/data_query.yml.orig
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '586'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:40:04 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:40:03 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:40:04 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query_order_by.yml b/test/vcr_cassettes/data_query_order_by.yml
new file mode 100644
index 0000000..101e6f4
--- /dev/null
+++ b/test/vcr_cassettes/data_query_order_by.yml
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param><param><value><string>Id</string></value></param><param><value><boolean>0</boolean></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '685'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:42:00 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:41:59 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:42:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_query_order_by.yml.orig b/test/vcr_cassettes/data_query_order_by.yml.orig
new file mode 100644
index 0000000..101e6f4
--- /dev/null
+++ b/test/vcr_cassettes/data_query_order_by.yml.orig
@@ -0,0 +1,51 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.query</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>5</i4></value></param><param><value><i4>0</i4></value></param><param><value><struct><member><name>Company</name><value><string>Hogwarts of America</string></value></member></struct></value></param><param><value><array><data><value><string>Id</string></value><value><string>Company</string></value></data></array></value></param><param><value><string>Id</string></value></param><param><value><boolean>0</boolean></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '685'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:42:00 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '472'
+ Date:
+ - Sat, 11 Apr 2015 22:41:59 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3620</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value><value><struct><member><name>Id</name><value><i4>3618</i4></value></member><member><name>Company</name><value>Hogwarts
+ of America</value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:42:00 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_update.yml b/test/vcr_cassettes/data_update.yml
new file mode 100644
index 0000000..7e0abc5
--- /dev/null
+++ b/test/vcr_cassettes/data_update.yml
@@ -0,0 +1,96 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.update</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><struct><member><name>Phone1</name><value><string>987-654-3211</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '411'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:13:28 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Sat, 11 Apr 2015 22:13:28 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3618</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:13:28 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Phone1</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '378'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:13:29 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '200'
+ Date:
+ - Sat, 11 Apr 2015 22:13:28 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Phone1</name><value>(987)
+ 654-3211</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:13:29 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_update.yml.orig b/test/vcr_cassettes/data_update.yml.orig
new file mode 100644
index 0000000..7e0abc5
--- /dev/null
+++ b/test/vcr_cassettes/data_update.yml.orig
@@ -0,0 +1,96 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.update</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><struct><member><name>Phone1</name><value><string>987-654-3211</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '411'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:13:28 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '131'
+ Date:
+ - Sat, 11 Apr 2015 22:13:28 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><i4>3618</i4></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:13:28 GMT
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.load</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>Company</string></value></param><param><value><i4>3618</i4></value></param><param><value><array><data><value><string>Phone1</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '378'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 10:13:29 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '200'
+ Date:
+ - Sat, 11 Apr 2015 22:13:28 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><struct><member><name>Phone1</name><value>(987)
+ 654-3211</value></member></struct></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 22:13:29 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_update_custom_field.yml b/test/vcr_cassettes/data_update_custom_field.yml
new file mode 100644
index 0000000..67201bf
--- /dev/null
+++ b/test/vcr_cassettes/data_update_custom_field.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.updateCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>16</i4></value></param><param><value><struct><member><name>Label</name><value><string>Stuff</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '358'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:12:51 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sat, 11 Apr 2015 23:12:51 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:12:51 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/data_update_custom_field.yml.orig b/test/vcr_cassettes/data_update_custom_field.yml.orig
new file mode 100644
index 0000000..67201bf
--- /dev/null
+++ b/test/vcr_cassettes/data_update_custom_field.yml.orig
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>DataService.updateCustomField</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><i4>16</i4></value></param><param><value><struct><member><name>Label</name><value><string>Stuff</string></value></member></struct></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '358'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Sun, 12 Apr 2015 11:12:51 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '138'
+ Date:
+ - Sat, 11 Apr 2015 23:12:51 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><boolean>1</boolean></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Sat, 11 Apr 2015 23:12:51 GMT
+recorded_with: VCR 2.9.3
diff --git a/test/vcr_cassettes/find_by_email.yml b/test/vcr_cassettes/find_by_email.yml
new file mode 100644
index 0000000..9cf6c7f
--- /dev/null
+++ b/test/vcr_cassettes/find_by_email.yml
@@ -0,0 +1,49 @@
+---
+http_interactions:
+- request:
+ method: post
+ uri: https://test.infusionsoft.com/api/xmlrpc
+ body:
+ encoding: UTF-8
+ string: |
+ <?xml version="1.0" ?><methodCall><methodName>ContactService.findByEmail</methodName><params><param><value><string>not_a_real_key</string></value></param><param><value><string>[email protected]</string></value></param><param><value><array><data><value><string>Id</string></value></data></array></value></param></params></methodCall>
+ headers:
+ User-Agent:
+ - Infusionsoft-1.1.8 (RubyGem)
+ Content-Type:
+ - text/xml; charset=utf-8
+ Content-Length:
+ - '349'
+ Connection:
+ - keep-alive
+ Accept-Encoding:
+ - gzip;q=1.0,deflate;q=0.6,identity;q=0.3
+ Accept:
+ - "*/*"
+ response:
+ status:
+ code: 200
+ message: OK
+ headers:
+ Server:
+ - Apache-Coyote/1.1
+ Pragma:
+ - no-cache
+ Cache-Control:
+ - no-cache, no-store
+ Expires:
+ - Fri, 10 Apr 2015 20:18:59 GMT
+ Content-Type:
+ - text/xml;charset=UTF-8
+ Content-Length:
+ - '330'
+ Date:
+ - Fri, 10 Apr 2015 08:18:59 GMT
+ Set-Cookie:
+ - app-lb=2466578442.20480.0000; path=/
+ body:
+ encoding: UTF-8
+ string: <?xml version="1.0" encoding="utf-8"?><methodResponse><params><param><value><array><data><value><struct><member><name>Id</name><value><i4>3606</i4></value></member></struct></value><value><struct><member><name>Id</name><value><i4>3610</i4></value></member></struct></value></data></array></value></param></params></methodResponse>
+ http_version:
+ recorded_at: Fri, 10 Apr 2015 08:18:59 GMT
+recorded_with: VCR 2.9.3
|
nateleavitt/infusionsoft
|
fc9a3d3c0164f1739767d4abdb06b5cda4f23c11
|
adding missing key in documentation for charge_invoice
|
diff --git a/lib/infusionsoft/client/invoice.rb b/lib/infusionsoft/client/invoice.rb
index 1b5aebf..fbfaa86 100644
--- a/lib/infusionsoft/client/invoice.rb
+++ b/lib/infusionsoft/client/invoice.rb
@@ -1,254 +1,254 @@
module Infusionsoft
class Client
# The Invoice service allows you to manage eCommerce transactions.
module Invoice
# Creates a blank order with no items.
#
# @param [Integer] contact_id
# @param [String] description the name this order will display
# @param [Date] order_date
# @param [Integer] lead_affiliate_id 0 should be used if none
# @param [Integer] sale_affiliate_id 0 should be used if none
# @return [Integer] returns the invoice id
def invoice_create_blank_order(contact_id, description, order_date, lead_affiliate_id,
sale_affiliate_id)
response = get('InvoiceService.createBlankOrder', contact_id, description, order_date,
lead_affiliate_id, sale_affiliate_id)
end
# Adds a line item to an order. This used to add a Product to an order as well as
# any other sort of charge/discount.
#
# @param [Integer] invoice_id
# @param [Integer] product_id
# @param [Integer] type UNKNOWN = 0, SHIPPING = 1, TAX = 2, SERVICE = 3, PRODUCT = 4,
# UPSELL = 5, FINANCECHARGE = 6, SPECIAL = 7
# @param [Float] price
# @param [Integer] quantity
# @param [String] description a full description of the line item
# @param [String] notes
# @return [Boolean] returns true/false if it was added successfully or not
def invoice_add_order_item(invoice_id, product_id, type, price, quantity, description, notes)
response = get('InvoiceService.addOrderItem', invoice_id, product_id, type, price,
quantity, description, notes)
end
# This will cause a credit card to be charged for the amount currently due on an invoice.
#
# @param [Integer] invoice_id
# @param [String] notes a note about the payment
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Boolean] bypass_commission
- # @return [Hash] containing the following keys {'Successful => [Boolean],
+ # @return [Hash] containing the following keys {'Successful' => [Boolean],
# 'Code' => [String], 'RefNum' => [String], 'Message' => [String]}
def invoice_charge_invoice(invoice_id, notes, credit_card_id, merchant_account_id,
bypass_commissions)
response = get('InvoiceService.chargeInvoice', invoice_id, notes, credit_card_id,
merchant_account_id, bypass_commissions)
end
# Deletes the specified subscription from the database, as well as all invoices
# tied to the subscription.
#
# @param [Integer] cprogram_id the id of the subscription being deleted
# @return [Boolean]
def invoice_delete_subscription(cprogram_id)
response = get('InvoiceService.deleteSubscription', cprogram_id)
end
# Creates a subscription for a contact. Subscriptions are billing automatically
# by infusionsoft within the next six hours. If you want to bill immediately you
# will need to utilize the create_invoice_for_recurring and then
# charge_invoice method to accomplish this.
#
# @param [Integer] contact_id
# @param [Boolean] allow_duplicate
# @param [Integer] cprogram_id the subscription id
# @param [Integer] merchant_account_id
# @param [Integer] credit_card_id
# @param [Integer] affiliate_id
# @param [Integer] days_till_charge number of days you want to wait till it's charged
def invoice_add_recurring_order(contact_id, allow_duplicate, cprogram_id,
merchant_account_id, credit_card_id, affiliate_id,
days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id,
allow_duplicate, cprogram_id, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# This modifies the commissions being earned on a particular subscription.
# This does not affect previously generated invoices for this subscription.
#
# @param [Integer] recurring_order_id
# @param [Integer] affiliate_id
# @param [Float] amount
# @param [Integer] paryout_type how commissions will be earned (possible options are
# 4 - up front earning, 5 - upon customer payment) typically this is 5
# @return [Boolean]
def invoice_add_recurring_commission_override(recurring_order_id, affiliate_id,
amount, payout_type, description)
response = get('InvoiceService.addRecurringCommissionOverride', recurring_order_id,
affiliate_id, amount, payout_type, description)
end
# Adds a payment to an invoice without actually processing a charge through a merchant.
#
# @param [Integer] invoice_id
# @param [Float] amount
# @param [Date] date
# @param [String] type Cash, Check, Credit Card, Money Order, PayPal, etc.
# @param [String] description an area useful for noting payment details such as check number
# @param [Boolean] bypass_commissions
# @return [Boolean]
def invoice_add_manual_payment(invoice_id, amount, date, type, description, bypass_commissions)
response = get('InvoiceService.addManualPayment', invoice_id, amount, date, type,
description, bypass_commissions)
end
# This will create an invoice for all charges due on a Subscription. If the
# subscription has three billing cycles that are due, it will create one
# invoice with all three items attached.
#
# @param [Integer] recurring_order_id
# @return [Integer] returns the id of the invoice that was created
def invoice_create_invoice_for_recurring(recurring_order_id)
response = get('InvoiceService.createInvoiceForRecurring', recurring_order_id)
end
# Adds a payment plan to an existing invoice.
#
# @param [Integer] invoice_id
# @param [Boolean]
# @param [Integer] credit_card_id
# @param [Integer] merchant_account_id
# @param [Integer] days_between_retry the number of days Infusionsoft should wait
# before re-attempting to charge a failed payment
# @param [Integer] max_retry the maximum number of charge attempts
# @param [Float] initial_payment_ammount the amount of the very first charge
# @param [Date] initial_payment_date
# @param [Date] plan_start_date
# @param [Integer] number_of_payments the number of payments in this payplan (does not include
# initial payment)
# @param [Integer] days_between_payments the number of days between each payment
# @return [Boolean]
def invoice_add_payment_plan(invoice_id, auto_charge, credit_card_id,
merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date,
number_of_payments, days_between_payments)
response = get('InvoiceService.addPaymentPlan', invoice_id, auto_charge,
credit_card_id, merchant_account_id, days_between_retry, max_retry,
initial_payment_amount, initial_payment_date, plan_start_date, number_of_payments,
days_between_payments)
end
# Calculates the amount owed for a given invoice.
#
# @param [Integer] invoice_id
# @return [Float]
def invoice_calculate_amount_owed(invoice_id)
response = get('InvoiceService.calculateAmountOwed', invoice_id)
end
# Retrieve all Payment Types currently setup under the Order Settings section of Infusionsoft.
#
# @return [Array]
def invoice_get_all_payment_otpions
response = get('InvoiceService.getAllPaymentOptions')
end
# Retrieves all payments for a given invoice.
#
# @param [Integer] invoice_id
# @return [Array<Hash>] returns an array of payments
def invoice_get_payments(invoice_id)
response = get('Invoice.getPayments', invoice_id)
end
# Locates an existing card in the system for a contact, using the last 4 digits.
#
# @param [Integer] contact_id
# @param [Integer] last_four
# @return [Integer] returns the id of the credit card
def invoice_locate_existing_card(contact_id, last_four)
response = get('InvoiceService.locateExistingCard', contact_id, last_four)
end
# Calculates tax, and places it onto the given invoice.
#
# @param [Integer] invoice_id
# @return [Boolean]
def invoice_recalculate_tax(invoice_id)
response = get('InvoiceService.recalculateTax', invoice_id)
end
# This will validate a credit card in the system.
#
# @param [Integer] credit_card_id if the card is already in the system
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(credit_card_id)
response = get('InvoiceService.validateCreditCard', credit_card_id)
end
# This will validate a credit card by passing in values of the
# card directly (this card doesn't have to be added to the system).
#
# @param [Hash] data
# @return [Hash] returns a hash { 'Valid' => false, 'Message' => 'Card is expired' }
def invoice_validate_card(data)
response = get('InvoiceService.validateCreditCard', data)
end
# Retrieves the shipping options currently setup for the Infusionsoft shopping cart.
#
# @return [Array]
def invoice_get_all_shipping_options
response = get('Invoice.getAllShippingOptions')
end
# Changes the next bill date on a subscription.
#
# @param [Integer] job_recurring_id this is the subscription id on the contact
# @param [Date] next_bill_date
# @return [Boolean]
def invoice_update_recurring_next_bill_date(job_recurring_id, next_bill_date)
response = get('InvoiceService.updateJobRecurringNextBillDate', job_recurring_id, next_bill_date)
end
# Adds a commission override to a one time order, using a combination of percentage
# and hard-coded amounts.
#
# @param [Integer] invoice_id
# @param [Integer] affiliate_id
# @param [Integer] product_id
# @param [Integer] percentage
# @param [Float] amount
# @param [Integer] payout_type how commision should be earned (4 - up front in full, 5 - upon
# customer payment
# @param [String] description a note about this commission
# @param [Date] date the commission was generated, not necessarily earned
# @return [Boolean]
def invoice_add_order_commission_override(invoice_id, affiliate_id, product_id, percentage,
amount, payout_type, description, date)
response = get('InvoiceService.addOrderCommissionOverride', invoice_id, affiliate_id,
product_id, percentage, amount, payout_type, description, date)
end
# Deprecated - Adds a recurring order to the database.
def invoice_add_recurring_order_with_price(contact_id, allow_duplicate, cprogram_id, qty,
price, allow_tax, merchant_account_id,
credit_card_id, affiliate_id, days_till_charge)
response = get('InvoiceService.addRecurringOrder', contact_id, allow_duplicate,
cprogram_id, qty, price, allow_tax, merchant_account_id, credit_card_id,
affiliate_id, days_till_charge)
end
# Deprecated - returns the invoice id from a one time order.
def invoice_get_invoice_id(order_id)
response = get('InvoiceService.getinvoice_id', order_id)
end
end
end
end
|
nateleavitt/infusionsoft
|
36477fe9392cfa7d3b306b63445a2c8b6051f38e
|
Fix APIEmailService.sendTemplate
|
diff --git a/lib/infusionsoft/client/email.rb b/lib/infusionsoft/client/email.rb
index 15f9102..7f62fda 100644
--- a/lib/infusionsoft/client/email.rb
+++ b/lib/infusionsoft/client/email.rb
@@ -1,152 +1,152 @@
module Infusionsoft
class Client
# The Email service allows you to email your contacts as well as attaching emails sent
# elsewhere (this lets you send email from multiple services and still see all communications
# inside of Infusionsoft).
module Email
# Create a new email template that can be used for future emails
#
# @param [String] title
# @param [String] categories a comma separated list of the categories
# you want this template in Infusionsoft
# @param [String] from the from address format use is 'FirstName LastName <[email protected]>'
# @param [String] to the email address this template is sent to
# @param [String] cc a comma separated list of cc email addresses
# @param [String] bcc a comma separated list of bcc email addresses
# @param [String] subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
def email_add(title, categories, from, to, cc, bcc, subject, text_body, html_body,
content_type, merge_context)
response = get('APIEmailService.addEmailTemplate', title, categories, from, to,
cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
# This will create an item in the email history for a contact. This does not actually
# send the email, it only places an item into the email history. Using the API to
# instruct Infusionsoft to send an email will handle this automatically.
#
# @param [Integer] contact_id
# @param [String] from_name the name portion of the from address, not the email
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_addresses
# @param [String] bcc_addresses
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @param [String] header the header info for this email (will be listed in history)
# @param [Date] receive_date
# @param [Date] sent_date
def email_attach(contact_id, from_name, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, txt_body,
header, receive_date, send_date)
response = get('APIEmailService.attachEmail', contact_id, from_name, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, txt_body, header, receive_date, send_date)
end
# This retrieves all possible merge fields for the context provided.
#
# @param [String] merge_context could include Contact, ServiceCall, Opportunity, or CreditCard
# @return [Array] returns the merge fields for the given context
def email_get_available_merge_fields(merge_context)
response = get('APIEmailService.getAvailableMergeFields', merge_context)
end
# Retrieves the details for a particular email template.
#
# @param [Integer] id
# @return [Hash] all data for the email template
def email_get_template(id)
response = get('APIEmailService.getEmailTemplate', id)
end
# Retrieves the status of the given email address.
#
# @param [String] email_address
# @return [Integer] 0 = opted out, 1 = single opt-in, 2 = double opt-in
def email_get_opt_status(email_address)
response = get('APIEmailService.getOptStatus', email_address)
end
# This method opts-in an email address. This method only works the first time
# an email address opts-in.
#
# @param [String] email_address
# @param [String] reason
# This is how you can note why/how this email was opted-in. If a blank
# reason is passed the system will default a reason of "API Opt In"
# @return [Boolean]
def email_optin(email_address, reason)
response = get('APIEmailService.optIn', email_address, reason)
end
# Opts-out an email address. Note that once an address is opt-out,
# the API cannot opt it back in.
#
# @param [String] email_address
# @param [String] reason
# @return [Boolean]
def email_optout(email_address, reason)
response = get('APIEmailService.optOut', email_address, reason)
end
# This will send an email to a list of contacts, as well as record the email
# in the contacts' email history.
#
# @param [Array<Integer>] contact_list list of contact ids you want to send this email to
# @param [String] from_address
# @param [String] to_address
# @param [String] cc_address
# @param [String] bcc_address
# @param [String] content_type this must be one of the following Text, HTML, or Multipart
# @param [String] subject
# @param [String] html_body
# @param [String] text_body
# @return [Boolean] returns true/false if the email has been sent
def email_send(contact_list, from_address, to_address, cc_addresses,
bcc_addresses, content_type, subject, html_body, text_body)
response = get('APIEmailService.sendEmail', contact_list, from_address,
to_address, cc_addresses, bcc_addresses, content_type, subject,
html_body, text_body)
end
# This will send an email to a list of contacts, as well as record the email in the
# contacts' email history.
#
# @param [Array<Integer>] contact_list is an array of Contact id numbers you would like to send this email to
# @param [String] The Id of the template to send
# @return returns true if the email has been sent, an error will be sent back otherwise.
def email_send_template(contact_list, template_id)
- response = get('APIEmailService.sendTemplate', contact_list, template_id)
+ response = get('APIEmailService.sendEmail', contact_list, template_id)
end
# This method is used to update an already existing email template.
#
# @param [Integer] id
# @param [String] title
# @param [String] category
# @param [String] from
# @param [String] to
# @param [String] cc
# @param [String] bcc
# @param [String subject
# @param [String] text_body
# @param [String] html_body
# @param [String] content_type can be Text, HTML, Multipart
# @param [String] merge_context can be Contact, ServiceCall, Opportunity, CreditCard
# @return [Boolean] returns true/false if teamplate was updated successfully
def email_update_template(id, title, category, from, to, cc, bcc, subject,
text_body, html_body, content_type, merge_context)
response = get('APIEmailService.updateEmailTemplate', id, title, category, from,
to, cc, bcc, subject, text_body, html_body, content_type, merge_context)
end
end
end
end
|
nateleavitt/infusionsoft
|
8e1a83e09819ad536f144d3c984cdb546853b31a
|
added funnel service - achieve goal
|
diff --git a/lib/infusionsoft/client.rb b/lib/infusionsoft/client.rb
index 153e9aa..111ffeb 100644
--- a/lib/infusionsoft/client.rb
+++ b/lib/infusionsoft/client.rb
@@ -1,29 +1,31 @@
module Infusionsoft
# Wrapper for the Infusionsoft API
#
# @note all services have been separated into different modules
class Client < Api
# Require client method modules after initializing the Client class in
# order to avoid a superclass mismatch error, allowing those modules to be
# Client-namespaced.
require 'infusionsoft/client/contact'
require 'infusionsoft/client/email'
require 'infusionsoft/client/invoice'
require 'infusionsoft/client/data'
require 'infusionsoft/client/affiliate'
require 'infusionsoft/client/file'
require 'infusionsoft/client/ticket' # Deprecated by Infusionsoft
require 'infusionsoft/client/search'
require 'infusionsoft/client/credit_card'
+ require 'infusionsoft/client/funnel'
include Infusionsoft::Client::Contact
include Infusionsoft::Client::Email
include Infusionsoft::Client::Invoice
include Infusionsoft::Client::Data
include Infusionsoft::Client::Affiliate
include Infusionsoft::Client::File
include Infusionsoft::Client::Ticket # Deprecated by Infusionsoft
include Infusionsoft::Client::Search
include Infusionsoft::Client::CreditCard
+ include Infusionsoft::Client::Funnel
end
end
diff --git a/lib/infusionsoft/client/funnel.rb b/lib/infusionsoft/client/funnel.rb
new file mode 100644
index 0000000..ab46276
--- /dev/null
+++ b/lib/infusionsoft/client/funnel.rb
@@ -0,0 +1,18 @@
+module Infusionsoft
+ class Client
+ # Funnel Service is used to add contacts to your sequences
+ module Funnel
+
+ # Achieves a goal, Returns the result of a goal being achieved.
+ #
+ # @param integration, string, The integration name of the goal. This defaults to the name of the app.
+ # @param call_name, string, The call name of the goal
+ # @param cid, int, The id of the contact you want to add to a sequence.
+ #
+ def funnel_achieve_goal(integration, call_name, cid)
+ response = get('FunnelService.achieveGoal', integration, call_name, cid)
+ end
+
+ end
+ end
+end
\ No newline at end of file
|
nateleavitt/infusionsoft
|
e84734d380ffff3bba1d1c37393481a4a967a2f6
|
udated readme with latest update notes
|
diff --git a/README.md b/README.md
index b99b815..751cfba 100644
--- a/README.md
+++ b/README.md
@@ -1,117 +1,104 @@
# The Infusionsoft Ruby Gem
A Ruby wrapper for the Infusionsoft API
**update notes**
+* v1.1.8 - Added a default user-agent in the headers. Also, give the
+ ability to set your own user-agent in the config block.
* v1.1.5 - Added a custom logger option. This will allow you to track all api calls/results in a separate log file. Defaults to $stdout if none is specified. To add logger specify `api_logger` in your [config block](#setup--configuration).
## <a name="installation">Installation</a>
gem install infusionsoft
## <a name="documentation">Documentation</a>
[http://rubydoc.info/gems/infusionsoft/frames](http://rubydoc.info/gems/infusionsoft/frames)
## <a name="setup">Setup & Configuration</a>
1. **Rails 2.3** - add `config.gem 'infusionsoft'` **Rails 3** - add `'infusionsoft'` to your `Gemfile`
2. Then create an initializer in `config\initializers` called infusionsoft.rb and the following
<b></b>
# Added to your config\initializers file
Infusionsoft.configure do |config|
config.api_url = 'YOUR_INFUSIONSOFT_URL' # example infused.infusionsoft.com
config.api_key = 'YOUR_INFUSIONSOFT_API_KEY'
config.api_logger = Logger.new("#{Rails.root}/log/infusionsoft_api.log") # optional logger file
end
## <a name="examples">Usage Examples</a>
# Get a users first and last name using the DataService
Infusionsoft.data_load('Contact', contact_id, [:FirstName, :LastName])
# Get a list of custom fields
Infusionsoft.data_find_by_field('DataFormField', 100, 0, 'FormId', -1, ['Name'])
# Note, when updating custom fields they are case sensisitve and need to be prefaced with a '_'
# Update a contact with specific field values
Infusionsoft.contact_update(contact_id, { :FirstName => 'first_name', :Email => '[email protected]' })
# Add a new Contact
Infusionsoft.contact_add({:FirstName => 'first_name', :LastName => 'last_name', :Email => '[email protected]'})
# Create a blank Invoice
invoice_id = Infusionsoft.invoice_create_blank_order(contact_id, description, Date.today, lead_affiliate_id, sale_affiliate_id)
# Then add item to invoice
Infusionsoft.invoice_add_order_item(invoice_id, product_id, product_type, amount, quantity, description_here, notes)
# Then charge the invoice
Infusionsoft.invoice_charge_invoice(invoice_id, notes, credit_card_id, merchange_id, bypass_commissions)
## <a name="contributing">Contributing</a>
In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.
Here are some ways *you* can contribute:
* by using alpha, beta, and prerelease versions
* by reporting bugs
* by suggesting new features
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up inconsistent whitespace)
* by refactoring code
* by closing [issues](https://github.com/nateleavitt/infusionsoft/issues)
* by reviewing patches
## <a name="issues">Submitting an Issue</a>
We use the [GitHub issue tracker](https://github.com/nateleavitt/infusionsoft/issues) to track bugs and
-features. Before submitting a bug report or feature request, check to make sure it hasn't already
-been submitted. You can indicate support for an existing issuse by voting it up. When submitting a
-bug report, please include a [Gist](https://gist.github.com/) that includes a stack trace and any
-details that may be necessary to reproduce the bug, including your gem version, Ruby version, and
-operating system. Ideally, a bug report should include a pull request with failing specs.
-
-## <a name="pulls">Submitting a Pull Request</a>
-1. Fork the project.
-2. Create a topic branch.
-3. Implement your feature or bug fix.
-4. Add documentation for your feature or bug fix.
-5. Run <tt>bundle exec rake doc:yard</tt>. If your changes are not 100% documented, go back to step 4.
-6. Add specs for your feature or bug fix.
-7. Run <tt>bundle exec rake spec</tt>. If your changes are not 100% covered, go back to step 6.
-8. Commit and push your changes.
-9. Submit a pull request. Please do not include changes to the gemspec, version, or history file. (If you want to create your own version for some reason, please do so in a separate commit.)
+features.
## <a name="rubies">Supported Rubies</a>
This library aims to support the following Ruby implementations:
* Ruby = 1.8.7
* Ruby >= 1.9
* [JRuby](http://www.jruby.org/)
* [Rubinius](http://rubini.us/)
* [Ruby Enterprise Edition](http://www.rubyenterpriseedition.com/)
If something doesn't work on one of these interpreters, it should be considered
a bug.
This library may inadvertently work (or seem to work) on other Ruby
implementations, however support will only be provided for the versions listed
above.
If you would like this library to support another Ruby version, you may
volunteer to be a maintainer. Being a maintainer entails making sure all tests
run and pass on that implementation. When something breaks on your
implementation, you will be personally responsible for providing patches in a
timely fashion. If critical issues for a particular implementation exist at the
time of a major release, support for that Ruby version may be dropped.
## <a name="todos">Todos</a>
* Need to fully implement testing
* Need to add a history log for additional contributers
## <a name="copyright">Copyright</a>
-Copyright (c) 2013 Nathan Leavitt
+Copyright (c) 2014 Nathan Leavitt
See [LICENSE](https://github.com/nateleavitt/infusionsoft/blob/master/LICENSE.md) for details.
|
nateleavitt/infusionsoft
|
0d1cf93f90a8eb06e90c583568c6c0426455713d
|
Fix method call
|
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index ff75028..5590e92 100644
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,43 +1,43 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
client = XMLRPC::Client.new3({
'host' => api_url,
'path' => "/api/xmlrpc",
'port' => 443,
'use_ssl' => true
})
- client.http_extra_header('User-Agent' => user_agent)
+ client.http_header_extra = {'User-Agent' => user_agent}
begin
api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
9dd4cdd55fe2352b46bdf177ff10b97f4baafbbc
|
Set default user-agent
|
diff --git a/lib/infusionsoft/configuration.rb b/lib/infusionsoft/configuration.rb
index b9df6ef..e1cdb43 100644
--- a/lib/infusionsoft/configuration.rb
+++ b/lib/infusionsoft/configuration.rb
@@ -1,42 +1,48 @@
+require 'infusionsoft/version'
+
module Infusionsoft
module Configuration
# The list of available options
VALID_OPTION_KEYS = [
:api_url,
:api_key,
:api_logger,
:user_agent # allows you to change the User-Agent of the request headers
].freeze
# @private
attr_accessor *VALID_OPTION_KEYS
# When this module is extended, set all configuration options to their default values
#def self.extended(base)
#base.reset
#end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
options = {}
VALID_OPTION_KEYS.each{|k| options[k] = send(k)}
options
end
#def reset
#self.url = ''
#self.api_key = 'na'
#end
+ def user_agent
+ @user_agent ||= "Infusionsoft-#{VERSION} (RubyGem)"
+ end
+
def api_logger
@api_logger || Infusionsoft::APILogger.new
end
end
end
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index 2a0c27a..ff75028 100644
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,43 +1,43 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
client = XMLRPC::Client.new3({
'host' => api_url,
'path' => "/api/xmlrpc",
'port' => 443,
'use_ssl' => true
})
- client.http_extra_header('User-Agent' => user_agent) if user_agent
+ client.http_extra_header('User-Agent' => user_agent)
begin
api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
e7dbabacf3386f259431e37cea17f8c6681787cf
|
added setting to enable specifying the user-agent header
|
diff --git a/lib/infusionsoft/configuration.rb b/lib/infusionsoft/configuration.rb
index a53f96a..b9df6ef 100644
--- a/lib/infusionsoft/configuration.rb
+++ b/lib/infusionsoft/configuration.rb
@@ -1,41 +1,42 @@
module Infusionsoft
module Configuration
# The list of available options
VALID_OPTION_KEYS = [
:api_url,
:api_key,
- :api_logger
+ :api_logger,
+ :user_agent # allows you to change the User-Agent of the request headers
].freeze
# @private
attr_accessor *VALID_OPTION_KEYS
# When this module is extended, set all configuration options to their default values
#def self.extended(base)
#base.reset
#end
# Convenience method to allow configuration options to be set in a block
def configure
yield self
end
# Create a hash of options and their values
def options
options = {}
VALID_OPTION_KEYS.each{|k| options[k] = send(k)}
options
end
#def reset
#self.url = ''
#self.api_key = 'na'
#end
def api_logger
@api_logger || Infusionsoft::APILogger.new
end
end
end
diff --git a/lib/infusionsoft/connection.rb b/lib/infusionsoft/connection.rb
index b75bf8b..2a0c27a 100644
--- a/lib/infusionsoft/connection.rb
+++ b/lib/infusionsoft/connection.rb
@@ -1,42 +1,43 @@
require "xmlrpc/client"
require 'infusionsoft/exception_handler'
module Infusionsoft
module Connection
private
def connection(service_call, *args)
- server = XMLRPC::Client.new3({
+ client = XMLRPC::Client.new3({
'host' => api_url,
'path' => "/api/xmlrpc",
'port' => 443,
'use_ssl' => true
})
+ client.http_extra_header('User-Agent' => user_agent) if user_agent
begin
api_logger.info "CALL: #{service_call} api_key:#{api_key} at:#{Time.now} args:#{args.inspect}"
- result = server.call("#{service_call}", api_key, *args)
+ result = client.call("#{service_call}", api_key, *args)
if result.nil?; ok_to_retry('nil response') end
rescue Timeout::Error => timeout
# Retry up to 5 times on a Timeout before raising it
ok_to_retry(timeout) ? retry : raise
rescue XMLRPC::FaultException => xmlrpc_error
# Catch all XMLRPC exceptions and rethrow specific exceptions for each type of xmlrpc fault code
Infusionsoft::ExceptionHandler.new(xmlrpc_error)
end # Purposefully not catching other exceptions so that they can be handled up the stack
api_logger.info "RESULT: #{result.inspect}"
return result
end
def ok_to_retry(e)
@retry_count += 1
if @retry_count <= 5
api_logger.warn "WARNING: [#{e}] retrying #{@retry_count}"
true
else
false
end
end
end
end
|
nateleavitt/infusionsoft
|
269abc5a9bf9ffe00f27572206f3c63ab873f130
|
v1.1.7
|
diff --git a/lib/infusionsoft/version.rb b/lib/infusionsoft/version.rb
index 98153aa..4208535 100644
--- a/lib/infusionsoft/version.rb
+++ b/lib/infusionsoft/version.rb
@@ -1,4 +1,4 @@
module Infusionsoft
# The version of the gem
- VERSION = '1.1.7b'.freeze unless defined?(::Infusionsoft::VERSION)
+ VERSION = '1.1.7'.freeze unless defined?(::Infusionsoft::VERSION)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.