# ExecuteAdvancedSearch - Advanced Documentation ## When to Use **This executes an ad-hoc advanced search** - use it when you are assembling a search dynamically (SearchType, Columns, Filters) instead of referencing a saved search by ID. If a saved search already exists and needs no filter changes beyond its parameters, use `GetAdvancedSearchResults` or `GetAdvancedSearchResultString` instead - they are cheaper and reuse a stored definition. **The normal use case: a saved search is almost right, but a filter value you need to change is not parameterized** - a date range, a staff ID, a value range the search's author never exposed as a parameter. Fetch the tree with `GetAdvancedSearchFilters`, change that one value in place, and execute the modified definition here. Nothing is saved - the definition is executed and discarded. ## The Escalation Ladder Reach for the cheapest rung that satisfies the request: 1. **Saved search as-is** - `GetAdvancedSearchResults` with no parameters. 2. **Parameterized filter** - `GetAdvancedSearchResults` with `ParametersJson`; replace the populated value slot of the filter found by `ParameterName`. 3. **Non-parameterized filter needs a different value** - fetch the tree with `GetAdvancedSearchFilters`, change the value in place, execute here. 4. **No suitable search exists** - assemble Columns and Filters from scratch and execute here. Last resort. Rungs 2, 3, and 4 are the same skill: the fetched definition is always the template, and the populated value slot is always the worked example. What varies is how much of it you change. **The round trip is a supported contract.** The output of `GetAdvancedSearchColumns` and `GetAdvancedSearchFilters` feeds into this endpoint unchanged - fetch from a sample search, modify, execute. **Changing a date value on a fetched filter object.** Date filter values such as `BetweenValueDate.StartValue` and `EndValue` come back from `GetAdvancedSearchFilters` as a `Date`. To change one on the object you pass to this endpoint, assign a `Date` or a `"yyyy-mm-dd"` string. Do not assign a `{ Value: ... }` object here - it fails with `dt.getFullYear is not a function`. The `{ Value: "yyyy-MM-dd" }` wrapper belongs only inside the `ParametersJson` string of `GetAdvancedSearchResultString` and `GetAdvancedSearchResults`. **Building from scratch (rung 4):** call `GetAdvancedSearchFields(fieldType, isColumnField)` to list the available fields for each entity - it is the catalog of valid fields; do not guess field names or IDs. Use it as the catalog of available fields, and the columns and filters of existing searches as worked examples of valid field chains. A `FieldList` is an ordered chain: every entry except the last carries `NextEntityName`, and the last entry - the leaf - carries the `DataType` and must not have a `NextEntityName`. Note that ad-hoc definitions are not validated field-by-field before execution: a malformed chain surfaces as a query build or execution error, not a friendly validation message. Copy working chains rather than inventing them. **Phone chain example.** A phone number on a related contact is a four-entry chain that must end at `PhoneContact.DisplayPhone`: `Claim.ReferralContactID` -> `Contact.Phone` -> `PhoneTypeContact.Preferred` (or a specific phone type name) -> `PhoneContact.DisplayPhone`. Stopping at `Contact.Phone` or at the phone type is a malformed chain. **Permissions.** This endpoint checks only that the caller is a member of the current company - it needs neither ManageAdvancedSearch nor ManageFirm. Callers without ManageFirm cannot list firm searches (`GetFirmAdvancedSearches*`) and cannot save firm searches; they run ad-hoc searches here instead. Saving any search needs ManageAdvancedSearch, and saving a firm search needs ManageFirm in addition. **Companion calling conventions** (positional args): - `GetAdvancedSearchColumns(advancedSearchId)` -> `SearchColumnInfo[]` - `DisplayName` plus `FieldList`, whose last entry (the leaf) carries `DataType` - `GetAdvancedSearchFilters(advancedSearchId)` -> a `FilterGroupInfo` tree - each filter carries `ParameterName`, `Operator`, and its value slots - `GetAdvancedSearchFields(fieldType, isColumnField)` -> `SearchField[]` - the field catalog NEVER call GetEndpointDetail for these three when assembling an ad-hoc search - everything the workflow needs from them is shown above. **Caching:** the result is identical in shape to `GetAdvancedSearchResults`, so all of its caching and aggregation guidance applies here unchanged - cache the packed `DataJson` before computing, return the batchId early, batch every question into the one run. See `GetAdvancedSearchResults` documentation. ## Overview Executes a caller-supplied advanced search against `Claim`, `Contact`, or `Person` data with no saved search record. Applies the same SQL construction, 30 second execution timeout, row-level claim security, time zone handling, and firm/company membership checks as the saved-search endpoints - the only difference is that Columns and Filters come directly from the request instead of being loaded from a saved `AdvancedSearchID`. ## Filtering and Columns on Child Entities A claim or contact has child entities (contacts, phones, notes, tasks, documents, ledger entries, correspondence). To filter on or return a child field, chain `FieldList` entries from the root to the child field: every entry except the last carries `NextEntityName`, the entity the chain moves into; the last entry carries the child field and its `DataType`. Copy each entry (`FieldName`, `FieldSource`, `FieldType`, `ID`, `DisplayName`, `NextEntityName`, `DataType`) from `GetAdvancedSearchFields`, calling it once per `FieldType` along the chain. - **Filter on a child field:** the filter's `FieldList` is the chain; the leaf entry also carries `Operator` and its value slot. A filter group whose chain crosses into a child entity matches when at least one matching child row exists. - **Child must NOT exist:** set `NotIn: true` on the `FilterGroupInfo` that holds the child filter. The group then matches when no matching child row exists. - **Column on a child field:** the column's `FieldList` is the same chain. **Row grain follows the columns.** With only root columns, each row is one root record. Adding a column from a child entity makes each row one child record - a claim with 23 requests returns 23 rows, and a claim with no request still returns one row with the child columns blank. Filters on child data never multiply rows: a search with only root columns, filtered on a child field, returns each matching root record once. **Child-level reports use this endpoint.** For a question about child records (request turnaround per provider, notes per staff member, documents per claim), run a `Claim` or `Contact` search with the child columns and aggregate the rows. Do not pull a firm-wide list endpoint such as `GetClaimRequestsForFirm`. **Child entities without a chain.** Some child entities, such as `ClaimRequest`, have no link entry in the `Claim` catalog. Copy the leaf from `GetAdvancedSearchFields` with that child as `FieldType` and use it as a one-entry `FieldList`. ## Parameters - **SearchType** - `"Claim"`, `"Contact"`, or `"Person"`. Determines which base view the search runs against, and what one row is when only root columns are used. Sent as a string, never an integer. Saved search type names such as `Claim Requests` or `Claim Notes` are not valid here - those types run as `Claim` (types starting with `Contact` run as `Contact`); use child columns to get child rows. - **Columns** - list of `SearchColumnInfo` describing the fields to return, in the same shape returned by `GetAdvancedSearchColumns` - see Allowed String Values below. - **Filters** - a `FilterGroupInfo` filter tree, in the same shape returned by `GetAdvancedSearchFilters` - see Allowed String Values below. - **PersonID** - ID of the person executing the search (used for security filtering and time zone conversion). Required. Pass the `UserId` returned by GetSystemInstructions. A value of 0 or a missing value is rejected with ArgumentOutOfRangeException "PersonID must be a positive value identifying the person executing the search." **At least 1 column and 1 filter are required.** An empty `Filters` tree (no `Children` and no `FieldList`) throws `To view results, your advanced search must have at least 1 filter.` - it does not mean "all rows". Minimal valid filter, `Status Exactly Matches Won` (Claim Status field ID 13979): ```json { "Condition": "and", "Children": [ { "Condition": "and", "FieldList": [ { "FieldName": "Status", "FieldSource": "Claim", "FieldType": "Entity", "DataType": "TextShort", "ID": 13979, "Operator": "Exactly Matches", "ValueString": "Won" } ] } ] } ``` ## Allowed String Values These fields are strings. Send the exact name below. Never send an integer. | Field | Allowed values | |---|---| | `SearchType` | `"Claim"`, `"Contact"`, `"Person"` | | `Condition` | `"and"`, `"or"` | | `SortDirection` | `null`, `"Ascending"`, `"Descending"` | | `AggregateFunction` | `"Count"`, `"Sum"`, `"Average"` | | `FieldType` | `"Entity"`, `"AdHoc"`, `"ClaimList"`, `"ContactList"`, `"Address"`, `"AddressType"`, `"Phone"`, `"PhoneType"`, `"Email"` | | `DataType` | `"TextShort"`, `"TextLong"`, `"Number"`, `"Decimal"`, `"Date"`, `"DateOfBirth"`, `"DateTime"`, `"Yes/No"`, `"Dropdown"`, `"Staff"`, `"Document"`, `"State"`, `"Hyperlink"`, `"Tags"`, `"Image"`, `"ClaimStaff"`, `"ClaimRole"` | | `Operator` | Depends on the filter's `DataType` - see Operators by DataType below. | Copy `FieldType` and `DataType` from `GetAdvancedSearchFields` or an existing search. Do not choose them. ## Operators by DataType Send the operator text exactly as shown (matching is case-insensitive). Use only the operators listed for the filter's `DataType`; any other operator does not produce the intended rows. | DataType | Operators | |---|---| | `Number`, `Decimal` | `Is Blank`, `Is Not Blank`, `Exactly Matches`, `Is Not Equal To`, `Greater Than`, `Greater Than or Equal`, `Less Than`, `Less Than or Equal`, `Between Inclusive`, `Is in List` | | `TextShort`, `TextLong`, `Hyperlink` | `Is Blank`, `Is Not Blank`, `Exactly Matches`, `Is Not Equal To`, `Begins With`, `Ends With`, `Contains`, `Is in List`, `Is not in List` | | `Document` | `Is Blank`, `Is Not Blank`, `Exactly Matches`, `Is Not Equal To`, `Begins With`, `Ends With`, `Contains`, `Is in List` | | `Yes/No` | `Is Blank`, `Is Not Blank`, `Yes`, `No` | | `Date`, `DateTime` | `Is Blank`, `Is Not Blank`, `Exactly Matches`, `Is Not Equal To`, `Greater Than`, `Greater Than or Equal`, `Less Than`, `Less Than or Equal`, `Between Inclusive`, `Is in List`, `In the Last X Days`, `In the Last X Weeks`, `In the Last X Months`, `In the Last X Quarters`, `In the Last X Years`, `In the Next Y Days`, `In the Past`, `In the Future`, `Today`, `Last Month`, `Month to Date`, `This Month`, `Last Year`, `Year to Date`, `This Year` | | `DateOfBirth` | `Is Blank`, `Is Not Blank`, `Today`, `In X Days`, `Last Month`, `This Month`, `Next Month`, `Between Inclusive`, `X Years Or Younger`, `Y Years Or Older` | | `Dropdown`, `State` | `Is Blank`, `Is Not Blank`, `Exactly Matches`, `Is Not Equal To`, `Is in List`, `Is not in List` | | `Staff`, `Tags` | `Is Blank`, `Is Not Blank`, `Is in List`, `Is not in List` | | `ClaimStaff` | `Is in List`, `Is any Role` | | `ClaimRole` | `Is Blank`, `Is Not Blank`, `Is in List` | | `Image` | `Is Blank`, `Is Not Blank` | `Is not in List` exists only for `TextShort`, `TextLong`, `Hyperlink`, `Dropdown`, `State`, `Staff`, and `Tags`. For `Number`, `Decimal`, `Date`, `DateTime`, and `Document`, use the `NotIn` flag on the filter group instead (see Filtering and Columns on Child Entities). **List operators** (`Is in List`, `Is not in List`): put the values in the `ListValue*` array that matches the `DataType`, never in a single `Value*` slot. `TextShort`, `TextLong`, `Hyperlink`, `Document`, `State`, `Tags`, and `Dropdown` on a non-`Entity` field use `ListValueString`; `Number` and `Decimal` use `ListValueNumber`; `Date` uses `ListValueDate`; `DateTime` uses `ListValueDateTime`; `Dropdown` on an `Entity` field and `Staff` use `ListValueIDName` (items are `{ ID, Name }`); `ClaimStaff` and `ClaimRole` use `ListValueStaff` (`ClaimStaff` `Is in List` also needs `ListValueRole`). There is no `ValueList` property. Example, `Status` is Won or Open: ```json { "FieldName": "Status", "FieldSource": "Claim", "FieldType": "Entity", "DataType": "TextShort", "ID": 13979, "Operator": "Is in List", "ListValueString": ["Won", "Open"] } ``` For every value slot by `DataType` and `Operator`, see the Required Slot table in `GetAdvancedSearchResults` documentation. **Columns: what is required.** To execute, each column needs a `FieldList`; `DisplayName` names the result column. `Width`, `AggregateFunction`, and `Format` are not checked when executing. When columns are saved with a search, each column must have a `DisplayName`, a `Width` of at least 1, an `AggregateFunction`, a `Format`, and a `FieldList` whose every entry has a `DisplayName`; `SortDirection` must be `null`, `"Ascending"`, or `"Descending"`. ## Return Structure Returns an `AdvancedSearchResults` object, identical in shape to `GetAdvancedSearchResults`: - **Columns** - field names, types, and display names for each column in the result set - **DataJson** - list of JSON-serialized `row.ItemArray` values (one entry per row) - **`_cid` column** - Claim searches get a hidden first column `_cid` (claim ID) ahead of the columns you passed; Contact searches get `_bcid` (contact ID). It is in `Columns` and is index 0 of every row. Map values by `Columns[i].DisplayName`, never by the position of the columns you requested. Column `SortDirection` is not applied (no ORDER BY in the generated SQL). ## Script Example ```javascript async () => { const columns = [ { DisplayName: "Claim Name", Width: 150, AggregateFunction: "Count", SortDirection: null, FieldList: [{ DisplayName: "Name", FieldName: "Name", FieldSource: "Claim", FieldType: "Entity", DataType: "TextShort", ID: 13917 }] } ]; const filters = { Condition: "and", Children: [ { Condition: "and", FieldList: [{ FieldName: "Status", FieldSource: "Claim", FieldType: "Entity", DataType: "TextShort", ID: 13979, Operator: "Exactly Matches", ValueString: "Open" }] } ] }; const results = await SecureApi.ExecuteAdvancedSearch("Claim", columns, filters, 8514); const colNames = results.Columns.map(c => c.DisplayName); const rows = results.DataJson.map(json => { const vals = JSON.parse(json); const row = {}; colNames.forEach((name, i) => row[name] = vals[i]); return row; }); return { total: rows.length, rows }; } ```