text:
"""Worry-free YAML configuration files.
"""
from __future__ import (unicode_literals, absolute_import, print_function,
                        division)

import platform
import os
import pkgutil
import sys
import yaml
import types
import collections
import re
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

UNIX_DIR_VAR = 'XDG_CONFIG_HOME'
UNIX_DIR_FALLBACK = '~/.config'
WINDOWS_DIR_VAR = 'APPDATA'
WINDOWS_DIR_FALLBACK = '~\\AppData\\Roaming'
MAC_DIR = '~/Library/Application Support'

CONFIG_FILENAME = 'config.yaml'
DEFAULT_FILENAME = 'config_default.yaml'
ROOT_NAME = 'root'

YAML_TAB_PROBLEM = "found character '\\t' that cannot start any token"

REDACTED_TOMBSTONE = 'REDACTED'

# Utilities.

PY3 = sys.version_info[0] == 3
STRING = str if PY3 else unicode
BASESTRING = str if PY3 else basestring
NUMERIC_TYPES = (int, float) if PY3 else (int, float, long)
TYPE_TYPES = (type,) if PY3 else (type, types.ClassType)

def iter_first(sequence):
    """Get the first element from an iterable or raise a ValueError if
    the iterator generates no values.
    """
    it = iter(sequence)
    try:
        if PY3:
            return next(it)
        else:
            return it.next()
    except StopIteration:
        raise ValueError()

# Exceptions.

class ConfigError(Exception):
    """Base class for exceptions raised when querying a configuration.
    """

class NotFoundError(ConfigError):
    """A requested value could not be found in the configuration trees.
    """

class ConfigValueError(ConfigError):
    """The value in the configuration is illegal."""

class ConfigTypeError(ConfigValueError):
    """The value in the configuration did not match the expected type.
    """

class ConfigTemplateError(ConfigError):
    """Base class for exceptions raised because of an invalid template.
    """

class ConfigReadError(ConfigError):
    """A configuration file could not be read."""
    def __init__(self, filename, reason=None):
        self.filename = filename
        self.reason = reason

        message = 'file {0} could not be read'.format(filename)
        if isinstance(reason, yaml.scanner.ScannerError) and \
                reason.problem == YAML_TAB_PROBLEM:
            # Special-case error message for tab indentation in YAML markup.
            message += ': found tab character at line {0}, column {1}'.format(
                reason.problem_mark.line + 1,
                reason.problem_mark.column + 1,
            )
        elif reason:
            # Generic error message uses exception's message.
            message += ': {0}'.format(reason)

        super(ConfigReadError, self).__init__(message)

# Views and sources.

class ConfigSource(dict):
    """A dictionary augmented with metadata about the source of the
    configuration.
    """
    def __init__(self, value, filename=None, default=False):
        super(ConfigSource, self).__init__(value)
        if filename is not None and not isinstance(filename, BASESTRING):
            raise TypeError('filename must be a string or None')
        self.filename = filename
        self.default = default

    def __repr__(self):
        return 'ConfigSource({0}, {1}, {2})'.format(
            super(ConfigSource, self).__repr__(),
            repr(self.filename),
            repr(self.default)
        )

    @classmethod
    def of(self, value):
        """Given either a dictionary or a `ConfigSource` object, return
        a `ConfigSource` object. This lets a function accept either type
        of object as an argument.
        """
        if isinstance(value, ConfigSource):
            return value
        elif isinstance(value, dict):
            return ConfigSource(value)
        else:
            raise TypeError('source value must be a dict')

class ConfigView(object):
    """A configuration "view" is a query into a program's configuration
    data. A view represents a hypothetical location in the configuration
    tree; to extract the data from the location, a client typically
    calls the ``view.get()`` method. The client can access children in
    the tree (subviews) by subscripting the parent view (i.e.,
    ``view[key]``).
    """

    name = None
    """The name of the view, depicting the path taken through the
    configuration in Python-like syntax (e.g., ``foo['bar'][42]``).
    """

    def resolve(self):
        """The core (internal) data retrieval method. Generates (value,
        source) pairs for each source that contains a value for this
        view. May raise ConfigTypeError if a type error occurs while
        traversing a source.
        """
        raise NotImplementedError

    def first(self):
        """Return a (value, source) pair for the first object found for
        this view. This amounts to the first element returned by
        `resolve`. If no values are available, a NotFoundError is
        raised.
        """
        pairs = self.resolve()
        try:
            return iter_first(pairs)
        except ValueError:
            raise NotFoundError("{0} not found".format(self.name))

    def exists(self):
        """Determine whether the view has a setting in any source.
        """
        try:
            self.first()
        except NotFoundError:
            return False
        return True

    def add(self, value):
        """Set the *default* value for this configuration view. The
        specified value is added as the lowest-priority configuration
        data source.
        """
        raise NotImplementedError

    def set(self, value):
        """*Override* the value for this configuration view. The
        specified value is added as the highest-priority configuration
        data source.
        """
        raise NotImplementedError

    def root(self):
        """The RootView object from which this view is descended.
        """
        raise NotImplementedError

    def __repr__(self):
        return '<{}: {}>'.format(self.__class__.__name__, self.name)

    def __iter__(self):
        """Iterate over the keys of a dictionary view or the *subviews*
        of a list view.
        """
        # Try getting the keys, if this is a dictionary view.
        try:
            keys = self.keys()
            for key in keys:
                yield key

        except ConfigTypeError:
            # Otherwise, try iterating over a list.
            collection = self.get()
            if not isinstance(collection, (list, tuple)):
                raise ConfigTypeError(
                    '{0} must be a dictionary or a list, not {1}'.format(
                        self.name, type(collection).__name__
                    )
                )

            # Yield all the indices in the list.
            for index in range(len(collection)):
                yield self[index]

    def __getitem__(self, key):
        """Get a subview of this view."""
        return Subview(self, key)

    def __setitem__(self, key, value):
        """Create an overlay source to assign a given key under this
        view.
        """
        self.set({key: value})

    def __contains__(self, key):
        return self[key].exists()

    def set_args(self, namespace):
        """Overlay parsed command-line arguments, generated by a library
        like argparse or optparse, onto this view's value.
        """
        args = {}
        for key, value in namespace.__dict__.items():
            if value is not None:  # Avoid unset options.
                args[key] = value
        self.set(args)

    # Magical conversions. These special methods make it possible to use
    # View objects somewhat transparently in certain circumstances. For
    # example, rather than using ``view.get(bool)``, it's possible to
    # just say ``bool(view)`` or use ``view`` in a conditional.

    def __str__(self):
        """Get the value for this view as a bytestring.
        """
        if PY3:
            return self.__unicode__()
        else:
            return bytes(self.get())

    def __unicode__(self):
        """Get the value for this view as a Unicode string.
        """
        return STRING(self.get())

    def __nonzero__(self):
        """Gets the value for this view as a boolean. (Python 2 only.)
        """
        return self.__bool__()

    def __bool__(self):
        """Gets the value for this view as a boolean. (Python 3 only.)
        """
        return bool(self.get())

    # Dictionary emulation methods.

    def keys(self):
        """Returns a list containing all the keys available as subviews
        of the current views. This enumerates all the keys in *all*
        dictionaries matching the current view, in contrast to
        ``view.get(dict).keys()``, which gets all the keys for the
        *first* dict matching the view. If the object for this view in
        any source is not a dict, then a ConfigTypeError is raised. The
        keys are ordered according to how they appear in each source.
        """
        keys = []

        for dic, _ in self.resolve():
            try:
                cur_keys = dic.keys()
            except AttributeError:
                raise ConfigTypeError(
                    '{0} must be a dict, not {1}'.format(
                        self.name, type(dic).__name__
                    )
                )

            for key in cur_keys:
                if key not in keys:
                    keys.append(key)

        return keys

    def items(self):
        """Iterates over (key, subview) pairs contained in dictionaries
        from *all* sources at this view. If the object for this view in
        any source is not a dict, then a ConfigTypeError is raised.
        """
        for key in self.keys():
            yield key, self[key]

    def values(self):
        """Iterates over all the subviews contained in dictionaries from
        *all* sources at this view. If the object for this view in any
        source is not a dict, then a ConfigTypeError is raised.
        """
        for key in self.keys():
            yield self[key]

    # List/sequence emulation.

    def all_contents(self):
        """Iterates over all subviews from collections at this view from
        *all* sources. If the object for this view in any source is not
        iterable, then a ConfigTypeError is raised. This method is
        intended to be used when the view indicates a list; this method
        will concatenate the contents of the list from all sources.
        """
        for collection, _ in self.resolve():
            try:
                it = iter(collection)
            except TypeError:
                raise ConfigTypeError(
                    '{0} must be an iterable, not {1}'.format(
                        self.name, type(collection).__name__
                    )
                )
            for value in it:
                yield value

    # Validation and conversion.

    def flatten(self, redact=False):
        """Create a hierarchy of OrderedDicts containing the data from
        this view, recursively reifying all views to get their
        represented values.

        If `redact` is set, then sensitive values are replaced with
        the string "REDACTED".
        """
        od = OrderedDict()
        for key, view in self.items():
            if redact and view.redact:
                od[key] = REDACTED_TOMBSTONE
            else:
                try:
                    od[key] = view.flatten(redact=redact)
                except ConfigTypeError:
                    od[key] = view.get()
        return od

    def get(self, template=None):
        """Retrieve the value for this view according to the template.

        The `template` against which the values are checked can be
        anything convertible to a `Template` using `as_template`. This
        means you can pass in a default integer or string value, for
        example, or a type to just check that something matches the type
        you expect.

        May raise a `ConfigValueError` (or its subclass,
        `ConfigTypeError`) or a `NotFoundError` when the configuration
        doesn't satisfy the template.
        """
        return as_template(template).value(self, template)

    # Old validation methods (deprecated).

    def as_filename(self):
        return self.get(Filename())

    def as_choice(self, choices):
        return self.get(Choice(choices))

    def as_number(self):
        return self.get(Number())

    def as_str_seq(self):
        return self.get(StrSeq())

    # Redaction.

    @property
    def redact(self):
        """Whether the view contains sensitive information and should be
        redacted from output.
        """
        return () in self.get_redactions()

    @redact.setter
    def redact(self, flag):
        self.set_redaction((), flag)

    def set_redaction(self, path, flag):
        """Add or remove a redaction for a key path, which should be an
        iterable of keys.
        """
        raise NotImplementedError()

    def get_redactions(self):
        """Get the set of currently-redacted sub-key-paths at this view.
        """
        raise NotImplementedError()

class RootView(ConfigView):
    """The base of a view hierarchy. This view keeps track of the
    sources that may be accessed by subviews.
    """
    def __init__(self, sources):
        """Create a configuration hierarchy for a list of sources. At
        least one source must be provided. The first source in the list
        has the highest priority.
        """
        self.sources = list(sources)
        self.name = ROOT_NAME
        self.redactions = set()

    def add(self, obj):
        self.sources.append(ConfigSource.of(obj))

    def set(self, value):
        self.sources.insert(0, ConfigSource.of(value))

    def resolve(self):
        return ((dict(s), s) for s in self.sources)

    def clear(self):
        """Remove all sources (and redactions) from this
        configuration.
        """
        del self.sources[:]
        self.redactions.clear()

    def root(self):
        return self

    def set_redaction(self, path, flag):
        if flag:
            self.redactions.add(path)
        elif path in self.redactions:
            self.redactions.remove(path)

    def get_redactions(self):
        return self.redactions

class Subview(ConfigView):
    """A subview accessed via a subscript of a parent view."""
    def __init__(self, parent, key):
        """Make a subview of a parent view for a given subscript key.
        """
        self.parent = parent
        self.key = key

        # Choose a human-readable name for this view.
        if isinstance(self.parent, RootView):
            self.name = ''
        else:
            self.name = self.parent.name
            if not isinstance(self.key, int):
                self.name += '.'
        if isinstance(self.key, int):
            self.name += '#{0}'.format(self.key)
        elif isinstance(self.key, BASESTRING):
            if isinstance(self.key, bytes):
                self.name += self.key.decode('utf8')
            else:
                self.name += self.key
        else:
            self.name += repr(self.key)

    def resolve(self):
        for collection, source in self.parent.resolve():
            try:
                value = collection[self.key]
            except IndexError:
                # List index out of bounds.
                continue
            except KeyError:
                # Dict key does not exist.
                continue
            except TypeError:
                # Not subscriptable.
                raise ConfigTypeError(
                    "{0} must be a collection, not {1}".format(
                        self.parent.name, type(collection).__name__
                    )
                )
            yield value, source

    def set(self, value):
        self.parent.set({self.key: value})

    def add(self, value):
        self.parent.add({self.key: value})

    def root(self):
        return self.parent.root()

    def set_redaction(self, path, flag):
        self.parent.set_redaction((self.key,) + path, flag)

    def get_redactions(self):
        return (kp[1:] for kp in self.parent.get_redactions()
                if kp and kp[0] == self.key)

# Config file paths, including platform-specific paths and in-package
# defaults.

# Based on get_root_path from Flask by Armin Ronacher.
def _package_path(name):
    """Returns the path to the package containing the named module or
    None if the path could not be identified (e.g., if
    ``name == "__main__"``).
    """
    loader = pkgutil.get_loader(name)
    if loader is None or name == b'__main__':
        return None

    if hasattr(loader, 'get_filename'):
        filepath = loader.get_filename(name)
    else:
        # Fall back to importing the specified module.
        __import__(name)
        filepath = sys.modules[name].__file__

    return os.path.dirname(os.path.abspath(filepath))

def config_dirs():
    """Return a platform-specific list of candidates for user
    configuration directories on the system.

    The candidates are in order of priority, from highest to lowest. The
    last element is the "fallback" location to be used when no
    higher-priority config file exists.
    """
    paths = []

    if platform.system() == 'Darwin':
        paths.append(MAC_DIR)
        paths.append(UNIX_DIR_FALLBACK)
        if UNIX_DIR_VAR in os.environ:
            paths.append(os.environ[UNIX_DIR_VAR])

    elif platform.system() == 'Windows':
        paths.append(WINDOWS_DIR_FALLBACK)
        if WINDOWS_DIR_VAR in os.environ:
            paths.append(os.environ[WINDOWS_DIR_VAR])

    else:
        # Assume Unix.
        paths.append(UNIX_DIR_FALLBACK)
        if UNIX_DIR_VAR in os.environ:
            paths.append(os.environ[UNIX_DIR_VAR])

    # Expand and deduplicate paths.
    out = []
    for path in paths:
        path = os.path.abspath(os.path.expanduser(path))
        if path not in out:
            out.append(path)
    return out

# YAML loading.

class Loader(yaml.SafeLoader):
    """A customized YAML loader. This loader deviates from the official
    YAML spec in a few convenient ways:

    - All strings as are Unicode objects.
    - All maps are OrderedDicts.
    - Strings can begin with % without quotation.
    """
    # All strings should be Unicode objects, regardless of contents.
    def _construct_unicode(self, node):
        return self.construct_scalar(node)

    # Use ordered dictionaries for every YAML map.
    # From https://gist.github.com/844388
    def construct_yaml_map(self, node):
        data = OrderedDict()
        yield data
        value = self.construct_mapping(node)
        data.update(value)

    def construct_mapping(self, node, deep=False):
        if isinstance(node, yaml.MappingNode):
            self.flatten_mapping(node)
        else:
            raise yaml.constructor.ConstructorError(
                None, None,
                'expected a mapping node, but found %s' % node.id,
                node.start_mark
            )

        mapping = OrderedDict()
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            try:
                hash(key)
            except TypeError as exc:
                raise yaml.constructor.ConstructorError(
                    'while constructing a mapping',
                    node.start_mark, 'found unacceptable key (%s)' % exc,
                    key_node.start_mark
                )
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping

    # Allow bare strings to begin with %. Directives are still detected.
    def check_plain(self):
        plain = super(Loader, self).check_plain()
        return plain or self.peek() == '%'

Loader.add_constructor('tag:yaml.org,2002:str', Loader._construct_unicode)
Loader.add_constructor('tag:yaml.org,2002:map', Loader.construct_yaml_map)
Loader.add_constructor('tag:yaml.org,2002:omap', Loader.construct_yaml_map)

def load_yaml(filename):
    """Read a YAML document from a file. If the file cannot be read or
    parsed, a ConfigReadError is raised.
    """
    try:
        with open(filename, 'r') as f:
            return yaml.load(f, Loader=Loader)
    except (IOError, yaml.error.YAMLError) as exc:
        raise ConfigReadError(filename, exc)

# YAML dumping.

class Dumper(yaml.SafeDumper):
    """A PyYAML Dumper that represents OrderedDicts as ordinary mappings
    (in order, of course).
    """
    # From http://pyyaml.org/attachment/ticket/161/use_ordered_dict.py
    def represent_mapping(self, tag, mapping, flow_style=None):
        value = []
        node = yaml.MappingNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = False
        if hasattr(mapping, 'items'):
            mapping = list(mapping.items())
        for item_key, item_value in mapping:
            node_key = self.represent_data(item_key)
            node_value = self.represent_data(item_value)
            if not (isinstance(node_key, yaml.ScalarNode) and
                    not node_key.style):
                best_style = False
            if not (isinstance(node_value, yaml.ScalarNode) and
                    not node_value.style):
                best_style = False
            value.append((node_key, node_value))
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

    def represent_list(self, data):
        """If a list has less than 4 items, represent it in inline style
        (i.e. comma separated, within square brackets).
        """
        node = super(Dumper, self).represent_list(data)
        length = len(data)
        if self.default_flow_style is None and length < 4:
            node.flow_style = True
        elif self.default_flow_style is None:
            node.flow_style = False
        return node

    def represent_bool(self, data):
        """Represent bool as 'yes' or 'no' instead of 'true' or 'false'.
        """
        if data:
            value = 'yes'
        else:
            value = 'no'
        return self.represent_scalar('tag:yaml.org,2002:bool', value)

    def represent_none(self, data):
        """Represent a None value with nothing instead of 'none'.
        """
        return self.represent_scalar('tag:yaml.org,2002:null', '')

Dumper.add_representer(OrderedDict, Dumper.represent_dict)
Dumper.add_representer(bool, Dumper.represent_bool)
Dumper.add_representer(type(None), Dumper.represent_none)
Dumper.add_representer(list, Dumper.represent_list)

def restore_yaml_comments(data, default_data):
    """Scan default_data for comments (we include empty lines in our
    definition of comments) and place them before the same keys in data.
    Only works with comments that are on one or more own lines, i.e.
    not next to a yaml mapping.
    """
    comment_map = dict()
    default_lines = iter(default_data.splitlines())
    for line in default_lines:
        if not line:
            comment = "\n"
        elif line.startswith("#"):
            comment = "{0}\n".format(line)
        else:
            continue
        while True:
            line = next(default_lines)
            if line and not line.startswith("#"):
                break
            comment += "{0}\n".format(line)
        key = line.split(':')[0].strip()
        comment_map[key] = comment
    out_lines = iter(data.splitlines())
    out_data = ""
    for line in out_lines:
        key = line.split(':')[0].strip()
        if key in comment_map:
            out_data += comment_map[key]
        out_data += "{0}\n".format(line)
    return out_data

# Main interface.

class Configuration(RootView):
    def __init__(self, appname, modname=None, read=True):
        """Create a configuration object by reading the
        automatically-discovered config files for the application for a
        given name. If `modname` is specified, it should be the import
        name of a module whose package will be searched for a default
        config file. (Otherwise, no defaults are used.) Pass `False` for
        `read` to disable automatic reading of all discovered
        configuration files. Use this when creating a configuration
        object at module load time and then call the `read` method
        later.
        """
        super(Configuration, self).__init__([])
        self.appname = appname
        self.modname = modname

        self._env_var = '{0}DIR'.format(self.appname.upper())

        if read:
            self.read()

    def user_config_path(self):
        """Points to the location of the user configuration.

        The file may not exist.
        """
        return os.path.join(self.config_dir(), CONFIG_FILENAME)

    def _add_user_source(self):
        """Add the configuration options from the YAML file in the
        user's configuration directory (given by `config_dir`) if it
        exists.
        """
        filename = self.user_config_path()
        if os.path.isfile(filename):
            self.add(ConfigSource(load_yaml(filename) or {}, filename))

    def _add_default_source(self):
        """Add the package's default configuration settings. This looks
        for a YAML file located inside the package for the module
        `modname` if it was given.
        """
        if self.modname:
            pkg_path = _package_path(self.modname)
            if pkg_path:
                filename = os.path.join(pkg_path, DEFAULT_FILENAME)
                if os.path.isfile(filename):
                    self.add(ConfigSource(load_yaml(filename), filename, True))

    def read(self, user=True, defaults=True):
        """Find and read the files for this configuration and set them
        as the sources for this configuration. To disable either
        discovered user configuration files or the in-package defaults,
        set `user` or `defaults` to `False`.
        """
        if user:
            self._add_user_source()
        if defaults:
            self._add_default_source()

    def config_dir(self):
        """Get the path to the user configuration directory. The
        directory is guaranteed to exist as a postcondition (one may be
        created if none exist).

        If the application's ``...DIR`` environment variable is set, it
        is used as the configuration directory. Otherwise,
        platform-specific standard configuration locations are searched
        for a ``config.yaml`` file. If no configuration file is found, a
        fallback path is used.
        """
        # If environment variable is set, use it.
        if self._env_var in os.environ:
            appdir = os.environ[self._env_var]
            appdir = os.path.abspath(os.path.expanduser(appdir))
            if os.path.isfile(appdir):
                raise ConfigError('{0} must be a directory'.format(
                    self._env_var
                ))

        else:
            # Search platform-specific locations. If no config file is
            # found, fall back to the final directory in the list.
            for confdir in config_dirs():
                appdir = os.path.join(confdir, self.appname)
                if os.path.isfile(os.path.join(appdir, CONFIG_FILENAME)):
                    break

        # Ensure that the directory exists.
        if not os.path.isdir(appdir):
            os.makedirs(appdir)
        return appdir

    def set_file(self, filename):
        """Parses the file as YAML and inserts it into the configuration
        sources with highest priority.
        """
        filename = os.path.abspath(filename)
        self.set(ConfigSource(load_yaml(filename), filename))

    def dump(self, full=True, redact=False):
        """Dump the Configuration object to a YAML file.

        The order of the keys is determined from the default
        configuration file. All keys not in the default configuration
        will be appended to the end of the file.

        :param filename:  The file to dump the configuration to, or None
                          if the YAML string should be returned instead
        :type filename:   unicode
        :param full:      Dump settings that don't differ from the defaults
                          as well
        :param redact:    Remove sensitive information (views with the `redact`
                          flag set) from the output
        """
        if full:
            out_dict = self.flatten(redact=redact)
        else:
            # Exclude defaults when flattening.
            sources = [s for s in self.sources if not s.default]
            temp_root = RootView(sources)
            temp_root.redactions = self.redactions
            out_dict = temp_root.flatten(redact=redact)

        yaml_out = yaml.dump(out_dict, Dumper=Dumper,
                             default_flow_style=None, indent=4,
                             width=1000)

        # Restore comments to the YAML text.
        default_source = None
        for source in self.sources:
            if source.default:
                default_source = source
                break
        if default_source and default_source.filename:
            with open(default_source.filename, 'r') as fp:
                default_data = fp.read()
            yaml_out = restore_yaml_comments(yaml_out, default_data)

        return yaml_out

class LazyConfig(Configuration):
    """A Configuration at reads files on demand when it is first
    accessed. This is appropriate for using as a global config object at
    the module level.
    """
    def __init__(self, appname, modname=None):
        super(LazyConfig, self).__init__(appname, modname, False)
        self._materialized = False  # Have we read the files yet?
        self._lazy_prefix = []  # Pre-materialization calls to set().
        self._lazy_suffix = []  # Calls to add().

    def read(self, user=True, defaults=True):
        self._materialized = True
        super(LazyConfig, self).read(user, defaults)

    def resolve(self):
        if not self._materialized:
            # Read files and unspool buffers.
            self.read()
            self.sources += self._lazy_suffix
            self.sources[:0] = self._lazy_prefix
        return super(LazyConfig, self).resolve()

    def add(self, value):
        super(LazyConfig, self).add(value)
        if not self._materialized:
            # Buffer additions to end.
            self._lazy_suffix += self.sources
            del self.sources[:]

    def set(self, value):
        super(LazyConfig, self).set(value)
        if not self._materialized:
            # Buffer additions to beginning.
            self._lazy_prefix[:0] = self.sources
            del self.sources[:]

    def clear(self):
        """Remove all sources from this configuration."""
        super(LazyConfig, self).clear()
        self._lazy_suffix = []
        self._lazy_prefix = []

# "Validated" configuration views: experimental!

REQUIRED = object()
"""A sentinel indicating that there is no default value and an exception
should be raised when the value is missing.
"""

class Template(object):
    """A value template for configuration fields.

    The template works like a type and instructs Confit about how to
    interpret a deserialized YAML value. This includes type conversions,
    providing a default value, and validating for errors. For example, a
    filepath type might expand tildes and check that the file exists.
    """
    def __init__(self, default=REQUIRED):
        """Create a template with a given default value.

        If `default` is the sentinel `REQUIRED` (as it is by default),
        then an error will be raised when a value is missing. Otherwise,
        missing values will instead return `default`.
        """
        self.default = default

    def __call__(self, view):
        """Invoking a template on a view gets the view's value according
        to the template.
        """
        return self.value(view, self)

    def value(self, view, template=None):
        """Get the value for a `ConfigView`.

        May raise a `NotFoundError` if the value is missing (and the
        template requires it) or a `ConfigValueError` for invalid values.
        """
        if view.exists():
            value, _ = view.first()
            return self.convert(value, view)
        elif self.default is REQUIRED:
            # Missing required value. This is an error.
            raise NotFoundError("{0} not found".format(view.name))
        else:
            # Missing value, but not required.
            return self.default

    def convert(self, value, view):
        """Convert the YAML-deserialized value to a value of the desired
        type.

        Subclasses should override this to provide useful conversions.
        May raise a `ConfigValueError` when the configuration is wrong.
        """
        # Default implementation does no conversion.
        return value

    def fail(self, message, view, type_error=False):
        """Raise an exception indicating that a value cannot be
        accepted.

        `type_error` indicates whether the error is due to a type
        mismatch rather than a malformed value. In this case, a more
        specific exception is raised.
        """
        exc_class = ConfigTypeError if type_error else ConfigValueError
        raise exc_class(
            '{0}: {1}'.format(view.name, message)
        )

    def __repr__(self):
        return '{0}({1})'.format(
            type(self).__name__,
            '' if self.default is REQUIRED else repr(self.default),
        )

class Integer(Template):
    """An integer configuration value template.
    """
    def convert(self, value, view):
        """Check that the value is an integer. Floats are rounded.
        """
        if isinstance(value, int):
            return value
        elif isinstance(value, float):
            return int(value)
        else:
            self.fail('must be a number', view, True)

class Number(Template):
    """A numeric type: either an integer or a floating-point number.
    """
    def convert(self, value, view):
        """Check that the value is an int or a float.
        """
        if isinstance(value, NUMERIC_TYPES):
            return value
        else:
            self.fail(
                'must be numeric, not {0}'.format(type(value).__name__),
                view,
                True
            )

class MappingTemplate(Template):
    """A template that uses a dictionary to specify other types for the
    values for a set of keys and produce a validated `AttrDict`.
    """
    def __init__(self, mapping):
        """Create a template according to a dict (mapping). The
        mapping's values should themselves either be Types or
        convertible to Types.
        """
        subtemplates = {}
        for key, typ in mapping.items():
            subtemplates[key] = as_template(typ)
        self.subtemplates = subtemplates

    def value(self, view, template=None):
        """Get a dict with the same keys as the template and values
        validated according to the value types.
        """
        out = AttrDict()
        for key, typ in self.subtemplates.items():
            out[key] = typ.value(view[key], self)
        return out

    def __repr__(self):
        return 'MappingTemplate({0})'.format(repr(self.subtemplates))

class String(Template):
    """A string configuration value template.
    """
    def __init__(self, default=REQUIRED, pattern=None):
        """Create a template with the added optional `pattern` argument,
        a regular expression string that the value should match.
        """
        super(String, self).__init__(default)
        self.pattern = pattern
        if pattern:
            self.regex = re.compile(pattern)

    def __repr__(self):
        args = []

        if self.default is not REQUIRED:
            args.append(repr(self.default))

        if self.pattern is not None:
            args.append('pattern=' + repr(self.pattern))

        return 'String({0})'.format(', '.join(args))

    def convert(self, value, view):
        """Check that the value is a string and matches the pattern.
        """
        if isinstance(value, BASESTRING):
            if self.pattern and not self.regex.match(value):
                self.fail(
                    "must match the pattern {0}".format(self.pattern),
                    view
                )
            return value
        else:
            self.fail('must be a string', view, True)

class Choice(Template):
    """A template that permits values from a sequence of choices.
    """
    def __init__(self, choices):
        """Create a template that validates any of the values from the
        iterable `choices`.

        If `choices` is a map, then the corresponding value is emitted.
        Otherwise, the value itself is emitted.
        """
        self.choices = choices

    def convert(self, value, view):
        """Ensure that the value is among the choices (and remap if the
        choices are a mapping).
        """
        if value not in self.choices:
            self.fail(
                'must be one of {0}, not {1}'.format(
                    repr(list(self.choices)), repr(value)
                ),
                view
            )

        if isinstance(self.choices, collections.Mapping):
            return self.choices[value]
        else:
            return value

    def __repr__(self):
        return 'Choice({0!r})'.format(self.choices)

class OneOf(Template):
    """A template that permits values complying to one of the given templates.
    """
    def __init__(self, allowed, default=REQUIRED):
        super(OneOf, self).__init__(default)
        self.allowed = list(allowed)

    def __repr__(self):
        args = []

        if self.allowed is not None:
            args.append('allowed=' + repr(self.allowed))

        if self.default is not REQUIRED:
            args.append(repr(self.default))

        return 'OneOf({0})'.format(', '.join(args))

    def value(self, view, template):
        self.template = template
        return super(OneOf, self).value(view, template)

    def convert(self, value, view):
        """Ensure that the value follows at least one template.
        """
        is_mapping = isinstance(self.template, MappingTemplate)

        for candidate in self.allowed:
            try:
                if is_mapping:
                    if isinstance(candidate, Filename) and \
                            candidate.relative_to:
                        next_template = candidate.template_with_relatives(
                            view,
                            self.template
                        )

                        next_template.subtemplates[view.key] = as_template(
                            candidate
                        )
                    else:
                        next_template = MappingTemplate({view.key: candidate})

                    return view.parent.get(next_template)[view.key]
                else:
                    return view.get(candidate)
            except ConfigTemplateError:
                raise
            except ConfigError:
                pass
            except ValueError as exc:
                raise ConfigTemplateError(exc)

        self.fail(
            'must be one of {0}, not {1}'.format(
                repr(self.allowed), repr(value)
            ),
            view
        )

class StrSeq(Template):
    """A template for values that are lists of strings.

    Validates both actual YAML string lists and single strings. Strings
    can optionally be split on whitespace.
    """
    def __init__(self, split=True):
        """Create a new template.

        `split` indicates whether, when the underlying value is a single
        string, it should be split on whitespace. Otherwise, the
        resulting value is a list containing a single string.
        """
        super(StrSeq, self).__init__()
        self.split = split

    def convert(self, value, view):
        if isinstance(value, bytes):
            value = value.decode('utf8', 'ignore')

        if isinstance(value, STRING):
            if self.split:
                return value.split()
            else:
                return [value]

        try:
            value = list(value)
        except TypeError:
            self.fail('must be a whitespace-separated string or a list',
                      view, True)

        def convert(x):
            if isinstance(x, STRING):
                return x
            elif isinstance(x, bytes):
                return x.decode('utf8', 'ignore')
            else:
                self.fail('must be a list of strings', view, True)
        return list(map(convert, value))

class Filename(Template):
    """A template that validates strings as filenames.

    Filenames are returned as absolute, tilde-free paths.

    Relative paths are relative to the template's `cwd` argument
    when it is specified, then the configuration directory (see
    the `config_dir` method) if they come from a file. Otherwise,
    they are relative to the current working directory. This helps
    attain the expected behavior when using command-line options.
    """
    def __init__(self, default=REQUIRED, cwd=None, relative_to=None,
                 in_app_dir=False):
        """`relative_to` is the name of a sibling value that is
        being validated at the same time.

        `in_app_dir` indicates whether the path should be resolved
        inside the application's config directory (even when the setting
        does not come from a file).
        """
        super(Filename, self).__init__(default)
        self.cwd = cwd
        self.relative_to = relative_to
        self.in_app_dir = in_app_dir

    def __repr__(self):
        args = []

        if self.default is not REQUIRED:
            args.append(repr(self.default))

        if self.cwd is not None:
            args.append('cwd=' + repr(self.cwd))

        if self.relative_to is not None:
            args.append('relative_to=' + repr(self.relative_to))

        if self.in_app_dir:
            args.append('in_app_dir=True')

        return 'Filename({0})'.format(', '.join(args))

    def resolve_relative_to(self, view, template):
        if not isinstance(template, (collections.Mapping, MappingTemplate)):
            # disallow config.get(Filename(relative_to='foo'))
            raise ConfigTemplateError(
                'relative_to may only be used when getting multiple values.'
            )

        elif self.relative_to == view.key:
            raise ConfigTemplateError(
                '{0} is relative to itself'.format(view.name)
            )

        elif self.relative_to not in view.parent.keys():
            # self.relative_to is not in the config
            self.fail(
                (
                    'needs sibling value "{0}" to expand relative path'
                ).format(self.relative_to),
                view
            )

        old_template = {}
        old_template.update(template.subtemplates)

        # save time by skipping MappingTemplate's init loop
        next_template = MappingTemplate({})
        next_relative = self.relative_to

        # gather all the needed templates and nothing else
        while next_relative is not None:
            try:
                # pop to avoid infinite loop because of recursive
                # relative paths
                rel_to_template = old_template.pop(next_relative)
            except KeyError:
                if next_relative in template.subtemplates:
                    # we encountered this config key previously
                    raise ConfigTemplateError((
                        '{0} and {1} are recursively relative'
                    ).format(view.name, self.relative_to))
                else:
                    raise ConfigTemplateError((
                        'missing template for {0}, needed to expand {1}\'s' +
                        'relative path'
                    ).format(self.relative_to, view.name))

            next_template.subtemplates[next_relative] = rel_to_template
            next_relative = rel_to_template.relative_to

        return view.parent.get(next_template)[self.relative_to]

    def value(self, view, template=None):
        path, source = view.first()
        if not isinstance(path, BASESTRING):
            self.fail(
                'must be a filename, not {0}'.format(type(path).__name__),
                view,
                True
            )
        path = os.path.expanduser(STRING(path))

        if not os.path.isabs(path):
            if self.cwd is not None:
                # relative to the template's argument
                path = os.path.join(self.cwd, path)

            elif self.relative_to is not None:
                path = os.path.join(
                    self.resolve_relative_to(view, template),
                    path,
                )

            elif source.filename or self.in_app_dir:
                # From defaults: relative to the app's directory.
                path = os.path.join(view.root().config_dir(), path)

        return os.path.abspath(path)

class TypeTemplate(Template):
    """A simple template that checks that a value is an instance of a
    desired Python type.
    """
    def __init__(self, typ, default=REQUIRED):
        """Create a template that checks that the value is an instance
        of `typ`.
        """
        super(TypeTemplate, self).__init__(default)
        self.typ = typ

    def convert(self, value, view):
        if not isinstance(value, self.typ):
            self.fail(
                'must be a {0}, not {1}'.format(
                    self.typ.__name__,
                    type(value).__name__,
                ),
                view,
                True
            )
        return value

class AttrDict(dict):
    """A `dict` subclass that can be accessed via attributes (dot
    notation) for convenience.
    """
    def __getattr__(self, key):
        if key in self:
            return self[key]
        else:
            raise AttributeError(key)

def as_template(value):
    """Convert a simple "shorthand" Python value to a `Template`.
    """
    if isinstance(value, Template):
        # If it's already a Template, pass it through.
        return value
    elif isinstance(value, collections.Mapping):
        # Dictionaries work as templates.
        return MappingTemplate(value)
    elif value is int:
        return Integer()
    elif isinstance(value, int):
        return Integer(value)
    elif isinstance(value, type) and issubclass(value, BASESTRING):
        return String()
    elif isinstance(value, BASESTRING):
        return String(value)
    elif isinstance(value, set):
        # convert to list to avoid hash related problems
        return Choice(list(value))
    elif isinstance(value, list):
        return OneOf(value)
    elif value is float:
        return Number()
    elif value is None:
        return Template()
    elif value is dict:
        return TypeTemplate(collections.Mapping)
    elif value is list:
        return TypeTemplate(collections.Sequence)
    elif isinstance(value, type):
        return TypeTemplate(value)
    else:
        raise ValueError('cannot convert to template: {0!r}'.format(value))


text:
title: Get report details
layout: reference
---

# Get Report Details

Retrieves the full set of information for the report. Includes the Report Header, Entry, Attendee, Itemization and Allocation details.

Some elements will appear only if the OAuth consumer has the Web Services Admin role. These include: The **ReportKey** element, the employee's credit card information, and the employee's bank account information, VAT information, Journal entries. Connectors that utilize this information go through a review process with SAP Concur that includes verification of secure data handling.

GET list of reports can be found [here](/api-reference/expense/expense-report/v2.reports.html)

* [Request](#request)
* [Response](#response)
  * [Schema](#schema)
    * [Expense Entry](#expense-entry)
    * [Itemization](#itemization)
    * [Attendee](#attendee)
    * [Allocation](#allocation)
    * [Journal Entry](#journal-entry)
    * [VAT Data](#vat-data)
    * [Card Transaction](#card-transaction)
    * [Custom Fields](#custom-fields)
    * [Report Owner](#report-owner)
    * [Employee Bank Account](#employee-bank-account)
* [Examples](#examples)

## Request

### Request Parameters

#### Path Parameters

| Parameter |Required/Optional| Description |
|-----------------|--------|-----------------------------|
|_reportId_| required | The identifier for the desired report.|

Example: `https://us.api.concursolutions.com/api/expense/expensereport/v2.0/report/{reportId}`

**URI Source**: The ReportId is returned in the **ReportId** element of the Get List of Reports function

### Headers

#### Authorization Header
Authorization header with OAuth token for valid SAP Concur user. The OAuth consumer must have one of the following user roles in SAP Concur: Company Administrator or Web Services Administrator for Professional, or Can Administer for Standard.
These roles allow the user to manage data for the entire company.

#### Accept Header
application/xml

## Response

### Content Types
application/xml

### Schema
This request will return a **ReportDetails** parent element.

#### ReportDetails

 Element |  Description
 -----| ----- |
  UserLoginID |  The user ID of the report owner. Maximum 128 characters.
  EmployeeName |  The name of the employee who created the report. Maximum 66 characters. |
 ReportID |  The unique identifier for the report, which appears in the Concur Expense UI. Maximum 32 character varchar. |
  ReportKey |  The unencrypted unique identifier for the report, that appears on the report header. The element appears only if the OAuth consumer has the Web Services Admin role in SAP Concur. Maximum 48 characters. |
  ReportName |  The name of the report. Maximum 40 characters. |
  Purpose |  The information from the Business Purpose field. |
  ReportDate |  The date from the report header. Format: YYYY-MM-DDThh:mm:ss |
  CreationDate |  The date the report was created. Format: YYYY-MM-DDThh:mm:ss |
  SubmitDate |  The date the report was submitted. Maximum 10 characters. |
  PaidDate |  The date the report was extracted for payment. This element has an attribute named i:nil. If the value for this element is null, the i:nil attribute will be set to true. Format: YYYY-MM-DDThh:mm:ss |
  CurrencyCode |  The [3-letter ISO 4217 currency code][1] for the expense report currency. The expense report currency is defined as the report creator's default reimbursement currency.
  ReportTotal |  The total amount of the report. Maximum 23 characters. |
  PersonalExpenses |  The total amount of expenses marked as personal. Maximum 23 characters.
  AmountDueEmployee | The total amount due to the employee for the report. Maximum 23 characters. |
  AmountDueCompanyCard |  The total amount due to the company card for the report. Maximum 23 characters. |
  TotalClaimedAmount |  The total amount of all non-personal expenses in the report. Maximum 23 characters. |
  TotalApprovedAmount |  The total amount of approved expenses in the report. Maximum 23 characters. |
  ApprovalStatusCode |  The approval status code for the report. |
  ApprovalStatusName |  The approval status name for the report. |
  PaymentStatusCode |  The unique identifier for the payment status of the report. |
  PaymentStatusName |  The payment status of the report. |
  OrgUnit1 through OrgUnit6 |  The details from the Org Unit custom fields. These may not have data, depending on configuration. Maximum 48 characters for each field. |
  Custom1 through Custom20 |  The details from the Custom fields. These may not have data, depending on configuration. If report owner information is stored in these fields, it may be outdated. Refer to the **ReportOwner** parent element for the current owner information. Refer to the **Custom Fields** Child Elements table for more information. |
  LedgerName |  The name of the expense report ledger. Maximum 20 characters. |
  PolicyID |  The unique identifier of the policy that applies to this report. Maximum 64 characters. |
  EverSentBack |  Whether the report has ever been sent back to the employee. Format: Y/N |
  HasException |  Whether the report has exceptions. Format: Y/N  |
  WorkflowActionURL |  The URL to post a workflow action to the report using the Post Report Workflow Action function. |
  ExpenseEntriesList |  This parent element has an **ExpenseEntry** child element for each entry. Refer to the **ExpenseEntry elements** table for more information. |
  ReportImageURL |  The URL to access the image associated with the report. This URL is valid for 30 minutes after the web service call. |
  Country |  The report country. Maximum 2 characters. Format: [The ISO 3166-1 alpha-2 country code][3]. Example: United States is US. |
  CountrySubdivision |  The report country subdivision. Format: [ISO 3166-2:2007 country subdivision][4]. |
  ProcessingPaymentDate |  The date that the report completed all approvals and was ready to be extracted for payment. Format: YYYY-MM-DD |
  ReceiptsReceived |  If Y, then this report has its receipt receipt confirmed by the Expense Processor. Format: Y/N |
  ReportOwner |  This parent element includes details about the employee who is the report owner. It saves the caller from calling the Get User Information function to get employee information commonly used in accounting integration. The **ReportOwner** element includes the most recent information about the report owner, at the time the report is requested. |
  EmployeeBankAccount |  This parent element includes the bank account data found on the **Bank Information** page in Profile. This data is used in **Payment System** integrations where the payment system reimburses the employee via this bank account.

### ExpenseEntry

|  Element |  Description |
| -------- | ------------ |
|  ReportEntryID |  The ID of the report entry. Maximum 13 characters. |
|  ExpenseTypeID |  The expense type ID for the expense entry. Expense Type IDs are returned in the **ExpKey** element by the Get Expense Group Configuration endpoint. |
|  ExpenseTypeName |  The expense type name. Maximum 64 characters. |
|  SpendCategory |  The spend category specified for this expense type. Varies by client, used in reporting. |
|  PaymentTypeCode |  The code for the payment type. Maximum 4 characters. |
|  PaymentTypeName |  The name for the payment type. Maximum 80 characters. |
|  TransactionDate |  The date of the expense entry. Maximum 10 characters. Format: YYYY-MM-DD |
|  TransactionCurrencyName |  The name of the transaction currency. Example: US, Dollar |
|  ExchangeRate |  The exchange rate that applies to the entry. Maximum 23 characters. |
|  TransactionAmount |  The amount of the expense entry in the original transaction currency. Maximum 23 characters. |
|  PostedAmount |  The amount of the expense entry in the user's reimbursement currency. The user's reimbursement currency is returned in the **CrnCode** element for the report. Maximum 23 characters. |
|  ApprovedAmount |  The approved amount of the expense entry in the user's reimbursement currency.The user's reimbursement currency is returned in the **CrnCode** element for the report. Maximum 23 characters. |
|  BusinessPurpose |  The text from the Business Purpose field of the entry. Maximum 64 characters. |
|  VendorDescription |  The vendor name of the expense entry, which can be entered manually by the user or imported from the card transaction Merchant Name field. Maximum 64 characters. |
|  LocationName |  The location for the expense entry, usually the city name. |
|  LocationSubdivision |  The location's State, Province, or Country Subdivision. Maximum 6 characters. |
|  LocationCountry |  The location's Country. Maximum 2 characters. |
|  OrgUnit1 through OrgUnit6 |  The details from the Org Unit custom fields. These may not have data, depending on configuration. Maximum 48 characters for each field. |
|  Custom1 through Custom40 |  The details from the Custom fields. These may not have data, depending on configuration. Refer to the **Custom Fields elements** table for more information.  |
|  FormID |  The ID for the expense entry form. |
|  EntryImageID |  The unique identifier for the image associated with the entry. |
|  HasVat |  Whether the entry contains VAT data. Maximum 1 character. Format: Y/N |
|  HasComments |  Whether the expense entry has comments. Maximum 1 character. Format: Y/N |
|  CommentCount |  The number of comments associated with the expense entry. |
|  IsItemized |  Whether the expense entry is itemized. Maximum 1 character. Format: Y/N |
|  HasExceptions |  Whether the expense entry has exceptions. Maximum 1 character. Format: Y/N |
|  IsPersonal |  Whether the expense entry is marked as personal. Maximum 1 character. Format: Y/N |
|  HasAttendees |  Whether the expense entry has attendees. Maximum 1 character. Format: Y/N |
|  HasAllocation |  Defines the amount of allocations for the expense. Maximum 1 character. Possible values are: P, for partial allocation, F, for full allocation, or N, for no allocation. |
|  IsCreditCardCharge |  Whether the expense came from a credit card feed. Maximum 1 character. Format: Y/N |
|  IsPersonalCardCharge |  Whether the expense came from a personal card feed. Maximum 1 character. Format: Y/N |
|  ReceiptRequired | Whether the original receipt is required for the entry. Maximum 1 character. Format: Y/N |
|  ImageRequired |  Whether a receipt image is required for the entry. Maximum 1 character. Format: Y/N |
|  E-ReceiptID |  The ID for the attached e-receipt, if available. |
|  LastModifiedDate |  The date the expense entry was last changed. Maximum 19 characters. Format: YYYY-MM-DDThh:mm:ss |
|  ItemizationsList |  The list of itemizations for the expense entry. This parent element will have at least one **Itemization** child element. If the expense entry is not itemized, the **Itemization** will contain the same values as the entry. If the expense entry has itemizations, there will be one **Itemization** child element for each itemization. Refer to the **Itemization elements** table for more information.
 **NOTE**: There are a few rare cases where the **ItemizationsList** will be null. This happens when a report entry has a payment type code that is not **IBCP with offsets** or **CBCP** and there is a Regular or Child expense entry with an Approved Amount equal to zero. The expense entry will have a Null **ItemizationsList**. |
|  ReportEntryVendorName |  Vendor name the employee selected from the Vendor list field. Maximum 64 characters. |
|  ReportEntryReceiptReceived |  If Y, then this entry has been marked as reviewed by a processor. Maximum 1 character. Format: Y/N |
|  ReportEntryReceiptType |  Maximum 1 character. One of these:
 T = tax receipt
 R= regular receipt
 N = no receipt |
|  CardTransaction |  This parent element includes the card transaction data found in the card transaction associated to this expense entry. This data is used in **Payment System** integrations where the payment system reimburses the card issuer for the indicated card account. Refer to the **CardTransaction elements** table. |
|  ExpensePay |  Whether the entry was paid using the Expense Pay service. This element has a value if the report has reached the Processing Payment workflow step. Format: Yes/No |

### Itemization

|  Element |  Description |
| -------- | ------------ |
|  ItemType |  The type of itemization. If the expense entry does not have any itemizations, this will be set to Regular. If the expense entry contains itemizations, each one will be set to Child. |
|  ItemizationID |  The unique identifier for the itemization. Maximum 19 characters. |
|  ExpenseTypeID |  The expense type ID for the itemization. |
|  ExpenseTypeName |  The expense type for the itemization. Maximum 64 characters. |
|  TransactionDate |  The date of the transaction. Maximum 10 characters. Format: YYYY-MM-DD |
|  TransactionAmount |  The amount for the itemization in the expense currency. Maximum 23 characters. |
|  PostedAmount |  The amount for the itemization in the user's reimbursement currency. The user's reimbursement currency is returned in the **CrnCode** element for the report. Maximum 23 characters. |
|  ApprovedAmount |  The approved amount of the itemization in the user's reimbursement currency. The user's reimbursement currency is returned in the **CrnCode** element for the report. Maximum 23 characters. |
|  BusinessPurpose |  The business purpose field from the report header. |
|  OrgUnit1 through OrgUnit6 |  The details from the Org Unit custom fields. These may not have data, depending on configuration. Maximum 48 characters for each field. |
|  Custom1 through Custom40 |  The custom fields associated with the itemization. These may not have data, depending on your configuration. Refer to the **Custom Fields elements** table for more information.  |
|  Value |  The value in the custom field. Maximum 48 characters. |
|  Code |  Custom list fields will include the list item code in this element. |
|  HasComments |  Whether the itemization has comments. Maximum 1 character. Format: Y/N |
|  CommentCount |  The number of comments associated with the itemization. |
|  IsPersonal |  Whether the itemization is personal. Maximum 1 character. Format: Y/N |
|  LastModified |  The UTC date when the itemization was last modified. Maximum 19 characters. Format: YYYY-MM-DDThh:mm:ss |
|  AttendeesList |  This parent element contains one **Attendee** element for each associated attendee. Refer to the **Attendee elements** table for more information. |
|  AllocationsList |  This parent element contains at least one **Allocation** element. It will contain multiple **Allocation** elements if there are multiple allocations for the itemization. Refer to the **Allocation elements** table. |

### Attendee

|  Element |  Description |
| -------- | ------------ |
|  AttendeeType |  The type of attendee. Maximum 40 characters. |
|  FirstName |  The attendee's first name. Maximum 50 characters. |
|  LastName |  The attendee's last name. Maximum 132 characters. |
|  Company |  The attendee's company name. Maximum 150 characters. |
|  Title |  The attendee's title. Maximum 32 characters. |
|  ExternalID |  The unique identifier for the attendee, managed outside SAP Concur. Maximum 48 characters. |
|  Custom1 through Custom20 |  The details from the custom fields. These may not have data, depending on configuration. Refer to the **Custom Fields elements** table for more information. |
|  HasExceptionsPrevYear |  Whether the attendee has exceptions in the previous year, based on yearly total limits for attendees. Maximum 1 character. Format: Y/N |
|  HasExceptionsYTD |  Whether the attendee has exceptions in the current year, based on yearly total limits for attendees. Maximum 1 character. Format: Y/N |
|  IsDeleted |  Whether the attendee is marked as deleted. Maximum 1 character. Format: Y/N |
|  OwnerName |  The name of the employee that owns the attendee record. |
|  TotalAmountPrevYear |  The total amount spent on the attendee in the previous calendar year. |
|  TotalAmountYTD |  The total amount spent on the attendee in the current calendar year. |
|  VersionNumber |  The attendee's version number. |
|  AttendeeID |  Attendee unique identifier within SAP Concur. |
|  AttendeeTypeCode |  The unique identifier for the attendee type. |
|  AttendeeOwnerID |  The unique identifier for the person or system that owns the attendee. |
|  CurrencyCode |  The [3-letter ISO 4217 currency code][1] for attendee related amounts. |

### Allocation

|  Element |  Description |
| -------- | ------------ |
|  AllocationID |  The unique alphanumeric identifier for the allocation. Maximum 13 characters. |
|  Percentage |  The percentage of the expense that is included in this allocation. Maximum 11 characters. |
|  AccountCode1 |  The primary accounting code assigned to the expense type associated with this allocation. Typically, expense types have only this primary account code. |
|  AccountCode2 | The secondary or alternative accounting code assigned to the expense type associated with this allocation. In rare cases some expense types include this accounting code to handle special cases. One example of these special cases is when using travel allowance, where one expense would use the primary account code for the allowed amount, and the alternative account code for the overage. Another example is personal use of a company car.
 Refer to the _Expense: Account Codes Setup Guide_ for more information on how Concur Expense determines which accounting codes to use.  |
|  Custom1 through Custom20 |  The custom fields associated with the allocation. These may not have data, depending on your configuration. Refer to the **Custom Fields elements** table for more information. |
|  JournalEntriesList |  This parent element contains at least one **JournalEntry** child element. It contains multiple **JournalEntry** elements if the allocation has multiple journal entries. Refer to the **JournalEntry elements** table for more information. |
|  VATDataList |  This parent element contains one **VATData** element for each VAT line item. This element will be empty if there are no VAT line items. Refer to the **VATData elements** table for more information. |

### JournalEntry

|  Element |  Description |
| -------- | ------------ |
|  JournalID |  Unique identifier for the journal entry. |
|  PayerPaymentTypeName |Payer payment type. Maximum 64 characters. One of these:
 Company = Company
 Employee = Employee
 Payment Type for the Credit Card Payment Type|
|  PayerPaymentTypeCode |  Payment code name for the payer. Maximum 80 characters. |
|  PayeePaymentTypeName |  Payee payment type. Maximum 64 characters. One of these:
 Company = Company
 Employee = Employee
 Payment Type for the Credit Card Payment Type |
|  PayeePaymentCode |  Payment code name for the payee. Maximum 80 characters. |
|  AccountCode |  The account code Concur Expense determines should apply to this journal entry. For journal entries associated to an allocation, Concur Expense uses the business logic described in the _Expense: Account Codes Setup Guide_ to determine whether the primary or secondary account code should apply.  When there is no allocation associated to the journal entry, Concur Expense uses clearing account codes for Credit Card and Cash Advance for personal use of a company paid expense or a cash advance issued to an employee respectively. Maximum 48 characters.
 **NOTE**: The developer should almost always use this accounting code when creating financial transactions in financial systems. In some situations a developer may need to use the accounting codes in the Allocation parent element.|
|  DebitOrCredit |  Maximum 2 characters. Either:
 DR = Debit
 CR = Credit |
|  Amount |  Value, as credit or debit, of the amount to be exchanged between the payer and payee for this expense account code (not an absolute value) Maximum 23 characters. EXAMPLES: Value of zero, credit, or debit, as the following:
 0 (Zero) "0"
 \+ (Plus / Debit) "+50.00"
 \- (Minus / Credit) "-50.00" |
|  JobRunKey |  Either the unique identifier for job run for the accounting extract that processed this journal, or a static value indicating the journal was processed by Manual Pay, Expense Pay, or some other system. |

## VATData

|  Element |  Description |
| -------- | ------------ |
|  TaxName |  Tax authority name. Maximum 50 characters. |
|  TaxAuthorityLabel |  5-digit code that appears on the expense entry pages. Maximum 5 characters. |
|  TaxTransactionAmount |  Calculated tax amount for this expense in the spend currency. Maximum 23 characters. |
|  TaxPostedAmount |  Calculated tax amount for this expense entry in the reimbursement currency. Maximum 23 characters. |
|  Source |  Specifies how the tax data was derived. Maximum 4 characters. One of these:
 CARD = Provided from company card
 USER = Entered by employee
 SYST = Calculated by system
 PROC = Entered by processor |
|  TaxReclaimTransactionAmount |  Calculated amount of tax eligible for reclaim in the spend currency. Maximum 23 characters. |
|  TaxReclaimPostedAmount |  Calculated amount of tax eligible for reclaim in the reimbursement currency. Maximum 23 characters. |

###  CardTransaction

|  Element |  Description |
| -------- | ------------ |
|  AccountNumber |  Credit card number used for this expense. This value is encrypted in the response. Maximum 255 characters. |
|  CardDescription |  The name on the credit card used for this expense. Maximum 255 characters. |
|  CardTypeCode |  Type of credit card. |
|  TransactionReferenceNumber |  Reference number from the credit card vendor. Maximum 64 characters. |
|  TransactionCCTType |  Transaction type supplied by card vendor. Maximum 3 characters. One of these:
 ANF = Annual Fees
 CAV = Cash Advance
 CCF = Cash and Check Fees
 CHG = Other Bank Charges and Fees
 FNC = Finance Charges
 LAF = Late Fees
 NSF = Insufficient Funds Check Fees
 PAY = Payment
 RPE = Credit Card Transaction |
|  TransactionID |  Calculated value assigned to this card entry during the import process. Maximum 32 characters. |
|  TransactionAmount |  Amount of the charge in the spend currency. Maximum 23 characters. |
|  TaxAmount |  Amount of tax on the transaction amount (if provided by card vendor). Maximum 23 characters. |
|  TransactionAlphaCode |  Currency code for the spend currency. Maximum 3 characters. Format: [ISO 4217 3 digit alpha code][1] |
|  PostedAmount |  Amount of the charge in the billing currency of the card. Maximum 23 characters. |
|  PostedAlphaCode |  Currency code for the card billing currency. Maximum 3 characters. Format: [ISO 4217 3 digit alpha code][1] |
|  TransactionDate |  Date the charge was made at the merchant. Maximum 10 characters. |
|  PostedDate |  Date the charge was posted to the credit card account. Maximum 10 characters. |
|  Description |  Description of the charge from the merchant. Maximum 42 characters. |
|  MasterCardCode |  Merchant code sent from the credit card vendor. Maximum 5 characters. |
|  TransactionMerchantName |  Name of the merchant. Maximum 50 characters. |
|  MerchantCity |  Merchant city. Maximum 40 characters. |
|  MerchantState |  Merchant State/Province. Maximum 32 characters. |
|  MerchantCountryCode |  Merchant country location code. Format: 2 digit alpha code |
|  MerchantReferenceNumber |  Merchant reference number passed from the merchant to the card. Maximum 15 characters. |
|  ExchangeRateFromBillingToEmployeeCurrency |  Currency exchange rate used between the credit card billing currency and the employee's reimbursement currency. Maximum 23 characters. |
|  BillingAmount |  Amount due to the company card from the employee or company (depending on who is responsible for the bill) for this detail row. Maximum 23 characters. |
|  AccountNumberLastSegment  |  The last 4 digits of the Card Account.  |

### Custom Fields

|  Element |  Description |
| ----- | ----- |
|  Type |  The custom field type. Will be one of the following: Amount, Boolean, ConnectedList, Date, Integer, List, Number, Text |
|  Value |  The value in the custom field. Maximum 48 characters. |
|  Code |  Custom list fields will include the list item code in this element. |

### ReportOwner

|  Element |  Description |
| ----- | ----- |
|  EmployeeCustom21 |  The report owner's group ID. Maximum 48 characters. |
|  EmployeeID |  Employee ID often also serves as the employee's **Vendor ID** for AP system integrations or **Payroll ID** for Payroll integrations. Maximum 48 characters. |
|  EmployeeOrgUnit1 through EmployeeOrgUnit6 |  The report owner's organizational unit information. Maximum 48 characters for each field. |
|  FirstName |  The report owner's first name. Maximum 32 characters. |
|  LastName |  The report owner's last name. Maximum 32 characters. |
|  MiddleInitial |  The report owner's middle initial. Maximum 1 character. |
|  ReimbursementMethodCode |  The report owner's reimbursement method code, as defined in the employee's Profile. |

### EmployeeBankAccount

|  Element |  Description |
| ----- | ----- |
|  BankNumber |  The bank identification number entered on the Bank Information page. Maximum 11 characters. |
|  BankName |  The bank name entered on the Bank Information page. Maximum 48 characters. |
|  BranchLocation |  The branch location entered on the Bank Information page. Maximum 30 characters. |
|  AccountNumber |  The bank account number entered on the Bank Information page. Maximum 100 characters. |
|  AccountName |  The name on the account entered on the Bank Information page. |
|  PostalAddressLine1 |  The postal address line 1 entered on the Bank Information page. Maximum 48 characters. |
|  PostalAddressLine2 |  The postal address line 2 entered on the Bank Information page. Maximum 48 characters. |
|  PostalAddressCity |  The postal address city entered on the Bank Information page. Maximum 24 characters. |
|  PostalAddressRegion |  The postal address region entered on the Bank Information page. Maximum 24 characters. |
|  PostalAddressCode |  The postal address code entered on the Bank Information page. Maximum 20 characters. |
|  PostalAddressCountry |  The postal address country entered on the Bank Information page. Maximum 2 characters. Format: The [ISO 3166-1 alpha-2 country code][3]. Example: United States is US. |

## Examples

### XML Example Request

```http
GET https://us.api.concursolutions.com/api/expense/expensereport/v2.0/report/n6ujbuLd1Arwe45lT7As3ThJYJf2dAsrrEW HTTP/1.1
Authorization: OAuth {access token}
...
```

### XML Example of Successful Response

```http
HTTP/1.1 200 OK
Content-Type: application/xml

<?xml version="1.0" encoding="utf-8"?>
<ReportDetails xmlns="http://us.api.concursolutions.com/api/expense/expensereport/2012/07" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <UserLoginID>cm@example.com</UserLoginID>
    <EmployeeName>Miller, Chris</EmployeeName>
    <ReportID>425FE2ADB4954FCA90CD</ReportID>
    <ReportName>Client Meeting</ReportName>
    <Purpose>Sales meeting</Purpose>
    <ReportDate>2013-01-10T00:00:00</ReportDate>
    <CreationDate>2013-01-11T01:58:20</CreationDate>
    <SubmitDate>0001-01-01T00:00:00</SubmitDate>
    <PaidDate i:nil="true" />
    <CurrencyCode>USD</CurrencyCode>
    <ReportTotal>50.00000000</ReportTotal>
    <PersonalExpenses>0.00000000</PersonalExpenses>
    <AmountDueEmployee>50.00000000</AmountDueEmployee>
    <AmountDueCompanyCard>0.00000000</AmountDueCompanyCard>
    <TotalClaimedAmount>50.00000000</TotalClaimedAmount>
    <TotalApprovedAmount>50.00000000</TotalApprovedAmount>
    <ApprovalStatusCode>A_NOTF</ApprovalStatusCode>
    <ApprovalStatusName>Not Submitted</ApprovalStatusName>
    <PaymentStatusCode>P_NOTP</PaymentStatusCode>
    <PaymentStatusName>Not Paid</PaymentStatusName>
    <OrgUnit1>Sales</OrgUnit1>
    <OrgUnit2 />
    <OrgUnit3 />
    <OrgUnit4 />
    <OrgUnit5 />
    <OrgUnit6 />
    <Custom1 />
    <Custom2 />
    <Custom3 />
    <Custom4 />
    <Custom5 />
    <Custom6 />
    <Custom7 />
    <Custom8 />
    <Custom9 />
    <Custom10 />
    <Custom11 />
    <Custom12 />
    <Custom13 />
    <Custom14 />
    <Custom15 />
    <Custom16 />
    <Custom17 />
    <Custom18 />
    <Custom19 />
    <Custom20 />
    <LedgerName>Corporate</LedgerName>
    <PolicyID>ndrF8hjzl9FtFUdfaBwVvXP$sD1vDpRKNf</PolicyID>
    <EverSentBack>N</EverSentBack>
    <HasException>N</HasException>
    <WorkflowActionURL />
    <ExpenseEntriesList>
        <ExpenseEntry>
            <ReportEntryID>nE0avYnILN9mHdTErNSd2pH45udFoNQ$po</ReportEntryID>
            <ExpenseTypeID>BUSML</ExpenseTypeID>
            <ExpenseTypeName>Business Meal (attendees)</ExpenseTypeName>
            <SpendCategory>Entertainment</SpendCategory>
            <PaymentTypeCode>CASH</PaymentTypeCode>
            <PaymentTypeName>Cash</PaymentTypeName>
            <TransactionDate>2013-01-10T00:00:00</TransactionDate>
            <TransactionCurrencyName>US, Dollar</TransactionCurrencyName>
            <ExchangeRate>1.00000000000000</ExchangeRate>
            <TransactionAmount>50.00000000</TransactionAmount>
            <PostedAmount>50.00000000</PostedAmount>
            <ApprovedAmount />
            <BusinessPurpose />
            <VendorDescription />
            <LocationName>Washington</LocationName>
            <LocationSubdivision>US-DC</LocationSubdivision>
            <LocationCountry>US</LocationCountry>
            <OrgUnit1>Sales</OrgUnit1>
            <OrgUnit2 />
            <OrgUnit3 />
            <OrgUnit4 />
            <OrgUnit5 />
            <OrgUnit6 />
            <Custom1 />
            <Custom2 />
            <Custom3 />
            <Custom4 />
            <Custom5 />
            <Custom6 />
            <Custom7 />
            <Custom8 />
            <Custom9 />
            <Custom10 />
            <Custom11 />
            <Custom12 />
            <Custom13 />
            <Custom14 />
            <Custom15 />
            <Custom16 />
            <Custom17 />
            <Custom18 />
            <Custom19 />
            <Custom20 />
            <Custom21 />
            <Custom22 />
            <Custom23 />
            <Custom24 />
            <Custom25 />
            <Custom26 />
            <Custom27 />
            <Custom28 />
            <Custom29 />
            <Custom30 />
            <Custom31 />
            <Custom32 />
            <Custom33 />
            <Custom34 />
            <Custom35 />
            <Custom36 />
            <Custom37 />
            <Custom38 />
            <Custom39 />
            <Custom40 />
            <FormID>nAaT8$puKKOhs7h2wespCW7vyyxJAJcyb5</FormID>
            <EntryImageID />
            <HasVat>N</HasVat>
            <HasComments>N</HasComments>
            <CommentCount>0</CommentCount>
            <IsItemized>Y</IsItemized>
            <HasExceptions>N</HasExceptions>
            <IsPersonal>N</IsPersonal>
            <HasAttendees>Y</HasAttendees>
            <HasAllocation>N</HasAllocation>
            <IsCreditCardCharge>N</IsCreditCardCharge>
            <IsPersonalCardCharge>N</IsPersonalCardCharge>
            <ReceiptRequired>N</ReceiptRequired>
            <ImageRequired>N</ImageRequired>
            <E-ReceiptID />
            <LastModified>2013-01-11T01:59:52</LastModified>
            <ItemizationsList>
                <Itemization>
                    <ItemType>Regular</ItemType>
                    <ItemizationID>nE0avYnILN9mHdTErNSd2pH45udFoNQ$po</ItemizationID>
                    <ExpenseTypeID>BUSML</ExpenseTypeID>
                    <ExpenseTypeName>Business Meal (attendees)</ExpenseTypeName>
                    <TransactionDate>2013-01-10T00:00:00</TransactionDate>
                    <TransactionAmount>50.00000000</TransactionAmount>
                    <PostedAmount>50.00000000</PostedAmount>
                    <ApprovedAmount />
                    <BusinessPurpose />
                    <OrgUnit1>Sales</OrgUnit1>
                    <OrgUnit2 />
                    <OrgUnit3 />
                    <OrgUnit4 />
                    <OrgUnit5 />
                    <OrgUnit6 />
                    <Custom1 />
                    <Custom2 />
                    <Custom3 />
                    <Custom4 />
                    <Custom5 />
                    <Custom6 />
                    <Custom7 />
                    <Custom8 />
                    <Custom9 />
                    <Custom10 />
                    <Custom11 />
                    <Custom12 />
                    <Custom13 />
                    <Custom14 />
                    <Custom15 />
                    <Custom16 />
                    <Custom17 />
                    <Custom18 />
                    <Custom19 />
                    <Custom20 />
                    <Custom21 />
                    <Custom22 />
                    <Custom23 />
                    <Custom24 />
                    <Custom25 />
                    <Custom26 />
                    <Custom27 />
                    <Custom28 />
                    <Custom29 />
                    <Custom30 />
                    <Custom31 />
                    <Custom32 />
                    <Custom33 />
                    <Custom34 />
                    <Custom35 />
                    <Custom36 />
                    <Custom37 />
                    <Custom38 />
                    <Custom39 />
                    <Custom40 />
                    <HasComments>N</HasComments>
                    <CommentCount>0</CommentCount>
                    <IsPersonal>N</IsPersonal>
                    <LastModified>2013-01-11T01:59:52</LastModified>
                    <AllocationsList />
                    <AttendeesList>
                        <Attendee>
                            <AttendeeType>BUSGUEST</AttendeeType>
                            <FirstName>Pat</FirstName>
                            <LastName>Davis</LastName>
                            <Company />
                            <Title />
                            <ExternalID />
                            <Custom1 />
                            <Custom2 />
                            <Custom3 />
                            <Custom4 />
                            <Custom5 />
                            <Custom6 />
                            <Custom7 />
                            <Custom8 />
                            <Custom9 />
                            <Custom10 />
                            <Custom11 />
                            <Custom12 />
                            <Custom13 />
                            <Custom14 />
                            <Custom15 />
                            <Custom16 />
                            <Custom17 />
                            <Custom18 />
                            <Custom19 />
                            <Custom20 />
                            <HasExceptionsPrevYear>N</HasExceptionsPrevYear>
                            <HasExceptionsYTD>N</HasExceptionsYTD>
                            <IsDeleted>N</IsDeleted>
                            <OwnerEmpName>Miller, Chris</OwnerEmpName>
                            <TotalAmountPrevYear>0.00000000</TotalAmountPrevYear>
                            <TotalAmountYTD>0.00000000</TotalAmountYTD>
                            <VersionNumber>1</VersionNumber>
                            <AttendeeID>nFaAj038Hw$plfUD8be0I45wTx8$sMlTd$pP</AttendeeID>
                            <AttendeeTypeCode>BUSGUEST</AttendeeTypeCode>
                            <AttendeeOwnerID>cm@example.com</AttendeeOwnerID>
                            <CurrencyCode>USD</CurrencyCode>
                        </Attendee>
                    </AttendeesList>
                </Itemization>
                <Itemization>
                    <ItemType>Child</ItemType>
                    <ItemizationID>nE0avYnILN9g$s6lCFX0jFBWmHAiTYYf9C</ItemizationID>
                    <ExpenseTypeID>BRKFT</ExpenseTypeID>
                    <ExpenseTypeName>Breakfast</ExpenseTypeName>
                    <TransactionDate>2013-01-10T00:00:00</TransactionDate>
                    <TransactionAmount>50.00000000</TransactionAmount>
                    <PostedAmount>50.00000000</PostedAmount>
                    <ApprovedAmount>50.00000000</ApprovedAmount>
                    <BusinessPurpose />
                    <OrgUnit1>Sales</OrgUnit1>
                    <OrgUnit2 />
                    <OrgUnit3 />
                    <OrgUnit4 />
                    <OrgUnit5 />
                    <OrgUnit6 />
                    <Custom1 />
                    <Custom2 />
                    <Custom3 />
                    <Custom4 />
                    <Custom5 />
                    <Custom6 />
                    <Custom7 />
                    <Custom8 />
                    <Custom9 />
                    <Custom10 />
                    <Custom11 />
                    <Custom12 />
                    <Custom13 />
                    <Custom14 />
                    <Custom15 />
                    <Custom16 />
                    <Custom17 />
                    <Custom18 />
                    <Custom19 />
                    <Custom20 />
                    <Custom21 />
                    <Custom22 />
                    <Custom23 />
                    <Custom24 />
                    <Custom25 />
                    <Custom26 />
                    <Custom27 />
                    <Custom28 />
                    <Custom29 />
                    <Custom30 />
                    <Custom31 />
                    <Custom32 />
                    <Custom33 />
                    <Custom34 />
                    <Custom35 />
                    <Custom36 />
                    <Custom37 />
                    <Custom38 />
                    <Custom39 />
                    <Custom40 />
                    <HasComments>N</HasComments>
                    <CommentCount>0</CommentCount>
                    <IsPersonal>N</IsPersonal>
                    <LastModified>2013-01-11T01:59:52</LastModified>
                    <AllocationsList>
                        <Allocation>
                            <AllocationID>ngYn5SB4OUXgRV6P8VgsQQr88SaKYvbqz</AllocationID>
                            <Percentage>100.00000000%</Percentage>
                            <AccountCode1>AC_BRKFT1</AccountCode1>
                            <AccountCode2>AC_BRKFT2</AccountCode2>
                            <Custom1 />
                            <Custom2 />
                            <Custom3 />
                            <Custom4 />
                            <Custom5 />
                            <Custom6 />
                            <Custom7 />
                            <Custom8 />
                            <Custom9 />
                            <Custom10 />
                            <Custom11 />
                            <Custom12 />
                            <Custom13 />
                            <Custom14 />
                            <Custom15 />
                            <Custom16 />
                            <Custom17 />
                            <Custom18 />
                            <Custom19 />
                            <Custom20 />
                            <VATDataList />
                        </Allocation>
                    </AllocationsList>
                    <AttendeesList />
                </Itemization>
            </ItemizationsList>
            <UserLoginID>cm@example.com</UserLoginID>
        </ExpenseEntry>
    </ExpenseEntriesList>
    <Country>US</Country>
    <CountrySubdivision></CountrySubdivision>
    <ProcessingPaymentDate></ProcessingPaymentDate>
    <ReceiptsReceived>Y</ReceiptsReceived>
    <ReportOwner>
        <EmployeeID>cm@example.com</EmployeeID>
        <LastName>Chris</LastName>
        <FirstName>Miller</FirstName>
        <MiddleInitial></MiddleInitial>
        <EmployeeCustom21></EmployeeCustom21>
        <EmployeeOrgUnit1></EmployeeOrgUnit1>
        <EmployeeOrgUnit2></EmployeeOrgUnit2>
        <EmployeeOrgUnit3></EmployeeOrgUnit3>
        <EmployeeOrgUnit4></EmployeeOrgUnit4>
        <EmployeeOrgUnit5></EmployeeOrgUnit5>
        <EmployeeOrgUnit6></EmployeeOrgUnit6>
        <ReimbursementMethodCode>CNQRPAY</ReimbursementMethodCode>
    </ReportOwner>
</ReportDetails>
```

[1]: https://en.wikipedia.org/wiki/ISO_4217
[3]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
[4]: https://en.wikipedia.org/wiki/ISO_3166-2
[5]: https://developer.concur.com/users/users-resource/user-resource-get
[6]: https://developer.concur.com/expense-report/expense-group-configuration-resource/expense-group-configuration-resource-get
[7]: https://developer.concur.com/api-documentation/deprecated-features/get-list-reports-v20

redpajama_set_name: RedPajamaGithub


text:
set -e
set -u
set -o pipefail

source "tests/util/samples.sh"

# @setup profile=default

# Make sure default namespace is injected
kubectl label namespace default istio-injection=enabled || true

# Deploy sample and set up variable pointing to it
startup_sleep_sample
snip_before_you_begin_3

# Confirm we can access plain HTTP
snip_apply_simple

_wait_for_istio serviceentry default edition-cnn-com
_wait_for_istio virtualservice default edition-cnn-com

_verify_elided snip_curl_simple "$snip_curl_simple_out"

# Apply TLS origination config, check http and https content is correct
snip_apply_origination

_wait_for_istio virtualservice default edition-cnn-com
_wait_for_istio destinationrule default edition-cnn-com

_verify_elided snip_curl_origination_http "$snip_curl_origination_http_out"
_verify_elided snip_curl_origination_https "$snip_curl_origination_https_out"

# @cleanup
snip_cleanup_the_tls_origination_configuration_1
cleanup_sleep_sample


text:
package br.edu.ifmt.cba.java.teste;

public class ItemProduto {

	Produto produto;
	int qtde;

}


text:
package io.reactors

import io.reactors.concurrent.Frame
import scala.collection._
import scala.reflect.ClassTag

/** A pair of a channel and its event stream.
 *
 *  Allows closing the channel with its `seal` operation.
 */
class Connector[@spec(Int, Long, Double) T](
  private[reactors] val sharedChannel: Channel.Shared[T],
  private[reactors] val localChannel: Channel.Local[T],
  private[reactors] val queue: EventQueue[T],
  private[reactors] val frame: Frame,
  private[reactors] val extras: mutable.Map[Class[_], Any],
  val isDaemon: Boolean
) extends Identifiable {
  // Note: the `localChannel` reference should never be used for message forwarding.

  /** Retrieves the name of this connector.
   */
  def name = sharedChannel.url.anchor

  /** Returns the unique identifier of the channel.
   */
  def uid = localChannel.uid

  /** Returns the channel.
   */
  def channel: Channel[T] = sharedChannel

  /** Returns the event stream.
   */
  def events: Events[T] = queue.events

  /** Seals the channel, preventing it from delivering additional events.
   */
  def seal(): Boolean = {
    if (localChannel.isOpen) {
      frame.sealConnector(this)
      true
    } else false
  }

  /** Adds extra information to this connector.
   */
  def extra[C: ClassTag](v: C) = {
    extras(implicitly[ClassTag[C]].runtimeClass) = v
  }

  /** Returns extra information associated with this channel.
   */
  def extra[C: ClassTag]: C =
    extras(implicitly[ClassTag[C]].runtimeClass).asInstanceOf[C]

  private[reactors] def dequeue(): Int = queue.dequeue()
}


text:
/*
 * James A. Feister jfeister@udel.edu, openjaf@gmail.com
 * Project located at www.github.com/thegreatpissant/gemini.git
 * Class: CISC 360 - Computer Architecture
 * Instructor: Seth Morecraft
 * Web: http://www.cis.udel.edu/~morecraf/cisc360/
 *
 * Project 1: Gemini architecture, Implement the following
 * - GUI: Showing registers and instruction
 * - Parsing of program for syntax errors: Alert user of failure
 * - Running of program instructions, non bytecode translation
 * - Detection of memory access errors, Alert user of failure
 * - This is the base of the project.
 * *
 * Project 2: Gemini Enhancements, Implement the following
 * - Gemini Assembler: Create bytecode files from our Gemini assembly files
 * - Support Loading of binary files into the Gemini Simulator
 * - Add >=, <= Condition Jump checks
 * - Add JMP and RET commands for functions
 * - Add Cache implementation for One block Direct and 2 Way Set
 * - Extra credit: SETHI and SETLO instruction to handle 32 bit numbers
 * - Extra credit: Overflow on Multiplication and Divide
 * - Extra credit: JMP and RET instructions to support 25 levels of recursion
 * - Extra credit: Allow cache to support 4 memory block grabing at a time
 */

#ifndef GEMINIASSEMBLERCONTROL_H
#define GEMINIASSEMBLERCONTROL_H

#include "geminiassemblermodel.h"

#include <memory>
#include "geminiassemblerwindow.h"
class GeminiAssemblerWindow;

class GeminiAssemblerControl {
private:
  GeminiAssemblerModel *model;
  GeminiAssemblerWindow *view;

public:
  GeminiAssemblerControl();

  void setModel (GeminiAssemblerModel *m );
  void setView  (GeminiAssemblerWindow *v );

  bool convert_assembly_to_bytecode ();

  bool test_and_read_assembly_file();
  bool test_bytecode_file();
  bool validate_assembly_source();
  bool write_byte_code_to_file();
};

#endif // GEMINIASSEMBLERCONTROL_H


text:
import React, {Component, PropTypes} from 'react';
import WorkerItem from 'components/worker-item/worker-item';
import style from './stuff-employees-list.less';

export default class StuffEmployeesList extends Component {
  static propTypes = {
    items: PropTypes.arrayOf(
      PropTypes.shape({
        lastName: PropTypes.string,
        firstName: PropTypes.string,
        middleName: PropTypes.string,
        locked: PropTypes.bool,
        employeeId: PropTypes.number.isRequired
      })
    ),
    activeEmployeeId: PropTypes.number,
    onClickHandler: PropTypes.func,
    title: PropTypes.string
  };

  static defaultProps = {
    items: [],
    onClickHandler: ()=>{},
    title: '',
    activeEmployeeId: null
  };

  render () {

    const {items, onClickHandler, title, activeEmployeeId} = this.props;

    const onItemClick = (id) => {
      onClickHandler(id)
    };

    const getName = employee => {
      const {lastName, firstName, middleName} = employee;
      return `${lastName} ${firstName} ${middleName}`;
    };

    return (

{title}

          {items.map(item => {
            return <WorkerItem active={item.employeeId === activeEmployeeId} name={getName(item)} value={item.value} key={item.employeeId} isLock={item.locked} id={item.employeeId} onClickHandler={onItemClick.bind(this, item.employeeId)} ></WorkerItem>
          })}

    )
  }

}


text:
local Color = require "core.utils.color"

describe("Core utils", function()
    describe("Color", function()
        it("should be available for creation", function()
            local color = Color()
            assert.are.equal("table", type(color))
            assert.are.equal("Color", color.__type)
        end)

        it("should use default value (0x0, 0x0, 0x0, 0xFF)", function()
            local expected = { r = 0, g = 0, b = 0, a = 255 }
            local actual = Color()
            assert.are.same(expected, actual)
        end)

        it("should unpack to the initial values", function()
            local expected = { 10, 20, 30, 40 }

            local color = Color(unpack(expected))
            local actual = { color:unpack() }

            assert.are.same(expected, actual)
        end)
    end)

end)


text:
package horizon

import (
	"net/http"
	"net/url"

	"github.com/stellar/horizon/actions"
	"github.com/stellar/horizon/db"
	"github.com/stellar/horizon/httpx"
	"github.com/stellar/horizon/log"
	"github.com/zenazn/goji/web"
)

// Action is the "base type" for all actions in horizon.  It provides
// structs that embed it with access to the App struct.
//
// Additionally, this type is a trigger for go-codegen and causes
// the file at Action.tmpl to be instantiated for each struct that
// embeds Action.
type Action struct {
	actions.Base
	App *App
	Log *log.Entry
}

// Prepare sets the action's App field based upon the goji context
func (action *Action) Prepare(c web.C, w http.ResponseWriter, r *http.Request) {
	base := &action.Base
	base.Prepare(c, w, r)
	action.App = action.GojiCtx.Env["app"].(*App)

	if action.Ctx != nil {
		action.Log = log.Ctx(action.Ctx)
	} else {
		action.Log = log.DefaultLogger
	}
}

// GetPagingParams modifies the base GetPagingParams method to replace
// cursors that are "now" with the last seen ledger's cursor.
func (action *Action) GetPagingParams() (cursor string, order string, limit int32) {
	if action.Err != nil {
		return
	}

	cursor, order, limit = action.Base.GetPagingParams()

	if cursor == "now" {
		tid := db.TotalOrderID{
			LedgerSequence:   action.App.latestLedgerState.HorizonSequence,
			TransactionOrder: db.TotalOrderTransactionMask,
			OperationOrder:   db.TotalOrderOperationMask,
		}
		cursor = tid.String()
	}

	return
}

// GetPageQuery is a helper that returns a new db.PageQuery struct initialized
// using the results from a call to GetPagingParams()
func (action *Action) GetPageQuery() db.PageQuery {
	if action.Err != nil {
		return db.PageQuery{}
	}

	r, err := db.NewPageQuery(action.GetPagingParams())

	if err != nil {
		action.Err = err
	}

	return r
}

func (action *Action) ValidateCursorAsDefault() {
	if action.Err != nil {
		return
	}

	if action.GetString(actions.ParamCursor) == "now" {
		return
	}

	action.GetInt64(actions.ParamCursor)
}

func (action *Action) BaseURL() *url.URL {
	return httpx.BaseURL(action.Ctx)
}