Skip to content

Persons

Interaction Dates

The get() method supports fetching interaction date summaries for a person using the with_interaction_dates parameter. When enabled, the returned Person object will have its interaction_dates and interactions fields populated with:

  • Last meeting date: When the last calendar event with this person occurred
  • Next meeting date: When the next scheduled calendar event is
  • Last email date: When the last email exchange happened
  • Last interaction date: The most recent interaction of any type
from affinity import Affinity
from affinity.types import PersonId

with Affinity(api_key="YOUR_API_KEY") as client:
    # Fetch person with interaction dates
    person = client.persons.get(
        PersonId(456),
        with_interaction_dates=True,
        with_interaction_persons=True,  # Include person IDs for each interaction
    )

    # Access interaction data
    if person.interaction_dates:
        print(f"Last meeting: {person.interaction_dates.last_event_date}")
        print(f"Next meeting: {person.interaction_dates.next_event_date}")
        print(f"Last email: {person.interaction_dates.last_email_date}")

    # Access team member IDs from interactions
    if person.interactions and person.interactions.last_event:
        team_ids = person.interactions.last_event.person_ids
        print(f"Last meeting attendees: {team_ids}")

Service for managing persons (contacts).

Uses V2 API for efficient reading with field selection, V1 API for create/update/delete operations.

Source code in affinity/services/persons.py
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
class PersonService:
    """
    Service for managing persons (contacts).

    Uses V2 API for efficient reading with field selection,
    V1 API for create/update/delete operations.
    """

    def __init__(self, client: HTTPClient):
        self._client = client

    # =========================================================================
    # Read Operations (V2 API)
    # =========================================================================

    def list(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[Person]:
        """
        Get a page of persons.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include
            filter: V2 filter expression string, or a FilterExpression built via `affinity.F`
            limit: Maximum number of results
            cursor: Cursor to resume pagination (opaque; obtained from prior responses)

        Returns:
            Paginated response with persons
        """
        validate_entity_field_types(field_types, endpoint="person")
        if cursor is not None:
            if any(p is not None for p in (ids, field_ids, field_types, filter, limit)):
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context. Start a new pagination sequence without a cursor to change "
                    "parameters."
                )
            data = self._client.get_url(cursor)
        else:
            params: dict[str, Any] = {}
            if ids:
                params["ids"] = [int(id_) for id_ in ids]
            if field_ids:
                params["fieldIds"] = [str(field_id) for field_id in field_ids]
            if field_types:
                params["fieldTypes"] = [field_type.value for field_type in field_types]
            if filter is not None:
                filter_text = str(filter).strip()
                if filter_text:
                    params["filter"] = filter_text
            if limit:
                params["limit"] = limit
            data = self._client.get("/persons", params=params or None)

        return PaginatedResponse[Person](
            data=[Person.model_validate(p) for p in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    def get_first(
        self,
        *,
        filter: str | FilterExpression | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
    ) -> Person | None:
        """
        Get the first person matching the filter, or None if no match.

        This is a convenience method equivalent to:
            page = client.persons.list(filter=filter, limit=1)
            return page.data[0] if page.data else None

        Args:
            filter: V2 filter expression
            field_ids: Specific field IDs to include
            field_types: Field types to include

        Returns:
            First matching Person, or None if no results.
        """
        page = self.list(
            filter=filter,
            field_ids=field_ids,
            field_types=field_types,
            limit=1,
        )
        return page.data[0] if page.data else None

    def pages(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> Iterator[PaginatedResponse[Person]]:
        """
        Iterate person pages (not items), yielding `PaginatedResponse[Person]`.

        Useful for ETL scripts that need checkpoint/resume via `page.next_cursor`.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include
            filter: V2 filter expression string or FilterExpression
            limit: Maximum results per page
            cursor: Cursor to resume pagination

        Yields:
            PaginatedResponse[Person] for each page
        """
        other_params = (ids, field_ids, field_types, filter, limit)
        if cursor is not None and any(p is not None for p in other_params):
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query context. "
                "Start a new pagination sequence without a cursor to change parameters."
            )
        requested_cursor = cursor
        page = (
            self.list(cursor=cursor)
            if cursor is not None
            else self.list(
                ids=ids, field_ids=field_ids, field_types=field_types, filter=filter, limit=limit
            )
        )
        while True:
            yield page
            if not page.has_next:
                return
            next_cursor = page.next_cursor
            if next_cursor is None or next_cursor == requested_cursor:
                return
            requested_cursor = next_cursor
            page = self.list(cursor=next_cursor)

    def all(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
    ) -> Iterator[Person]:
        """
        Iterate through all persons with automatic pagination.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include
            field_types: Field types to include
            filter: V2 filter expression

        Yields:
            Person objects
        """

        def fetch_page(next_url: str | None) -> PaginatedResponse[Person]:
            if next_url:
                data = self._client.get_url(next_url)
                return PaginatedResponse[Person](
                    data=[Person.model_validate(p) for p in data.get("data", [])],
                    pagination=PaginationInfo.model_validate(data.get("pagination", {})),
                )
            return self.list(
                ids=ids,
                field_ids=field_ids,
                field_types=field_types,
                filter=filter,
            )

        return PageIterator(fetch_page)

    def iter(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
    ) -> Iterator[Person]:
        """
        Auto-paginate all persons.

        Alias for `all()` (FR-006 public contract).
        """
        return self.all(ids=ids, field_ids=field_ids, field_types=field_types, filter=filter)

    def get(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """
        Get a single person by ID.

        Args:
            person_id: The person ID
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            include_field_values: If True, fetch embedded field values. This saves
                one API call when you need both person info and field values.
                Cannot be combined with field_ids/field_types.
            retries: Number of retries on 404 NotFoundError. Default is 0 (fail fast).
                Set to 2-3 if calling immediately after create() to handle eventual
                consistency lag.
            with_interaction_dates: Include interaction date summaries (last/next
                meeting dates, email dates).
            with_interaction_persons: Include person IDs for each interaction.
                Only applies when with_interaction_dates=True.

        Returns:
            Person object with requested field data.
            When include_field_values=True, the Person will have a `field_values`
            attribute containing the list of FieldValue objects.
            When with_interaction_dates=True, the Person will have interaction_dates
            and interactions populated.

        Raises:
            NotFoundError: If person does not exist after all retries.
            ValueError: If include_field_values is combined with field_ids/field_types.

        Note:
            When combining with_interaction_dates with field_ids/field_types,
            two API calls are made internally and the results are merged.
        """
        return self._get_with_retry(
            person_id,
            field_ids=field_ids,
            field_types=field_types,
            include_field_values=include_field_values,
            retries=retries,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
        )

    def _get_with_retry(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """Internal: get with retry logic."""
        last_error: NotFoundError | None = None
        attempts = retries + 1  # retries=0 means 1 attempt

        for attempt in range(attempts):
            try:
                return self._get_impl(
                    person_id,
                    field_ids=field_ids,
                    field_types=field_types,
                    include_field_values=include_field_values,
                    with_interaction_dates=with_interaction_dates,
                    with_interaction_persons=with_interaction_persons,
                )
            except NotFoundError as e:
                last_error = e
                if attempt < attempts - 1:  # Don't sleep after last attempt
                    time.sleep(0.5 * (attempt + 1))  # 0.5s, 1s, 1.5s backoff

        # V1 fallback: If V2 returned 404, try V1 API (handles V1→V2 sync delays)
        # Skip if already using V1 path (include_field_values or with_interaction_dates)
        if last_error is not None and not include_field_values and not with_interaction_dates:
            try:
                v1_data = self._client.get(f"/persons/{person_id}", v1=True)
                normalized = _normalize_v1_person_response(v1_data)
                return Person.model_validate(normalized)
            except NotFoundError:
                pass  # V1 also failed, raise original V2 error

        raise last_error  # type: ignore[misc]

    def _get_impl(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """Internal: actual get implementation."""
        has_field_filters = field_ids is not None or field_types is not None

        # include_field_values returns embedded field values, which is incompatible
        # with field_ids/field_types filtering (different data structures)
        if include_field_values and has_field_filters:
            raise ValueError(
                "Cannot combine 'include_field_values' with 'field_ids' or 'field_types'. "
                "Use include_field_values alone for embedded field values, or use "
                "field_ids/field_types alone for filtered fields."
            )

        # Path 1: include_field_values (V1 API, may include interaction dates)
        if include_field_values:
            v1_params: dict[str, Any] = {}
            if with_interaction_dates:
                v1_params["with_interaction_dates"] = True
            if with_interaction_persons:
                v1_params["with_interaction_persons"] = True

            data = self._client.get(
                f"/persons/{person_id}",
                params=v1_params or None,
                v1=True,
            )

            field_values_data = data.get("field_values", [])
            # V1 embedded field_values don't include entityId; add it before validation
            field_values = [
                FieldValue.model_validate({**fv, "entityId": int(person_id)})
                for fv in field_values_data
            ]
            normalized = _normalize_v1_person_response(data)
            person = Person.model_validate(normalized)
            object.__setattr__(person, "field_values", field_values)
            return person

        # Path 2: with_interaction_dates (may need merge if field filters present)
        if with_interaction_dates:
            v1_params = {"with_interaction_dates": True}
            if with_interaction_persons:
                v1_params["with_interaction_persons"] = True

            interaction_data = self._client.get(
                f"/persons/{person_id}",
                params=v1_params,
                v1=True,
            )

            # If field filtering is also requested, fetch filtered fields and merge
            if has_field_filters:
                v2_params: dict[str, Any] = {}
                if field_ids:
                    v2_params["fieldIds"] = [str(fid) for fid in field_ids]
                if field_types:
                    v2_params["fieldTypes"] = [ft.value for ft in field_types]

                filtered_data = self._client.get(
                    f"/persons/{person_id}",
                    params=v2_params,
                )

                # Merge: filtered fields + interaction data
                filtered_data["interaction_dates"] = interaction_data.get("interaction_dates")
                filtered_data["interactions"] = interaction_data.get("interactions")
                return Person.model_validate(filtered_data)

            # No field filtering, normalize and return V1 data
            normalized = _normalize_v1_person_response(interaction_data)
            return Person.model_validate(normalized)

        # Path 3: Standard path (supports field filtering)
        params: dict[str, Any] = {}
        if field_ids:
            params["fieldIds"] = [str(field_id) for field_id in field_ids]
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]

        data = self._client.get(
            f"/persons/{person_id}",
            params=params or None,
        )
        return Person.model_validate(data)

    def get_list_entries(
        self,
        person_id: PersonId,
    ) -> PaginatedResponse[ListEntry]:
        """Get all list entries for a person across all lists."""
        data = self._client.get(f"/persons/{person_id}/list-entries")

        return PaginatedResponse[ListEntry](
            data=[ListEntry.model_validate(e) for e in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    def get_lists(
        self,
        person_id: PersonId,
    ) -> PaginatedResponse[ListSummary]:
        """Get all lists that contain this person."""
        data = self._client.get(f"/persons/{person_id}/lists")

        return PaginatedResponse[ListSummary](
            data=[ListSummary.model_validate(item) for item in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    def get_fields(
        self,
        *,
        field_types: Sequence[FieldType] | None = None,
    ) -> builtins.list[FieldMetadata]:
        """
        Get metadata about person fields.

        Cached for performance.
        """
        params: dict[str, Any] = {}
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]

        data = self._client.get(
            "/persons/fields",
            params=params or None,
            cache_key=f"person_fields:{','.join(field_types or [])}",
            cache_ttl=300,
        )

        return [FieldMetadata.model_validate(f) for f in data.get("data", [])]

    # =========================================================================
    # Associations (V1 API)
    # =========================================================================

    def get_associated_company_ids(
        self,
        person_id: PersonId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[CompanyId]:
        """
        Get associated company IDs for a person.

        V1-only: V2 does not expose person -> company associations directly.
        Uses GET `/persons/{id}` (V1) and returns `organization_ids`.

        Args:
            person_id: The person ID
            max_results: Maximum number of company IDs to return

        Returns:
            List of CompanyId values associated with this person

        Note:
            The Person model already has `company_ids` populated from V1's
            `organizationIds` field. This method provides API parity with
            `CompanyService.get_associated_person_ids()`.
        """
        data = self._client.get(f"/persons/{person_id}", v1=True)
        # Defensive: handle potential {"person": {...}} wrapper
        # (consistent with CompanyService.get_associated_person_ids pattern)
        person = data.get("person") if isinstance(data, dict) else None
        source = person if isinstance(person, dict) else data
        org_ids = None
        if isinstance(source, dict):
            org_ids = source.get("organization_ids") or source.get("organizationIds")

        if not isinstance(org_ids, list):
            return []

        ids = [CompanyId(int(cid)) for cid in org_ids if cid is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    def get_associated_company_ids_batch(
        self,
        person_ids: Sequence[PersonId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[PersonId, builtins.list[CompanyId]]:
        """
        Get company associations for multiple persons.

        Makes one V1 API call per person.

        Args:
            person_ids: Sequence of person IDs to fetch
            on_error: How to handle errors - "raise" (default) or "skip" failed IDs

        Returns:
            Dict mapping person_id -> list of company_ids

        Raises:
            AffinityError: If on_error="raise" and any fetch fails.

        Example:
            associations = client.persons.get_associated_company_ids_batch(person_ids)
            all_company_ids = set()
            for company_ids in associations.values():
                all_company_ids.update(company_ids)
        """
        result: dict[PersonId, builtins.list[CompanyId]] = {}
        for person_id in person_ids:
            try:
                result[person_id] = self.get_associated_company_ids(person_id)
            except AffinityError:
                if on_error == "raise":
                    raise
                # skip: continue without this person
            except Exception as e:
                if on_error == "raise":
                    raise AffinityError(
                        f"Failed to get associations for person {person_id}: {e}"
                    ) from e
                # skip: continue without this person
        return result

    def get_associated_opportunity_ids(
        self,
        person_id: PersonId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[OpportunityId]:
        """
        Get associated opportunity IDs for a person.

        V1-only: V2 does not expose person -> opportunity associations directly.
        Uses GET `/persons/{id}` (V1) and returns `opportunity_ids`.

        Args:
            person_id: The person ID
            max_results: Maximum number of opportunity IDs to return

        Returns:
            List of OpportunityId values associated with this person

        Note:
            The Person model already has `opportunity_ids` populated from V1's
            `opportunityIds` field. This method provides API parity with
            `OpportunityService.get_associated_person_ids()`.
        """
        data = self._client.get(f"/persons/{person_id}", v1=True)
        # Defensive: handle potential {"person": {...}} wrapper
        person = data.get("person") if isinstance(data, dict) else None
        source = person if isinstance(person, dict) else data
        opp_ids = None
        if isinstance(source, dict):
            opp_ids = source.get("opportunity_ids") or source.get("opportunityIds")

        if not isinstance(opp_ids, list):
            return []

        ids = [OpportunityId(int(oid)) for oid in opp_ids if oid is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    def get_associated_opportunity_ids_batch(
        self,
        person_ids: Sequence[PersonId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[PersonId, builtins.list[OpportunityId]]:
        """
        Get opportunity associations for multiple persons.

        Makes one V1 API call per person.

        Args:
            person_ids: Sequence of person IDs to fetch
            on_error: How to handle errors - "raise" (default) or "skip" failed IDs

        Returns:
            Dict mapping person_id -> list of opportunity_ids

        Raises:
            AffinityError: If on_error="raise" and any fetch fails.
        """
        result: dict[PersonId, builtins.list[OpportunityId]] = {}
        for person_id in person_ids:
            try:
                result[person_id] = self.get_associated_opportunity_ids(person_id)
            except AffinityError:
                if on_error == "raise":
                    raise
                # skip: continue without this person
            except Exception as e:
                if on_error == "raise":
                    raise AffinityError(
                        f"Failed to get associations for person {person_id}: {e}"
                    ) from e
                # skip: continue without this person
        return result

    # =========================================================================
    # Search (V1 API)
    # =========================================================================

    def search(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> PaginatedResponse[Person]:
        """
        Search for persons by name or email.

        Uses V1 API for search functionality.

        Args:
            term: Search term (name or email)
            with_interaction_dates: Include interaction date data
            with_interaction_persons: Include persons for interactions
            with_opportunities: Include associated opportunity IDs
            page_size: Results per page (max 500)
            page_token: Pagination token

        Returns:
            PaginatedResponse[Person] with matching persons and pagination info
        """
        params: dict[str, Any] = {"term": term}
        if with_interaction_dates:
            params["with_interaction_dates"] = True
        if with_interaction_persons:
            params["with_interaction_persons"] = True
        if with_opportunities:
            params["with_opportunities"] = True
        if page_size:
            params["page_size"] = page_size
        if page_token:
            params["page_token"] = page_token

        data = self._client.get("/persons", params=params, v1=True)
        items = [Person.model_validate(p) for p in data.get("persons", [])]
        return PaginatedResponse[Person](
            data=items,
            next_page_token=data.get("next_page_token"),
        )

    def search_pages(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> Iterator[PaginatedResponse[Person]]:
        """
        Iterate V1 person-search result pages.

        Useful for scripts that need checkpoint/resume via `next_page_token`.

        Args:
            term: Search term (name or email)
            with_interaction_dates: Include interaction date data
            with_interaction_persons: Include persons for interactions
            with_opportunities: Include associated opportunity IDs
            page_size: Results per page (max 500)
            page_token: Resume from this pagination token

        Yields:
            PaginatedResponse[Person] for each page
        """
        requested_token = page_token
        page = self.search(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=page_token,
        )
        while True:
            yield page
            next_token = page.next_page_token
            if not next_token or next_token == requested_token:
                return
            requested_token = next_token
            page = self.search(
                term,
                with_interaction_dates=with_interaction_dates,
                with_interaction_persons=with_interaction_persons,
                with_opportunities=with_opportunities,
                page_size=page_size,
                page_token=next_token,
            )

    def search_all(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> Iterator[Person]:
        """
        Iterate all V1 person-search results with automatic pagination.

        Args:
            term: Search term (name or email)
            with_interaction_dates: Include interaction date data
            with_interaction_persons: Include persons for interactions
            with_opportunities: Include associated opportunity IDs
            page_size: Results per page (max 500)
            page_token: Resume from this pagination token

        Yields:
            Person objects matching the search term
        """
        for page in self.search_pages(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=page_token,
        ):
            yield from page.data

    def resolve(
        self,
        *,
        email: str | None = None,
        name: str | None = None,
    ) -> Person | None:
        """
        Find a single person by email or name.

        This is a convenience helper that searches and returns the first exact match,
        or None if not found. Uses V1 search internally.

        Args:
            email: Email address to search for
            name: Person name to search for (first + last)

        Returns:
            The matching Person, or None if not found

        Raises:
            ValueError: If neither email nor name is provided

        Note:
            This auto-paginates V1 search results until a match is found.
            If multiple matches are found, returns the first one. For full
            disambiguation, use resolve_all() or search() directly.
        """
        if not email and not name:
            raise ValueError("Must provide either email or name")

        term = email or name or ""
        for page in self.search_pages(term, page_size=10):
            for person in page.data:
                if _person_matches(person, email=email, name=name):
                    return person

        return None

    def resolve_all(
        self,
        *,
        email: str | None = None,
        name: str | None = None,
    ) -> builtins.list[Person]:
        """
        Find all persons matching an email or name.

        Notes:
        - This auto-paginates V1 search results to collect exact matches.
        - Unlike resolve(), this returns every match in server-provided order.
        """
        if not email and not name:
            raise ValueError("Must provide either email or name")

        term = email or name or ""
        matches: builtins.list[Person] = []
        for page in self.search_pages(term, page_size=10):
            for person in page.data:
                if _person_matches(person, email=email, name=name):
                    matches.append(person)
        return matches

    # =========================================================================
    # Write Operations (V1 API)
    # =========================================================================

    def create(self, data: PersonCreate) -> Person:
        """
        Create a new person.

        Note:
            Creates use V1 API, while reads use V2 API. Due to eventual consistency
            between V1 and V2, a `get()` call immediately after `create()` may return
            404 NotFoundError. If you need to read immediately after creation, either:
            - Use the Person object returned by this method (it contains the created data)
            - Add a short delay (100-500ms) before calling get()
            - Implement retry logic in your application

        Raises:
            ValidationError: If email conflicts with existing person
        """
        payload = data.model_dump(by_alias=True, mode="json")
        if not data.company_ids:
            payload.pop("organization_ids", None)

        result = self._client.post("/persons", json=payload, v1=True)

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return Person.model_validate(result)

    def update(
        self,
        person_id: PersonId,
        data: PersonUpdate,
    ) -> Person:
        """
        Update an existing person.

        Note: To add emails/organizations, include existing values plus new ones.
        """
        payload = data.model_dump(
            by_alias=True,
            mode="json",
            exclude_unset=True,
            exclude_none=True,
        )

        result = self._client.put(
            f"/persons/{person_id}",
            json=payload,
            v1=True,
        )

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return Person.model_validate(result)

    def delete(self, person_id: PersonId) -> bool:
        """Delete a person (also deletes associated field values)."""
        result = self._client.delete(f"/persons/{person_id}", v1=True)

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return bool(result.get("success", False))

    # =========================================================================
    # Merge Operations (V2 BETA)
    # =========================================================================

    def merge(
        self,
        primary_id: PersonId,
        duplicate_id: PersonId,
    ) -> str:
        """
        Merge a duplicate person into a primary person.

        Returns a task URL to check merge status.
        """
        if not self._client.enable_beta_endpoints:
            raise BetaEndpointDisabledError(
                "Person merge is a beta endpoint; set enable_beta_endpoints=True to use it."
            )
        result = self._client.post(
            "/person-merges",
            json={
                "primaryPersonId": int(primary_id),
                "duplicatePersonId": int(duplicate_id),
            },
        )
        return str(result.get("taskUrl", ""))

    def get_merge_status(self, task_id: str) -> MergeTask:
        """Check the status of a merge operation."""
        data = self._client.get(f"/tasks/person-merges/{task_id}")
        return MergeTask.model_validate(data)

all(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None) -> Iterator[Person]

Iterate through all persons with automatic pagination.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression

None

Yields:

Type Description
Person

Person objects

Source code in affinity/services/persons.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def all(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
) -> Iterator[Person]:
    """
    Iterate through all persons with automatic pagination.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include
        field_types: Field types to include
        filter: V2 filter expression

    Yields:
        Person objects
    """

    def fetch_page(next_url: str | None) -> PaginatedResponse[Person]:
        if next_url:
            data = self._client.get_url(next_url)
            return PaginatedResponse[Person](
                data=[Person.model_validate(p) for p in data.get("data", [])],
                pagination=PaginationInfo.model_validate(data.get("pagination", {})),
            )
        return self.list(
            ids=ids,
            field_ids=field_ids,
            field_types=field_types,
            filter=filter,
        )

    return PageIterator(fetch_page)

create(data: PersonCreate) -> Person

Create a new person.

Note

Creates use V1 API, while reads use V2 API. Due to eventual consistency between V1 and V2, a get() call immediately after create() may return 404 NotFoundError. If you need to read immediately after creation, either: - Use the Person object returned by this method (it contains the created data) - Add a short delay (100-500ms) before calling get() - Implement retry logic in your application

Raises:

Type Description
ValidationError

If email conflicts with existing person

Source code in affinity/services/persons.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
def create(self, data: PersonCreate) -> Person:
    """
    Create a new person.

    Note:
        Creates use V1 API, while reads use V2 API. Due to eventual consistency
        between V1 and V2, a `get()` call immediately after `create()` may return
        404 NotFoundError. If you need to read immediately after creation, either:
        - Use the Person object returned by this method (it contains the created data)
        - Add a short delay (100-500ms) before calling get()
        - Implement retry logic in your application

    Raises:
        ValidationError: If email conflicts with existing person
    """
    payload = data.model_dump(by_alias=True, mode="json")
    if not data.company_ids:
        payload.pop("organization_ids", None)

    result = self._client.post("/persons", json=payload, v1=True)

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return Person.model_validate(result)

delete(person_id: PersonId) -> bool

Delete a person (also deletes associated field values).

Source code in affinity/services/persons.py
966
967
968
969
970
971
972
973
def delete(self, person_id: PersonId) -> bool:
    """Delete a person (also deletes associated field values)."""
    result = self._client.delete(f"/persons/{person_id}", v1=True)

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return bool(result.get("success", False))

get(person_id: PersonId, *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, include_field_values: bool = False, retries: int = 0, with_interaction_dates: bool = False, with_interaction_persons: bool = False) -> Person

Get a single person by ID.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include (e.g., ["enriched", "global"])

None
include_field_values bool

If True, fetch embedded field values. This saves one API call when you need both person info and field values. Cannot be combined with field_ids/field_types.

False
retries int

Number of retries on 404 NotFoundError. Default is 0 (fail fast). Set to 2-3 if calling immediately after create() to handle eventual consistency lag.

0
with_interaction_dates bool

Include interaction date summaries (last/next meeting dates, email dates).

False
with_interaction_persons bool

Include person IDs for each interaction. Only applies when with_interaction_dates=True.

False

Returns:

Type Description
Person

Person object with requested field data.

Person

When include_field_values=True, the Person will have a field_values

Person

attribute containing the list of FieldValue objects.

Person

When with_interaction_dates=True, the Person will have interaction_dates

Person

and interactions populated.

Raises:

Type Description
NotFoundError

If person does not exist after all retries.

ValueError

If include_field_values is combined with field_ids/field_types.

Note

When combining with_interaction_dates with field_ids/field_types, two API calls are made internally and the results are merged.

Source code in affinity/services/persons.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def get(
    self,
    person_id: PersonId,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    include_field_values: bool = False,
    retries: int = 0,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
) -> Person:
    """
    Get a single person by ID.

    Args:
        person_id: The person ID
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        include_field_values: If True, fetch embedded field values. This saves
            one API call when you need both person info and field values.
            Cannot be combined with field_ids/field_types.
        retries: Number of retries on 404 NotFoundError. Default is 0 (fail fast).
            Set to 2-3 if calling immediately after create() to handle eventual
            consistency lag.
        with_interaction_dates: Include interaction date summaries (last/next
            meeting dates, email dates).
        with_interaction_persons: Include person IDs for each interaction.
            Only applies when with_interaction_dates=True.

    Returns:
        Person object with requested field data.
        When include_field_values=True, the Person will have a `field_values`
        attribute containing the list of FieldValue objects.
        When with_interaction_dates=True, the Person will have interaction_dates
        and interactions populated.

    Raises:
        NotFoundError: If person does not exist after all retries.
        ValueError: If include_field_values is combined with field_ids/field_types.

    Note:
        When combining with_interaction_dates with field_ids/field_types,
        two API calls are made internally and the results are merged.
    """
    return self._get_with_retry(
        person_id,
        field_ids=field_ids,
        field_types=field_types,
        include_field_values=include_field_values,
        retries=retries,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
    )

get_associated_company_ids(person_id: PersonId, *, max_results: int | None = None) -> builtins.list[CompanyId]

Get associated company IDs for a person.

V1-only: V2 does not expose person -> company associations directly. Uses GET /persons/{id} (V1) and returns organization_ids.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
max_results int | None

Maximum number of company IDs to return

None

Returns:

Type Description
list[CompanyId]

List of CompanyId values associated with this person

Note

The Person model already has company_ids populated from V1's organizationIds field. This method provides API parity with CompanyService.get_associated_person_ids().

Source code in affinity/services/persons.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def get_associated_company_ids(
    self,
    person_id: PersonId,
    *,
    max_results: int | None = None,
) -> builtins.list[CompanyId]:
    """
    Get associated company IDs for a person.

    V1-only: V2 does not expose person -> company associations directly.
    Uses GET `/persons/{id}` (V1) and returns `organization_ids`.

    Args:
        person_id: The person ID
        max_results: Maximum number of company IDs to return

    Returns:
        List of CompanyId values associated with this person

    Note:
        The Person model already has `company_ids` populated from V1's
        `organizationIds` field. This method provides API parity with
        `CompanyService.get_associated_person_ids()`.
    """
    data = self._client.get(f"/persons/{person_id}", v1=True)
    # Defensive: handle potential {"person": {...}} wrapper
    # (consistent with CompanyService.get_associated_person_ids pattern)
    person = data.get("person") if isinstance(data, dict) else None
    source = person if isinstance(person, dict) else data
    org_ids = None
    if isinstance(source, dict):
        org_ids = source.get("organization_ids") or source.get("organizationIds")

    if not isinstance(org_ids, list):
        return []

    ids = [CompanyId(int(cid)) for cid in org_ids if cid is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

get_associated_company_ids_batch(person_ids: Sequence[PersonId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[PersonId, builtins.list[CompanyId]]

Get company associations for multiple persons.

Makes one V1 API call per person.

Parameters:

Name Type Description Default
person_ids Sequence[PersonId]

Sequence of person IDs to fetch

required
on_error Literal['raise', 'skip']

How to handle errors - "raise" (default) or "skip" failed IDs

'raise'

Returns:

Type Description
dict[PersonId, list[CompanyId]]

Dict mapping person_id -> list of company_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Example

associations = client.persons.get_associated_company_ids_batch(person_ids) all_company_ids = set() for company_ids in associations.values(): all_company_ids.update(company_ids)

Source code in affinity/services/persons.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
def get_associated_company_ids_batch(
    self,
    person_ids: Sequence[PersonId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[PersonId, builtins.list[CompanyId]]:
    """
    Get company associations for multiple persons.

    Makes one V1 API call per person.

    Args:
        person_ids: Sequence of person IDs to fetch
        on_error: How to handle errors - "raise" (default) or "skip" failed IDs

    Returns:
        Dict mapping person_id -> list of company_ids

    Raises:
        AffinityError: If on_error="raise" and any fetch fails.

    Example:
        associations = client.persons.get_associated_company_ids_batch(person_ids)
        all_company_ids = set()
        for company_ids in associations.values():
            all_company_ids.update(company_ids)
    """
    result: dict[PersonId, builtins.list[CompanyId]] = {}
    for person_id in person_ids:
        try:
            result[person_id] = self.get_associated_company_ids(person_id)
        except AffinityError:
            if on_error == "raise":
                raise
            # skip: continue without this person
        except Exception as e:
            if on_error == "raise":
                raise AffinityError(
                    f"Failed to get associations for person {person_id}: {e}"
                ) from e
            # skip: continue without this person
    return result

get_associated_opportunity_ids(person_id: PersonId, *, max_results: int | None = None) -> builtins.list[OpportunityId]

Get associated opportunity IDs for a person.

V1-only: V2 does not expose person -> opportunity associations directly. Uses GET /persons/{id} (V1) and returns opportunity_ids.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
max_results int | None

Maximum number of opportunity IDs to return

None

Returns:

Type Description
list[OpportunityId]

List of OpportunityId values associated with this person

Note

The Person model already has opportunity_ids populated from V1's opportunityIds field. This method provides API parity with OpportunityService.get_associated_person_ids().

Source code in affinity/services/persons.py
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
def get_associated_opportunity_ids(
    self,
    person_id: PersonId,
    *,
    max_results: int | None = None,
) -> builtins.list[OpportunityId]:
    """
    Get associated opportunity IDs for a person.

    V1-only: V2 does not expose person -> opportunity associations directly.
    Uses GET `/persons/{id}` (V1) and returns `opportunity_ids`.

    Args:
        person_id: The person ID
        max_results: Maximum number of opportunity IDs to return

    Returns:
        List of OpportunityId values associated with this person

    Note:
        The Person model already has `opportunity_ids` populated from V1's
        `opportunityIds` field. This method provides API parity with
        `OpportunityService.get_associated_person_ids()`.
    """
    data = self._client.get(f"/persons/{person_id}", v1=True)
    # Defensive: handle potential {"person": {...}} wrapper
    person = data.get("person") if isinstance(data, dict) else None
    source = person if isinstance(person, dict) else data
    opp_ids = None
    if isinstance(source, dict):
        opp_ids = source.get("opportunity_ids") or source.get("opportunityIds")

    if not isinstance(opp_ids, list):
        return []

    ids = [OpportunityId(int(oid)) for oid in opp_ids if oid is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

get_associated_opportunity_ids_batch(person_ids: Sequence[PersonId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[PersonId, builtins.list[OpportunityId]]

Get opportunity associations for multiple persons.

Makes one V1 API call per person.

Parameters:

Name Type Description Default
person_ids Sequence[PersonId]

Sequence of person IDs to fetch

required
on_error Literal['raise', 'skip']

How to handle errors - "raise" (default) or "skip" failed IDs

'raise'

Returns:

Type Description
dict[PersonId, list[OpportunityId]]

Dict mapping person_id -> list of opportunity_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/persons.py
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
def get_associated_opportunity_ids_batch(
    self,
    person_ids: Sequence[PersonId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[PersonId, builtins.list[OpportunityId]]:
    """
    Get opportunity associations for multiple persons.

    Makes one V1 API call per person.

    Args:
        person_ids: Sequence of person IDs to fetch
        on_error: How to handle errors - "raise" (default) or "skip" failed IDs

    Returns:
        Dict mapping person_id -> list of opportunity_ids

    Raises:
        AffinityError: If on_error="raise" and any fetch fails.
    """
    result: dict[PersonId, builtins.list[OpportunityId]] = {}
    for person_id in person_ids:
        try:
            result[person_id] = self.get_associated_opportunity_ids(person_id)
        except AffinityError:
            if on_error == "raise":
                raise
            # skip: continue without this person
        except Exception as e:
            if on_error == "raise":
                raise AffinityError(
                    f"Failed to get associations for person {person_id}: {e}"
                ) from e
            # skip: continue without this person
    return result

get_fields(*, field_types: Sequence[FieldType] | None = None) -> builtins.list[FieldMetadata]

Get metadata about person fields.

Cached for performance.

Source code in affinity/services/persons.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
def get_fields(
    self,
    *,
    field_types: Sequence[FieldType] | None = None,
) -> builtins.list[FieldMetadata]:
    """
    Get metadata about person fields.

    Cached for performance.
    """
    params: dict[str, Any] = {}
    if field_types:
        params["fieldTypes"] = [field_type.value for field_type in field_types]

    data = self._client.get(
        "/persons/fields",
        params=params or None,
        cache_key=f"person_fields:{','.join(field_types or [])}",
        cache_ttl=300,
    )

    return [FieldMetadata.model_validate(f) for f in data.get("data", [])]

get_first(*, filter: str | FilterExpression | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None) -> Person | None

Get the first person matching the filter, or None if no match.

This is a convenience method equivalent to

page = client.persons.list(filter=filter, limit=1) return page.data[0] if page.data else None

Parameters:

Name Type Description Default
filter str | FilterExpression | None

V2 filter expression

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include

None
field_types Sequence[FieldType] | None

Field types to include

None

Returns:

Type Description
Person | None

First matching Person, or None if no results.

Source code in affinity/services/persons.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def get_first(
    self,
    *,
    filter: str | FilterExpression | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
) -> Person | None:
    """
    Get the first person matching the filter, or None if no match.

    This is a convenience method equivalent to:
        page = client.persons.list(filter=filter, limit=1)
        return page.data[0] if page.data else None

    Args:
        filter: V2 filter expression
        field_ids: Specific field IDs to include
        field_types: Field types to include

    Returns:
        First matching Person, or None if no results.
    """
    page = self.list(
        filter=filter,
        field_ids=field_ids,
        field_types=field_types,
        limit=1,
    )
    return page.data[0] if page.data else None

get_list_entries(person_id: PersonId) -> PaginatedResponse[ListEntry]

Get all list entries for a person across all lists.

Source code in affinity/services/persons.py
501
502
503
504
505
506
507
508
509
510
511
def get_list_entries(
    self,
    person_id: PersonId,
) -> PaginatedResponse[ListEntry]:
    """Get all list entries for a person across all lists."""
    data = self._client.get(f"/persons/{person_id}/list-entries")

    return PaginatedResponse[ListEntry](
        data=[ListEntry.model_validate(e) for e in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

get_lists(person_id: PersonId) -> PaginatedResponse[ListSummary]

Get all lists that contain this person.

Source code in affinity/services/persons.py
513
514
515
516
517
518
519
520
521
522
523
def get_lists(
    self,
    person_id: PersonId,
) -> PaginatedResponse[ListSummary]:
    """Get all lists that contain this person."""
    data = self._client.get(f"/persons/{person_id}/lists")

    return PaginatedResponse[ListSummary](
        data=[ListSummary.model_validate(item) for item in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

get_merge_status(task_id: str) -> MergeTask

Check the status of a merge operation.

Source code in affinity/services/persons.py
1002
1003
1004
1005
def get_merge_status(self, task_id: str) -> MergeTask:
    """Check the status of a merge operation."""
    data = self._client.get(f"/tasks/person-merges/{task_id}")
    return MergeTask.model_validate(data)

iter(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None) -> Iterator[Person]

Auto-paginate all persons.

Alias for all() (FR-006 public contract).

Source code in affinity/services/persons.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def iter(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
) -> Iterator[Person]:
    """
    Auto-paginate all persons.

    Alias for `all()` (FR-006 public contract).
    """
    return self.all(ids=ids, field_ids=field_ids, field_types=field_types, filter=filter)

list(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[Person]

Get a page of persons.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression string, or a FilterExpression built via affinity.F

None
limit int | None

Maximum number of results

None
cursor str | None

Cursor to resume pagination (opaque; obtained from prior responses)

None

Returns:

Type Description
PaginatedResponse[Person]

Paginated response with persons

Source code in affinity/services/persons.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def list(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[Person]:
    """
    Get a page of persons.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include
        filter: V2 filter expression string, or a FilterExpression built via `affinity.F`
        limit: Maximum number of results
        cursor: Cursor to resume pagination (opaque; obtained from prior responses)

    Returns:
        Paginated response with persons
    """
    validate_entity_field_types(field_types, endpoint="person")
    if cursor is not None:
        if any(p is not None for p in (ids, field_ids, field_types, filter, limit)):
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context. Start a new pagination sequence without a cursor to change "
                "parameters."
            )
        data = self._client.get_url(cursor)
    else:
        params: dict[str, Any] = {}
        if ids:
            params["ids"] = [int(id_) for id_ in ids]
        if field_ids:
            params["fieldIds"] = [str(field_id) for field_id in field_ids]
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]
        if filter is not None:
            filter_text = str(filter).strip()
            if filter_text:
                params["filter"] = filter_text
        if limit:
            params["limit"] = limit
        data = self._client.get("/persons", params=params or None)

    return PaginatedResponse[Person](
        data=[Person.model_validate(p) for p in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

merge(primary_id: PersonId, duplicate_id: PersonId) -> str

Merge a duplicate person into a primary person.

Returns a task URL to check merge status.

Source code in affinity/services/persons.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
def merge(
    self,
    primary_id: PersonId,
    duplicate_id: PersonId,
) -> str:
    """
    Merge a duplicate person into a primary person.

    Returns a task URL to check merge status.
    """
    if not self._client.enable_beta_endpoints:
        raise BetaEndpointDisabledError(
            "Person merge is a beta endpoint; set enable_beta_endpoints=True to use it."
        )
    result = self._client.post(
        "/person-merges",
        json={
            "primaryPersonId": int(primary_id),
            "duplicatePersonId": int(duplicate_id),
        },
    )
    return str(result.get("taskUrl", ""))

pages(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None, limit: int | None = None, cursor: str | None = None) -> Iterator[PaginatedResponse[Person]]

Iterate person pages (not items), yielding PaginatedResponse[Person].

Useful for ETL scripts that need checkpoint/resume via page.next_cursor.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression string or FilterExpression

None
limit int | None

Maximum results per page

None
cursor str | None

Cursor to resume pagination

None

Yields:

Type Description
PaginatedResponse[Person]

PaginatedResponse[Person] for each page

Source code in affinity/services/persons.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def pages(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> Iterator[PaginatedResponse[Person]]:
    """
    Iterate person pages (not items), yielding `PaginatedResponse[Person]`.

    Useful for ETL scripts that need checkpoint/resume via `page.next_cursor`.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include
        filter: V2 filter expression string or FilterExpression
        limit: Maximum results per page
        cursor: Cursor to resume pagination

    Yields:
        PaginatedResponse[Person] for each page
    """
    other_params = (ids, field_ids, field_types, filter, limit)
    if cursor is not None and any(p is not None for p in other_params):
        raise ValueError(
            "Cannot combine 'cursor' with other parameters; cursor encodes all query context. "
            "Start a new pagination sequence without a cursor to change parameters."
        )
    requested_cursor = cursor
    page = (
        self.list(cursor=cursor)
        if cursor is not None
        else self.list(
            ids=ids, field_ids=field_ids, field_types=field_types, filter=filter, limit=limit
        )
    )
    while True:
        yield page
        if not page.has_next:
            return
        next_cursor = page.next_cursor
        if next_cursor is None or next_cursor == requested_cursor:
            return
        requested_cursor = next_cursor
        page = self.list(cursor=next_cursor)

resolve(*, email: str | None = None, name: str | None = None) -> Person | None

Find a single person by email or name.

This is a convenience helper that searches and returns the first exact match, or None if not found. Uses V1 search internally.

Parameters:

Name Type Description Default
email str | None

Email address to search for

None
name str | None

Person name to search for (first + last)

None

Returns:

Type Description
Person | None

The matching Person, or None if not found

Raises:

Type Description
ValueError

If neither email nor name is provided

Note

This auto-paginates V1 search results until a match is found. If multiple matches are found, returns the first one. For full disambiguation, use resolve_all() or search() directly.

Source code in affinity/services/persons.py
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
def resolve(
    self,
    *,
    email: str | None = None,
    name: str | None = None,
) -> Person | None:
    """
    Find a single person by email or name.

    This is a convenience helper that searches and returns the first exact match,
    or None if not found. Uses V1 search internally.

    Args:
        email: Email address to search for
        name: Person name to search for (first + last)

    Returns:
        The matching Person, or None if not found

    Raises:
        ValueError: If neither email nor name is provided

    Note:
        This auto-paginates V1 search results until a match is found.
        If multiple matches are found, returns the first one. For full
        disambiguation, use resolve_all() or search() directly.
    """
    if not email and not name:
        raise ValueError("Must provide either email or name")

    term = email or name or ""
    for page in self.search_pages(term, page_size=10):
        for person in page.data:
            if _person_matches(person, email=email, name=name):
                return person

    return None

resolve_all(*, email: str | None = None, name: str | None = None) -> builtins.list[Person]

Find all persons matching an email or name.

Notes: - This auto-paginates V1 search results to collect exact matches. - Unlike resolve(), this returns every match in server-provided order.

Source code in affinity/services/persons.py
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
def resolve_all(
    self,
    *,
    email: str | None = None,
    name: str | None = None,
) -> builtins.list[Person]:
    """
    Find all persons matching an email or name.

    Notes:
    - This auto-paginates V1 search results to collect exact matches.
    - Unlike resolve(), this returns every match in server-provided order.
    """
    if not email and not name:
        raise ValueError("Must provide either email or name")

    term = email or name or ""
    matches: builtins.list[Person] = []
    for page in self.search_pages(term, page_size=10):
        for person in page.data:
            if _person_matches(person, email=email, name=name):
                matches.append(person)
    return matches

search(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> PaginatedResponse[Person]

Search for persons by name or email.

Uses V1 API for search functionality.

Parameters:

Name Type Description Default
term str

Search term (name or email)

required
with_interaction_dates bool

Include interaction date data

False
with_interaction_persons bool

Include persons for interactions

False
with_opportunities bool

Include associated opportunity IDs

False
page_size int | None

Results per page (max 500)

None
page_token str | None

Pagination token

None

Returns:

Type Description
PaginatedResponse[Person]

PaginatedResponse[Person] with matching persons and pagination info

Source code in affinity/services/persons.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def search(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> PaginatedResponse[Person]:
    """
    Search for persons by name or email.

    Uses V1 API for search functionality.

    Args:
        term: Search term (name or email)
        with_interaction_dates: Include interaction date data
        with_interaction_persons: Include persons for interactions
        with_opportunities: Include associated opportunity IDs
        page_size: Results per page (max 500)
        page_token: Pagination token

    Returns:
        PaginatedResponse[Person] with matching persons and pagination info
    """
    params: dict[str, Any] = {"term": term}
    if with_interaction_dates:
        params["with_interaction_dates"] = True
    if with_interaction_persons:
        params["with_interaction_persons"] = True
    if with_opportunities:
        params["with_opportunities"] = True
    if page_size:
        params["page_size"] = page_size
    if page_token:
        params["page_token"] = page_token

    data = self._client.get("/persons", params=params, v1=True)
    items = [Person.model_validate(p) for p in data.get("persons", [])]
    return PaginatedResponse[Person](
        data=items,
        next_page_token=data.get("next_page_token"),
    )

search_all(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> Iterator[Person]

Iterate all V1 person-search results with automatic pagination.

Parameters:

Name Type Description Default
term str

Search term (name or email)

required
with_interaction_dates bool

Include interaction date data

False
with_interaction_persons bool

Include persons for interactions

False
with_opportunities bool

Include associated opportunity IDs

False
page_size int | None

Results per page (max 500)

None
page_token str | None

Resume from this pagination token

None

Yields:

Type Description
Person

Person objects matching the search term

Source code in affinity/services/persons.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
def search_all(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> Iterator[Person]:
    """
    Iterate all V1 person-search results with automatic pagination.

    Args:
        term: Search term (name or email)
        with_interaction_dates: Include interaction date data
        with_interaction_persons: Include persons for interactions
        with_opportunities: Include associated opportunity IDs
        page_size: Results per page (max 500)
        page_token: Resume from this pagination token

    Yields:
        Person objects matching the search term
    """
    for page in self.search_pages(
        term,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
        with_opportunities=with_opportunities,
        page_size=page_size,
        page_token=page_token,
    ):
        yield from page.data

search_pages(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> Iterator[PaginatedResponse[Person]]

Iterate V1 person-search result pages.

Useful for scripts that need checkpoint/resume via next_page_token.

Parameters:

Name Type Description Default
term str

Search term (name or email)

required
with_interaction_dates bool

Include interaction date data

False
with_interaction_persons bool

Include persons for interactions

False
with_opportunities bool

Include associated opportunity IDs

False
page_size int | None

Results per page (max 500)

None
page_token str | None

Resume from this pagination token

None

Yields:

Type Description
PaginatedResponse[Person]

PaginatedResponse[Person] for each page

Source code in affinity/services/persons.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def search_pages(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> Iterator[PaginatedResponse[Person]]:
    """
    Iterate V1 person-search result pages.

    Useful for scripts that need checkpoint/resume via `next_page_token`.

    Args:
        term: Search term (name or email)
        with_interaction_dates: Include interaction date data
        with_interaction_persons: Include persons for interactions
        with_opportunities: Include associated opportunity IDs
        page_size: Results per page (max 500)
        page_token: Resume from this pagination token

    Yields:
        PaginatedResponse[Person] for each page
    """
    requested_token = page_token
    page = self.search(
        term,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
        with_opportunities=with_opportunities,
        page_size=page_size,
        page_token=page_token,
    )
    while True:
        yield page
        next_token = page.next_page_token
        if not next_token or next_token == requested_token:
            return
        requested_token = next_token
        page = self.search(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=next_token,
        )

update(person_id: PersonId, data: PersonUpdate) -> Person

Update an existing person.

Note: To add emails/organizations, include existing values plus new ones.

Source code in affinity/services/persons.py
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
def update(
    self,
    person_id: PersonId,
    data: PersonUpdate,
) -> Person:
    """
    Update an existing person.

    Note: To add emails/organizations, include existing values plus new ones.
    """
    payload = data.model_dump(
        by_alias=True,
        mode="json",
        exclude_unset=True,
        exclude_none=True,
    )

    result = self._client.put(
        f"/persons/{person_id}",
        json=payload,
        v1=True,
    )

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return Person.model_validate(result)

Async version of PersonService.

Source code in affinity/services/persons.py
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
class AsyncPersonService:
    """Async version of PersonService."""

    def __init__(self, client: AsyncHTTPClient):
        self._client = client

    async def list(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[Person]:
        """
        Get a page of persons.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include
            filter: V2 filter expression string, or a FilterExpression built via `affinity.F`
            limit: Maximum number of results
            cursor: Cursor to resume pagination (opaque; obtained from prior responses)

        Returns:
            Paginated response with persons
        """
        validate_entity_field_types(field_types, endpoint="person")
        if cursor is not None:
            if any(p is not None for p in (ids, field_ids, field_types, filter, limit)):
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context. Start a new pagination sequence without a cursor to change "
                    "parameters."
                )
            data = await self._client.get_url(cursor)
        else:
            params: dict[str, Any] = {}
            if ids:
                params["ids"] = [int(id_) for id_ in ids]
            if field_ids:
                params["fieldIds"] = [str(field_id) for field_id in field_ids]
            if field_types:
                params["fieldTypes"] = [field_type.value for field_type in field_types]
            if filter is not None:
                filter_text = str(filter).strip()
                if filter_text:
                    params["filter"] = filter_text
            if limit:
                params["limit"] = limit
            data = await self._client.get("/persons", params=params or None)

        return PaginatedResponse[Person](
            data=[Person.model_validate(p) for p in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    async def get_first(
        self,
        *,
        filter: str | FilterExpression | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
    ) -> Person | None:
        """
        Get the first person matching the filter, or None if no match.

        See PersonService.get_first() for details.
        """
        page = await self.list(
            filter=filter,
            field_ids=field_ids,
            field_types=field_types,
            limit=1,
        )
        return page.data[0] if page.data else None

    async def batch_get(
        self,
        person_ids: Sequence[PersonId],
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        max_concurrent: int = 10,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[PersonId, Person]:
        """
        Fetch multiple persons with controlled concurrency.

        Makes individual get() calls with bounded concurrency.

        Args:
            person_ids: Person IDs to fetch
            field_ids: Specific field IDs to include
            field_types: Field types to include
            include_field_values: If True, fetch embedded field values
            with_interaction_dates: Include interaction date summaries
            with_interaction_persons: Include person IDs for interactions
            max_concurrent: Maximum concurrent API calls (default: 10)
            on_error: How to handle AffinityError exceptions:
                - "raise": Raise on first AffinityError (default)
                - "skip": Skip failed IDs, return partial results

        Returns:
            Dict mapping person_id -> Person for successfully fetched persons.

        Raises:
            AffinityError: If on_error="raise" and any fetch fails.
        """
        if not person_ids:
            return {}
        if max_concurrent < 1:
            raise ValueError("max_concurrent must be at least 1")

        unique_ids = list(dict.fromkeys(person_ids))
        results: dict[PersonId, Person] = {}

        async def fetch_one(pid: PersonId) -> tuple[PersonId, Person | None]:
            try:
                person = await self.get(
                    pid,
                    field_ids=field_ids,
                    field_types=field_types,
                    include_field_values=include_field_values,
                    with_interaction_dates=with_interaction_dates,
                    with_interaction_persons=with_interaction_persons,
                )
                return (pid, person)
            except AffinityError:
                if on_error == "raise":
                    raise
                return (pid, None)

        for i in range(0, len(unique_ids), max_concurrent):
            chunk = unique_ids[i : i + max_concurrent]
            tasks = [asyncio.create_task(fetch_one(pid)) for pid in chunk]
            try:
                for coro in asyncio.as_completed(tasks):
                    pid, person = await coro
                    if person is not None:
                        results[pid] = person
            except BaseException:
                for task in tasks:
                    if not task.done():
                        task.cancel()
                await asyncio.gather(*tasks, return_exceptions=True)
                raise

        return results

    async def pages(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> AsyncIterator[PaginatedResponse[Person]]:
        """
        Iterate person pages (not items), yielding `PaginatedResponse[Person]`.

        Useful for ETL scripts that need checkpoint/resume via `page.next_cursor`.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include
            filter: V2 filter expression string or FilterExpression
            limit: Maximum results per page
            cursor: Cursor to resume pagination

        Yields:
            PaginatedResponse[Person] for each page
        """
        other_params = (ids, field_ids, field_types, filter, limit)
        if cursor is not None and any(p is not None for p in other_params):
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query context. "
                "Start a new pagination sequence without a cursor to change parameters."
            )
        requested_cursor = cursor
        if cursor is not None:
            page = await self.list(cursor=cursor)
        else:
            page = await self.list(
                ids=ids,
                field_ids=field_ids,
                field_types=field_types,
                filter=filter,
                limit=limit,
            )
        while True:
            yield page
            if not page.has_next:
                return
            next_cursor = page.next_cursor
            if next_cursor is None or next_cursor == requested_cursor:
                return
            requested_cursor = next_cursor
            page = await self.list(cursor=next_cursor)

    def all(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
    ) -> AsyncIterator[Person]:
        """
        Iterate through all persons with automatic pagination.

        Args:
            ids: Specific person IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include
            field_types: Field types to include
            filter: V2 filter expression

        Yields:
            Person objects
        """

        async def fetch_page(next_url: str | None) -> PaginatedResponse[Person]:
            if next_url:
                data = await self._client.get_url(next_url)
                return PaginatedResponse[Person](
                    data=[Person.model_validate(p) for p in data.get("data", [])],
                    pagination=PaginationInfo.model_validate(data.get("pagination", {})),
                )
            return await self.list(
                ids=ids, field_ids=field_ids, field_types=field_types, filter=filter
            )

        return AsyncPageIterator(fetch_page)

    def iter(
        self,
        *,
        ids: Sequence[PersonId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        filter: str | FilterExpression | None = None,
    ) -> AsyncIterator[Person]:
        """
        Auto-paginate all persons.

        Alias for `all()` (FR-006 public contract).
        """
        return self.all(ids=ids, field_ids=field_ids, field_types=field_types, filter=filter)

    async def get(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """
        Get a single person by ID.

        Args:
            person_id: The person ID
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            include_field_values: If True, fetch embedded field values. This saves
                one API call when you need both person info and field values.
                Cannot be combined with field_ids/field_types.
            retries: Number of retries on 404 NotFoundError. Default is 0 (fail fast).
                Set to 2-3 if calling immediately after create() to handle eventual
                consistency lag.
            with_interaction_dates: Include interaction date summaries (last/next
                meeting dates, email dates).
            with_interaction_persons: Include person IDs for each interaction.
                Only applies when with_interaction_dates=True.

        Returns:
            Person object with requested field data.
            When include_field_values=True, the Person will have a `field_values`
            attribute containing the list of FieldValue objects.
            When with_interaction_dates=True, the Person will have interaction_dates
            and interactions populated.

        Raises:
            NotFoundError: If person does not exist after all retries.
            ValueError: If include_field_values is combined with field_ids/field_types.

        Note:
            When combining with_interaction_dates with field_ids/field_types,
            two API calls are made internally and the results are merged.
        """
        return await self._get_with_retry(
            person_id,
            field_ids=field_ids,
            field_types=field_types,
            include_field_values=include_field_values,
            retries=retries,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
        )

    async def _get_with_retry(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """Internal: get with retry logic."""
        last_error: NotFoundError | None = None
        attempts = retries + 1  # retries=0 means 1 attempt

        for attempt in range(attempts):
            try:
                return await self._get_impl(
                    person_id,
                    field_ids=field_ids,
                    field_types=field_types,
                    include_field_values=include_field_values,
                    with_interaction_dates=with_interaction_dates,
                    with_interaction_persons=with_interaction_persons,
                )
            except NotFoundError as e:
                last_error = e
                if attempt < attempts - 1:  # Don't sleep after last attempt
                    await asyncio.sleep(0.5 * (attempt + 1))  # 0.5s, 1s, 1.5s backoff

        # V1 fallback: If V2 returned 404, try V1 API (handles V1→V2 sync delays)
        # Skip if already using V1 path (include_field_values or with_interaction_dates)
        if last_error is not None and not include_field_values and not with_interaction_dates:
            try:
                v1_data = await self._client.get(f"/persons/{person_id}", v1=True)
                normalized = _normalize_v1_person_response(v1_data)
                return Person.model_validate(normalized)
            except NotFoundError:
                pass  # V1 also failed, raise original V2 error

        raise last_error  # type: ignore[misc]

    async def _get_impl(
        self,
        person_id: PersonId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        include_field_values: bool = False,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Person:
        """Internal: actual get implementation."""
        has_field_filters = field_ids is not None or field_types is not None

        # include_field_values returns embedded field values, which is incompatible
        # with field_ids/field_types filtering (different data structures)
        if include_field_values and has_field_filters:
            raise ValueError(
                "Cannot combine 'include_field_values' with 'field_ids' or 'field_types'. "
                "Use include_field_values alone for embedded field values, or use "
                "field_ids/field_types alone for filtered fields."
            )

        # Path 1: include_field_values (V1 API, may include interaction dates)
        if include_field_values:
            v1_params: dict[str, Any] = {}
            if with_interaction_dates:
                v1_params["with_interaction_dates"] = True
            if with_interaction_persons:
                v1_params["with_interaction_persons"] = True

            data = await self._client.get(
                f"/persons/{person_id}",
                params=v1_params or None,
                v1=True,
            )

            field_values_data = data.get("field_values", [])
            # V1 embedded field_values don't include entityId; add it before validation
            field_values = [
                FieldValue.model_validate({**fv, "entityId": int(person_id)})
                for fv in field_values_data
            ]
            normalized = _normalize_v1_person_response(data)
            person = Person.model_validate(normalized)
            object.__setattr__(person, "field_values", field_values)
            return person

        # Path 2: with_interaction_dates (may need merge if field filters present)
        if with_interaction_dates:
            v1_params = {"with_interaction_dates": True}
            if with_interaction_persons:
                v1_params["with_interaction_persons"] = True

            interaction_data = await self._client.get(
                f"/persons/{person_id}",
                params=v1_params,
                v1=True,
            )

            # If field filtering is also requested, fetch filtered fields and merge
            if has_field_filters:
                v2_params: dict[str, Any] = {}
                if field_ids:
                    v2_params["fieldIds"] = [str(fid) for fid in field_ids]
                if field_types:
                    v2_params["fieldTypes"] = [ft.value for ft in field_types]

                filtered_data = await self._client.get(
                    f"/persons/{person_id}",
                    params=v2_params,
                )

                # Merge: filtered fields + interaction data
                filtered_data["interaction_dates"] = interaction_data.get("interaction_dates")
                filtered_data["interactions"] = interaction_data.get("interactions")
                return Person.model_validate(filtered_data)

            # No field filtering, normalize and return V1 data
            normalized = _normalize_v1_person_response(interaction_data)
            return Person.model_validate(normalized)

        # Path 3: Standard path (supports field filtering)
        params: dict[str, Any] = {}
        if field_ids:
            params["fieldIds"] = [str(field_id) for field_id in field_ids]
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]

        data = await self._client.get(f"/persons/{person_id}", params=params or None)
        return Person.model_validate(data)

    async def get_list_entries(
        self,
        person_id: PersonId,
    ) -> PaginatedResponse[ListEntry]:
        """Get all list entries for a person across all lists."""
        data = await self._client.get(f"/persons/{person_id}/list-entries")

        return PaginatedResponse[ListEntry](
            data=[ListEntry.model_validate(e) for e in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    async def get_lists(
        self,
        person_id: PersonId,
    ) -> PaginatedResponse[ListSummary]:
        """Get all lists that contain this person."""
        data = await self._client.get(f"/persons/{person_id}/lists")

        return PaginatedResponse[ListSummary](
            data=[ListSummary.model_validate(item) for item in data.get("data", [])],
            pagination=PaginationInfo.model_validate(data.get("pagination", {})),
        )

    async def get_fields(
        self,
        *,
        field_types: Sequence[FieldType] | None = None,
    ) -> builtins.list[FieldMetadata]:
        """
        Get metadata about person fields.

        Cached for performance.
        """
        params: dict[str, Any] = {}
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]

        data = await self._client.get(
            "/persons/fields",
            params=params or None,
            cache_key=f"person_fields:{','.join(field_types or [])}",
            cache_ttl=300,
        )

        return [FieldMetadata.model_validate(f) for f in data.get("data", [])]

    # =========================================================================
    # Associations (V1 API)
    # =========================================================================

    async def get_associated_company_ids(
        self,
        person_id: PersonId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[CompanyId]:
        """
        Get associated company IDs for a person.

        V1-only: V2 does not expose person -> company associations directly.
        Uses GET `/persons/{id}` (V1) and returns `organization_ids`.

        Args:
            person_id: The person ID
            max_results: Maximum number of company IDs to return

        Returns:
            List of CompanyId values associated with this person

        Note:
            The Person model already has `company_ids` populated from V1's
            `organizationIds` field. This method provides API parity with
            `CompanyService.get_associated_person_ids()`.
        """
        data = await self._client.get(f"/persons/{person_id}", v1=True)
        # Defensive: handle potential {"person": {...}} wrapper
        # (consistent with CompanyService.get_associated_person_ids pattern)
        person = data.get("person") if isinstance(data, dict) else None
        source = person if isinstance(person, dict) else data
        org_ids = None
        if isinstance(source, dict):
            org_ids = source.get("organization_ids") or source.get("organizationIds")

        if not isinstance(org_ids, list):
            return []

        ids = [CompanyId(int(cid)) for cid in org_ids if cid is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    async def get_associated_company_ids_batch(
        self,
        person_ids: Sequence[PersonId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[PersonId, builtins.list[CompanyId]]:
        """
        Get company associations for multiple persons.

        Makes one V1 API call per person.

        Args:
            person_ids: Sequence of person IDs to fetch
            on_error: How to handle errors - "raise" (default) or "skip" failed IDs

        Returns:
            Dict mapping person_id -> list of company_ids

        Raises:
            AffinityError: If on_error="raise" and any fetch fails.
        """
        result: dict[PersonId, builtins.list[CompanyId]] = {}
        for person_id in person_ids:
            try:
                result[person_id] = await self.get_associated_company_ids(person_id)
            except AffinityError:
                if on_error == "raise":
                    raise
                # skip: continue without this person
            except Exception as e:
                if on_error == "raise":
                    raise AffinityError(
                        f"Failed to get associations for person {person_id}: {e}"
                    ) from e
                # skip: continue without this person
        return result

    async def get_associated_opportunity_ids(
        self,
        person_id: PersonId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[OpportunityId]:
        """
        Get associated opportunity IDs for a person.

        V1-only: V2 does not expose person -> opportunity associations directly.
        Uses GET `/persons/{id}` (V1) and returns `opportunity_ids`.

        Args:
            person_id: The person ID
            max_results: Maximum number of opportunity IDs to return

        Returns:
            List of OpportunityId values associated with this person

        Note:
            The Person model already has `opportunity_ids` populated from V1's
            `opportunityIds` field. This method provides API parity with
            `OpportunityService.get_associated_person_ids()`.
        """
        data = await self._client.get(f"/persons/{person_id}", v1=True)
        # Defensive: handle potential {"person": {...}} wrapper
        person = data.get("person") if isinstance(data, dict) else None
        source = person if isinstance(person, dict) else data
        opp_ids = None
        if isinstance(source, dict):
            opp_ids = source.get("opportunity_ids") or source.get("opportunityIds")

        if not isinstance(opp_ids, list):
            return []

        ids = [OpportunityId(int(oid)) for oid in opp_ids if oid is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    async def get_associated_opportunity_ids_batch(
        self,
        person_ids: Sequence[PersonId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[PersonId, builtins.list[OpportunityId]]:
        """
        Get opportunity associations for multiple persons.

        Makes one V1 API call per person.

        Args:
            person_ids: Sequence of person IDs to fetch
            on_error: How to handle errors - "raise" (default) or "skip" failed IDs

        Returns:
            Dict mapping person_id -> list of opportunity_ids

        Raises:
            AffinityError: If on_error="raise" and any fetch fails.
        """
        result: dict[PersonId, builtins.list[OpportunityId]] = {}
        for person_id in person_ids:
            try:
                result[person_id] = await self.get_associated_opportunity_ids(person_id)
            except AffinityError:
                if on_error == "raise":
                    raise
                # skip: continue without this person
            except Exception as e:
                if on_error == "raise":
                    raise AffinityError(
                        f"Failed to get associations for person {person_id}: {e}"
                    ) from e
                # skip: continue without this person
        return result

    # =========================================================================
    # Search (V1 API)
    # =========================================================================

    async def search(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> PaginatedResponse[Person]:
        """
        Search for persons by name or email.

        Uses V1 API for search functionality.
        """
        params: dict[str, Any] = {"term": term}
        if with_interaction_dates:
            params["with_interaction_dates"] = True
        if with_interaction_persons:
            params["with_interaction_persons"] = True
        if with_opportunities:
            params["with_opportunities"] = True
        if page_size:
            params["page_size"] = page_size
        if page_token:
            params["page_token"] = page_token

        data = await self._client.get("/persons", params=params, v1=True)
        items = [Person.model_validate(p) for p in data.get("persons", [])]
        return PaginatedResponse[Person](
            data=items,
            next_page_token=data.get("next_page_token"),
        )

    async def search_pages(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> AsyncIterator[PaginatedResponse[Person]]:
        """
        Iterate V1 person-search result pages.

        Useful for scripts that need checkpoint/resume via `next_page_token`.

        Args:
            term: Search term (name or email)
            with_interaction_dates: Include interaction date data
            with_interaction_persons: Include persons for interactions
            with_opportunities: Include associated opportunity IDs
            page_size: Results per page (max 500)
            page_token: Resume from this pagination token

        Yields:
            PaginatedResponse[Person] for each page
        """
        requested_token = page_token
        page = await self.search(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=page_token,
        )
        while True:
            yield page
            next_token = page.next_page_token
            if not next_token or next_token == requested_token:
                return
            requested_token = next_token
            page = await self.search(
                term,
                with_interaction_dates=with_interaction_dates,
                with_interaction_persons=with_interaction_persons,
                with_opportunities=with_opportunities,
                page_size=page_size,
                page_token=next_token,
            )

    async def search_all(
        self,
        term: str,
        *,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
        with_opportunities: bool = False,
        page_size: int | None = None,
        page_token: str | None = None,
    ) -> AsyncIterator[Person]:
        """
        Iterate all V1 person-search results with automatic pagination.

        Args:
            term: Search term (name or email)
            with_interaction_dates: Include interaction date data
            with_interaction_persons: Include persons for interactions
            with_opportunities: Include associated opportunity IDs
            page_size: Results per page (max 500)
            page_token: Resume from this pagination token

        Yields:
            Person objects matching the search term
        """
        async for page in self.search_pages(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=page_token,
        ):
            for person in page.data:
                yield person

    async def resolve(
        self,
        *,
        email: str | None = None,
        name: str | None = None,
    ) -> Person | None:
        """
        Find a single person by email or name.

        This is a convenience helper that searches and returns the first exact match,
        or None if not found. Uses V1 search internally.
        """
        if not email and not name:
            raise ValueError("Must provide either email or name")

        term = email or name or ""
        async for page in self.search_pages(term, page_size=10):
            for person in page.data:
                if _person_matches(person, email=email, name=name):
                    return person

        return None

    async def resolve_all(
        self,
        *,
        email: str | None = None,
        name: str | None = None,
    ) -> builtins.list[Person]:
        """
        Find all persons matching an email or name.

        Notes:
        - This auto-paginates V1 search results to collect exact matches.
        - Unlike resolve(), this returns every match in server-provided order.
        """
        if not email and not name:
            raise ValueError("Must provide either email or name")

        term = email or name or ""
        matches: builtins.list[Person] = []
        async for page in self.search_pages(term, page_size=10):
            for person in page.data:
                if _person_matches(person, email=email, name=name):
                    matches.append(person)
        return matches

    # =========================================================================
    # Write Operations (V1 API)
    # =========================================================================

    async def create(self, data: PersonCreate) -> Person:
        """
        Create a new person.

        Note:
            Creates use V1 API, while reads use V2 API. Due to eventual consistency
            between V1 and V2, a `get()` call immediately after `create()` may return
            404 NotFoundError. If you need to read immediately after creation, either:
            - Use the Person object returned by this method (it contains the created data)
            - Add a short delay (100-500ms) before calling get()
            - Implement retry logic in your application

        Raises:
            ValidationError: If email conflicts with existing person
        """
        payload = data.model_dump(by_alias=True, mode="json")
        if not data.company_ids:
            payload.pop("organization_ids", None)

        result = await self._client.post("/persons", json=payload, v1=True)

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return Person.model_validate(result)

    async def update(
        self,
        person_id: PersonId,
        data: PersonUpdate,
    ) -> Person:
        """
        Update an existing person.

        Note: To add emails/organizations, include existing values plus new ones.
        """
        payload = data.model_dump(
            by_alias=True,
            mode="json",
            exclude_unset=True,
            exclude_none=True,
        )

        result = await self._client.put(
            f"/persons/{person_id}",
            json=payload,
            v1=True,
        )

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return Person.model_validate(result)

    async def delete(self, person_id: PersonId) -> bool:
        """Delete a person (also deletes associated field values)."""
        result = await self._client.delete(f"/persons/{person_id}", v1=True)

        if self._client.cache:
            self._client.cache.invalidate_prefix("person")

        return bool(result.get("success", False))

    # =========================================================================
    # Merge Operations (V2 BETA)
    # =========================================================================

    async def merge(
        self,
        primary_id: PersonId,
        duplicate_id: PersonId,
    ) -> str:
        """
        Merge a duplicate person into a primary person.

        Returns a task URL to check merge status.
        """
        if not self._client.enable_beta_endpoints:
            raise BetaEndpointDisabledError(
                "Person merge is a beta endpoint; set enable_beta_endpoints=True to use it."
            )
        result = await self._client.post(
            "/person-merges",
            json={
                "primaryPersonId": int(primary_id),
                "duplicatePersonId": int(duplicate_id),
            },
        )
        return str(result.get("taskUrl", ""))

    async def get_merge_status(self, task_id: str) -> MergeTask:
        """Check the status of a merge operation."""
        data = await self._client.get(f"/tasks/person-merges/{task_id}")
        return MergeTask.model_validate(data)

all(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None) -> AsyncIterator[Person]

Iterate through all persons with automatic pagination.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression

None

Yields:

Type Description
AsyncIterator[Person]

Person objects

Source code in affinity/services/persons.py
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def all(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
) -> AsyncIterator[Person]:
    """
    Iterate through all persons with automatic pagination.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include
        field_types: Field types to include
        filter: V2 filter expression

    Yields:
        Person objects
    """

    async def fetch_page(next_url: str | None) -> PaginatedResponse[Person]:
        if next_url:
            data = await self._client.get_url(next_url)
            return PaginatedResponse[Person](
                data=[Person.model_validate(p) for p in data.get("data", [])],
                pagination=PaginationInfo.model_validate(data.get("pagination", {})),
            )
        return await self.list(
            ids=ids, field_ids=field_ids, field_types=field_types, filter=filter
        )

    return AsyncPageIterator(fetch_page)

batch_get(person_ids: Sequence[PersonId], *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, include_field_values: bool = False, with_interaction_dates: bool = False, with_interaction_persons: bool = False, max_concurrent: int = 10, on_error: Literal['raise', 'skip'] = 'raise') -> dict[PersonId, Person] async

Fetch multiple persons with controlled concurrency.

Makes individual get() calls with bounded concurrency.

Parameters:

Name Type Description Default
person_ids Sequence[PersonId]

Person IDs to fetch

required
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include

None
field_types Sequence[FieldType] | None

Field types to include

None
include_field_values bool

If True, fetch embedded field values

False
with_interaction_dates bool

Include interaction date summaries

False
with_interaction_persons bool

Include person IDs for interactions

False
max_concurrent int

Maximum concurrent API calls (default: 10)

10
on_error Literal['raise', 'skip']

How to handle AffinityError exceptions: - "raise": Raise on first AffinityError (default) - "skip": Skip failed IDs, return partial results

'raise'

Returns:

Type Description
dict[PersonId, Person]

Dict mapping person_id -> Person for successfully fetched persons.

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/persons.py
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
async def batch_get(
    self,
    person_ids: Sequence[PersonId],
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    include_field_values: bool = False,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    max_concurrent: int = 10,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[PersonId, Person]:
    """
    Fetch multiple persons with controlled concurrency.

    Makes individual get() calls with bounded concurrency.

    Args:
        person_ids: Person IDs to fetch
        field_ids: Specific field IDs to include
        field_types: Field types to include
        include_field_values: If True, fetch embedded field values
        with_interaction_dates: Include interaction date summaries
        with_interaction_persons: Include person IDs for interactions
        max_concurrent: Maximum concurrent API calls (default: 10)
        on_error: How to handle AffinityError exceptions:
            - "raise": Raise on first AffinityError (default)
            - "skip": Skip failed IDs, return partial results

    Returns:
        Dict mapping person_id -> Person for successfully fetched persons.

    Raises:
        AffinityError: If on_error="raise" and any fetch fails.
    """
    if not person_ids:
        return {}
    if max_concurrent < 1:
        raise ValueError("max_concurrent must be at least 1")

    unique_ids = list(dict.fromkeys(person_ids))
    results: dict[PersonId, Person] = {}

    async def fetch_one(pid: PersonId) -> tuple[PersonId, Person | None]:
        try:
            person = await self.get(
                pid,
                field_ids=field_ids,
                field_types=field_types,
                include_field_values=include_field_values,
                with_interaction_dates=with_interaction_dates,
                with_interaction_persons=with_interaction_persons,
            )
            return (pid, person)
        except AffinityError:
            if on_error == "raise":
                raise
            return (pid, None)

    for i in range(0, len(unique_ids), max_concurrent):
        chunk = unique_ids[i : i + max_concurrent]
        tasks = [asyncio.create_task(fetch_one(pid)) for pid in chunk]
        try:
            for coro in asyncio.as_completed(tasks):
                pid, person = await coro
                if person is not None:
                    results[pid] = person
        except BaseException:
            for task in tasks:
                if not task.done():
                    task.cancel()
            await asyncio.gather(*tasks, return_exceptions=True)
            raise

    return results

create(data: PersonCreate) -> Person async

Create a new person.

Note

Creates use V1 API, while reads use V2 API. Due to eventual consistency between V1 and V2, a get() call immediately after create() may return 404 NotFoundError. If you need to read immediately after creation, either: - Use the Person object returned by this method (it contains the created data) - Add a short delay (100-500ms) before calling get() - Implement retry logic in your application

Raises:

Type Description
ValidationError

If email conflicts with existing person

Source code in affinity/services/persons.py
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
async def create(self, data: PersonCreate) -> Person:
    """
    Create a new person.

    Note:
        Creates use V1 API, while reads use V2 API. Due to eventual consistency
        between V1 and V2, a `get()` call immediately after `create()` may return
        404 NotFoundError. If you need to read immediately after creation, either:
        - Use the Person object returned by this method (it contains the created data)
        - Add a short delay (100-500ms) before calling get()
        - Implement retry logic in your application

    Raises:
        ValidationError: If email conflicts with existing person
    """
    payload = data.model_dump(by_alias=True, mode="json")
    if not data.company_ids:
        payload.pop("organization_ids", None)

    result = await self._client.post("/persons", json=payload, v1=True)

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return Person.model_validate(result)

delete(person_id: PersonId) -> bool async

Delete a person (also deletes associated field values).

Source code in affinity/services/persons.py
1887
1888
1889
1890
1891
1892
1893
1894
async def delete(self, person_id: PersonId) -> bool:
    """Delete a person (also deletes associated field values)."""
    result = await self._client.delete(f"/persons/{person_id}", v1=True)

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return bool(result.get("success", False))

get(person_id: PersonId, *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, include_field_values: bool = False, retries: int = 0, with_interaction_dates: bool = False, with_interaction_persons: bool = False) -> Person async

Get a single person by ID.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include (e.g., ["enriched", "global"])

None
include_field_values bool

If True, fetch embedded field values. This saves one API call when you need both person info and field values. Cannot be combined with field_ids/field_types.

False
retries int

Number of retries on 404 NotFoundError. Default is 0 (fail fast). Set to 2-3 if calling immediately after create() to handle eventual consistency lag.

0
with_interaction_dates bool

Include interaction date summaries (last/next meeting dates, email dates).

False
with_interaction_persons bool

Include person IDs for each interaction. Only applies when with_interaction_dates=True.

False

Returns:

Type Description
Person

Person object with requested field data.

Person

When include_field_values=True, the Person will have a field_values

Person

attribute containing the list of FieldValue objects.

Person

When with_interaction_dates=True, the Person will have interaction_dates

Person

and interactions populated.

Raises:

Type Description
NotFoundError

If person does not exist after all retries.

ValueError

If include_field_values is combined with field_ids/field_types.

Note

When combining with_interaction_dates with field_ids/field_types, two API calls are made internally and the results are merged.

Source code in affinity/services/persons.py
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
async def get(
    self,
    person_id: PersonId,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    include_field_values: bool = False,
    retries: int = 0,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
) -> Person:
    """
    Get a single person by ID.

    Args:
        person_id: The person ID
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        include_field_values: If True, fetch embedded field values. This saves
            one API call when you need both person info and field values.
            Cannot be combined with field_ids/field_types.
        retries: Number of retries on 404 NotFoundError. Default is 0 (fail fast).
            Set to 2-3 if calling immediately after create() to handle eventual
            consistency lag.
        with_interaction_dates: Include interaction date summaries (last/next
            meeting dates, email dates).
        with_interaction_persons: Include person IDs for each interaction.
            Only applies when with_interaction_dates=True.

    Returns:
        Person object with requested field data.
        When include_field_values=True, the Person will have a `field_values`
        attribute containing the list of FieldValue objects.
        When with_interaction_dates=True, the Person will have interaction_dates
        and interactions populated.

    Raises:
        NotFoundError: If person does not exist after all retries.
        ValueError: If include_field_values is combined with field_ids/field_types.

    Note:
        When combining with_interaction_dates with field_ids/field_types,
        two API calls are made internally and the results are merged.
    """
    return await self._get_with_retry(
        person_id,
        field_ids=field_ids,
        field_types=field_types,
        include_field_values=include_field_values,
        retries=retries,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
    )

get_associated_company_ids(person_id: PersonId, *, max_results: int | None = None) -> builtins.list[CompanyId] async

Get associated company IDs for a person.

V1-only: V2 does not expose person -> company associations directly. Uses GET /persons/{id} (V1) and returns organization_ids.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
max_results int | None

Maximum number of company IDs to return

None

Returns:

Type Description
list[CompanyId]

List of CompanyId values associated with this person

Note

The Person model already has company_ids populated from V1's organizationIds field. This method provides API parity with CompanyService.get_associated_person_ids().

Source code in affinity/services/persons.py
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
async def get_associated_company_ids(
    self,
    person_id: PersonId,
    *,
    max_results: int | None = None,
) -> builtins.list[CompanyId]:
    """
    Get associated company IDs for a person.

    V1-only: V2 does not expose person -> company associations directly.
    Uses GET `/persons/{id}` (V1) and returns `organization_ids`.

    Args:
        person_id: The person ID
        max_results: Maximum number of company IDs to return

    Returns:
        List of CompanyId values associated with this person

    Note:
        The Person model already has `company_ids` populated from V1's
        `organizationIds` field. This method provides API parity with
        `CompanyService.get_associated_person_ids()`.
    """
    data = await self._client.get(f"/persons/{person_id}", v1=True)
    # Defensive: handle potential {"person": {...}} wrapper
    # (consistent with CompanyService.get_associated_person_ids pattern)
    person = data.get("person") if isinstance(data, dict) else None
    source = person if isinstance(person, dict) else data
    org_ids = None
    if isinstance(source, dict):
        org_ids = source.get("organization_ids") or source.get("organizationIds")

    if not isinstance(org_ids, list):
        return []

    ids = [CompanyId(int(cid)) for cid in org_ids if cid is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

get_associated_company_ids_batch(person_ids: Sequence[PersonId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[PersonId, builtins.list[CompanyId]] async

Get company associations for multiple persons.

Makes one V1 API call per person.

Parameters:

Name Type Description Default
person_ids Sequence[PersonId]

Sequence of person IDs to fetch

required
on_error Literal['raise', 'skip']

How to handle errors - "raise" (default) or "skip" failed IDs

'raise'

Returns:

Type Description
dict[PersonId, list[CompanyId]]

Dict mapping person_id -> list of company_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/persons.py
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
async def get_associated_company_ids_batch(
    self,
    person_ids: Sequence[PersonId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[PersonId, builtins.list[CompanyId]]:
    """
    Get company associations for multiple persons.

    Makes one V1 API call per person.

    Args:
        person_ids: Sequence of person IDs to fetch
        on_error: How to handle errors - "raise" (default) or "skip" failed IDs

    Returns:
        Dict mapping person_id -> list of company_ids

    Raises:
        AffinityError: If on_error="raise" and any fetch fails.
    """
    result: dict[PersonId, builtins.list[CompanyId]] = {}
    for person_id in person_ids:
        try:
            result[person_id] = await self.get_associated_company_ids(person_id)
        except AffinityError:
            if on_error == "raise":
                raise
            # skip: continue without this person
        except Exception as e:
            if on_error == "raise":
                raise AffinityError(
                    f"Failed to get associations for person {person_id}: {e}"
                ) from e
            # skip: continue without this person
    return result

get_associated_opportunity_ids(person_id: PersonId, *, max_results: int | None = None) -> builtins.list[OpportunityId] async

Get associated opportunity IDs for a person.

V1-only: V2 does not expose person -> opportunity associations directly. Uses GET /persons/{id} (V1) and returns opportunity_ids.

Parameters:

Name Type Description Default
person_id PersonId

The person ID

required
max_results int | None

Maximum number of opportunity IDs to return

None

Returns:

Type Description
list[OpportunityId]

List of OpportunityId values associated with this person

Note

The Person model already has opportunity_ids populated from V1's opportunityIds field. This method provides API parity with OpportunityService.get_associated_person_ids().

Source code in affinity/services/persons.py
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
async def get_associated_opportunity_ids(
    self,
    person_id: PersonId,
    *,
    max_results: int | None = None,
) -> builtins.list[OpportunityId]:
    """
    Get associated opportunity IDs for a person.

    V1-only: V2 does not expose person -> opportunity associations directly.
    Uses GET `/persons/{id}` (V1) and returns `opportunity_ids`.

    Args:
        person_id: The person ID
        max_results: Maximum number of opportunity IDs to return

    Returns:
        List of OpportunityId values associated with this person

    Note:
        The Person model already has `opportunity_ids` populated from V1's
        `opportunityIds` field. This method provides API parity with
        `OpportunityService.get_associated_person_ids()`.
    """
    data = await self._client.get(f"/persons/{person_id}", v1=True)
    # Defensive: handle potential {"person": {...}} wrapper
    person = data.get("person") if isinstance(data, dict) else None
    source = person if isinstance(person, dict) else data
    opp_ids = None
    if isinstance(source, dict):
        opp_ids = source.get("opportunity_ids") or source.get("opportunityIds")

    if not isinstance(opp_ids, list):
        return []

    ids = [OpportunityId(int(oid)) for oid in opp_ids if oid is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

get_associated_opportunity_ids_batch(person_ids: Sequence[PersonId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[PersonId, builtins.list[OpportunityId]] async

Get opportunity associations for multiple persons.

Makes one V1 API call per person.

Parameters:

Name Type Description Default
person_ids Sequence[PersonId]

Sequence of person IDs to fetch

required
on_error Literal['raise', 'skip']

How to handle errors - "raise" (default) or "skip" failed IDs

'raise'

Returns:

Type Description
dict[PersonId, list[OpportunityId]]

Dict mapping person_id -> list of opportunity_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/persons.py
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
async def get_associated_opportunity_ids_batch(
    self,
    person_ids: Sequence[PersonId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[PersonId, builtins.list[OpportunityId]]:
    """
    Get opportunity associations for multiple persons.

    Makes one V1 API call per person.

    Args:
        person_ids: Sequence of person IDs to fetch
        on_error: How to handle errors - "raise" (default) or "skip" failed IDs

    Returns:
        Dict mapping person_id -> list of opportunity_ids

    Raises:
        AffinityError: If on_error="raise" and any fetch fails.
    """
    result: dict[PersonId, builtins.list[OpportunityId]] = {}
    for person_id in person_ids:
        try:
            result[person_id] = await self.get_associated_opportunity_ids(person_id)
        except AffinityError:
            if on_error == "raise":
                raise
            # skip: continue without this person
        except Exception as e:
            if on_error == "raise":
                raise AffinityError(
                    f"Failed to get associations for person {person_id}: {e}"
                ) from e
            # skip: continue without this person
    return result

get_fields(*, field_types: Sequence[FieldType] | None = None) -> builtins.list[FieldMetadata] async

Get metadata about person fields.

Cached for performance.

Source code in affinity/services/persons.py
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
async def get_fields(
    self,
    *,
    field_types: Sequence[FieldType] | None = None,
) -> builtins.list[FieldMetadata]:
    """
    Get metadata about person fields.

    Cached for performance.
    """
    params: dict[str, Any] = {}
    if field_types:
        params["fieldTypes"] = [field_type.value for field_type in field_types]

    data = await self._client.get(
        "/persons/fields",
        params=params or None,
        cache_key=f"person_fields:{','.join(field_types or [])}",
        cache_ttl=300,
    )

    return [FieldMetadata.model_validate(f) for f in data.get("data", [])]

get_first(*, filter: str | FilterExpression | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None) -> Person | None async

Get the first person matching the filter, or None if no match.

See PersonService.get_first() for details.

Source code in affinity/services/persons.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
async def get_first(
    self,
    *,
    filter: str | FilterExpression | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
) -> Person | None:
    """
    Get the first person matching the filter, or None if no match.

    See PersonService.get_first() for details.
    """
    page = await self.list(
        filter=filter,
        field_ids=field_ids,
        field_types=field_types,
        limit=1,
    )
    return page.data[0] if page.data else None

get_list_entries(person_id: PersonId) -> PaginatedResponse[ListEntry] async

Get all list entries for a person across all lists.

Source code in affinity/services/persons.py
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
async def get_list_entries(
    self,
    person_id: PersonId,
) -> PaginatedResponse[ListEntry]:
    """Get all list entries for a person across all lists."""
    data = await self._client.get(f"/persons/{person_id}/list-entries")

    return PaginatedResponse[ListEntry](
        data=[ListEntry.model_validate(e) for e in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

get_lists(person_id: PersonId) -> PaginatedResponse[ListSummary] async

Get all lists that contain this person.

Source code in affinity/services/persons.py
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
async def get_lists(
    self,
    person_id: PersonId,
) -> PaginatedResponse[ListSummary]:
    """Get all lists that contain this person."""
    data = await self._client.get(f"/persons/{person_id}/lists")

    return PaginatedResponse[ListSummary](
        data=[ListSummary.model_validate(item) for item in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

get_merge_status(task_id: str) -> MergeTask async

Check the status of a merge operation.

Source code in affinity/services/persons.py
1923
1924
1925
1926
async def get_merge_status(self, task_id: str) -> MergeTask:
    """Check the status of a merge operation."""
    data = await self._client.get(f"/tasks/person-merges/{task_id}")
    return MergeTask.model_validate(data)

iter(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None) -> AsyncIterator[Person]

Auto-paginate all persons.

Alias for all() (FR-006 public contract).

Source code in affinity/services/persons.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
def iter(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
) -> AsyncIterator[Person]:
    """
    Auto-paginate all persons.

    Alias for `all()` (FR-006 public contract).
    """
    return self.all(ids=ids, field_ids=field_ids, field_types=field_types, filter=filter)

list(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[Person] async

Get a page of persons.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression string, or a FilterExpression built via affinity.F

None
limit int | None

Maximum number of results

None
cursor str | None

Cursor to resume pagination (opaque; obtained from prior responses)

None

Returns:

Type Description
PaginatedResponse[Person]

Paginated response with persons

Source code in affinity/services/persons.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
async def list(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[Person]:
    """
    Get a page of persons.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include
        filter: V2 filter expression string, or a FilterExpression built via `affinity.F`
        limit: Maximum number of results
        cursor: Cursor to resume pagination (opaque; obtained from prior responses)

    Returns:
        Paginated response with persons
    """
    validate_entity_field_types(field_types, endpoint="person")
    if cursor is not None:
        if any(p is not None for p in (ids, field_ids, field_types, filter, limit)):
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context. Start a new pagination sequence without a cursor to change "
                "parameters."
            )
        data = await self._client.get_url(cursor)
    else:
        params: dict[str, Any] = {}
        if ids:
            params["ids"] = [int(id_) for id_ in ids]
        if field_ids:
            params["fieldIds"] = [str(field_id) for field_id in field_ids]
        if field_types:
            params["fieldTypes"] = [field_type.value for field_type in field_types]
        if filter is not None:
            filter_text = str(filter).strip()
            if filter_text:
                params["filter"] = filter_text
        if limit:
            params["limit"] = limit
        data = await self._client.get("/persons", params=params or None)

    return PaginatedResponse[Person](
        data=[Person.model_validate(p) for p in data.get("data", [])],
        pagination=PaginationInfo.model_validate(data.get("pagination", {})),
    )

merge(primary_id: PersonId, duplicate_id: PersonId) -> str async

Merge a duplicate person into a primary person.

Returns a task URL to check merge status.

Source code in affinity/services/persons.py
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
async def merge(
    self,
    primary_id: PersonId,
    duplicate_id: PersonId,
) -> str:
    """
    Merge a duplicate person into a primary person.

    Returns a task URL to check merge status.
    """
    if not self._client.enable_beta_endpoints:
        raise BetaEndpointDisabledError(
            "Person merge is a beta endpoint; set enable_beta_endpoints=True to use it."
        )
    result = await self._client.post(
        "/person-merges",
        json={
            "primaryPersonId": int(primary_id),
            "duplicatePersonId": int(duplicate_id),
        },
    )
    return str(result.get("taskUrl", ""))

pages(*, ids: Sequence[PersonId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, filter: str | FilterExpression | None = None, limit: int | None = None, cursor: str | None = None) -> AsyncIterator[PaginatedResponse[Person]] async

Iterate person pages (not items), yielding PaginatedResponse[Person].

Useful for ETL scripts that need checkpoint/resume via page.next_cursor.

Parameters:

Name Type Description Default
ids Sequence[PersonId] | None

Specific person IDs to fetch (batch lookup)

None
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include in response

None
field_types Sequence[FieldType] | None

Field types to include

None
filter str | FilterExpression | None

V2 filter expression string or FilterExpression

None
limit int | None

Maximum results per page

None
cursor str | None

Cursor to resume pagination

None

Yields:

Type Description
AsyncIterator[PaginatedResponse[Person]]

PaginatedResponse[Person] for each page

Source code in affinity/services/persons.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
async def pages(
    self,
    *,
    ids: Sequence[PersonId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    filter: str | FilterExpression | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> AsyncIterator[PaginatedResponse[Person]]:
    """
    Iterate person pages (not items), yielding `PaginatedResponse[Person]`.

    Useful for ETL scripts that need checkpoint/resume via `page.next_cursor`.

    Args:
        ids: Specific person IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include
        filter: V2 filter expression string or FilterExpression
        limit: Maximum results per page
        cursor: Cursor to resume pagination

    Yields:
        PaginatedResponse[Person] for each page
    """
    other_params = (ids, field_ids, field_types, filter, limit)
    if cursor is not None and any(p is not None for p in other_params):
        raise ValueError(
            "Cannot combine 'cursor' with other parameters; cursor encodes all query context. "
            "Start a new pagination sequence without a cursor to change parameters."
        )
    requested_cursor = cursor
    if cursor is not None:
        page = await self.list(cursor=cursor)
    else:
        page = await self.list(
            ids=ids,
            field_ids=field_ids,
            field_types=field_types,
            filter=filter,
            limit=limit,
        )
    while True:
        yield page
        if not page.has_next:
            return
        next_cursor = page.next_cursor
        if next_cursor is None or next_cursor == requested_cursor:
            return
        requested_cursor = next_cursor
        page = await self.list(cursor=next_cursor)

resolve(*, email: str | None = None, name: str | None = None) -> Person | None async

Find a single person by email or name.

This is a convenience helper that searches and returns the first exact match, or None if not found. Uses V1 search internally.

Source code in affinity/services/persons.py
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
async def resolve(
    self,
    *,
    email: str | None = None,
    name: str | None = None,
) -> Person | None:
    """
    Find a single person by email or name.

    This is a convenience helper that searches and returns the first exact match,
    or None if not found. Uses V1 search internally.
    """
    if not email and not name:
        raise ValueError("Must provide either email or name")

    term = email or name or ""
    async for page in self.search_pages(term, page_size=10):
        for person in page.data:
            if _person_matches(person, email=email, name=name):
                return person

    return None

resolve_all(*, email: str | None = None, name: str | None = None) -> builtins.list[Person] async

Find all persons matching an email or name.

Notes: - This auto-paginates V1 search results to collect exact matches. - Unlike resolve(), this returns every match in server-provided order.

Source code in affinity/services/persons.py
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
async def resolve_all(
    self,
    *,
    email: str | None = None,
    name: str | None = None,
) -> builtins.list[Person]:
    """
    Find all persons matching an email or name.

    Notes:
    - This auto-paginates V1 search results to collect exact matches.
    - Unlike resolve(), this returns every match in server-provided order.
    """
    if not email and not name:
        raise ValueError("Must provide either email or name")

    term = email or name or ""
    matches: builtins.list[Person] = []
    async for page in self.search_pages(term, page_size=10):
        for person in page.data:
            if _person_matches(person, email=email, name=name):
                matches.append(person)
    return matches

search(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> PaginatedResponse[Person] async

Search for persons by name or email.

Uses V1 API for search functionality.

Source code in affinity/services/persons.py
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
async def search(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> PaginatedResponse[Person]:
    """
    Search for persons by name or email.

    Uses V1 API for search functionality.
    """
    params: dict[str, Any] = {"term": term}
    if with_interaction_dates:
        params["with_interaction_dates"] = True
    if with_interaction_persons:
        params["with_interaction_persons"] = True
    if with_opportunities:
        params["with_opportunities"] = True
    if page_size:
        params["page_size"] = page_size
    if page_token:
        params["page_token"] = page_token

    data = await self._client.get("/persons", params=params, v1=True)
    items = [Person.model_validate(p) for p in data.get("persons", [])]
    return PaginatedResponse[Person](
        data=items,
        next_page_token=data.get("next_page_token"),
    )

search_all(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> AsyncIterator[Person] async

Iterate all V1 person-search results with automatic pagination.

Parameters:

Name Type Description Default
term str

Search term (name or email)

required
with_interaction_dates bool

Include interaction date data

False
with_interaction_persons bool

Include persons for interactions

False
with_opportunities bool

Include associated opportunity IDs

False
page_size int | None

Results per page (max 500)

None
page_token str | None

Resume from this pagination token

None

Yields:

Type Description
AsyncIterator[Person]

Person objects matching the search term

Source code in affinity/services/persons.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
async def search_all(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> AsyncIterator[Person]:
    """
    Iterate all V1 person-search results with automatic pagination.

    Args:
        term: Search term (name or email)
        with_interaction_dates: Include interaction date data
        with_interaction_persons: Include persons for interactions
        with_opportunities: Include associated opportunity IDs
        page_size: Results per page (max 500)
        page_token: Resume from this pagination token

    Yields:
        Person objects matching the search term
    """
    async for page in self.search_pages(
        term,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
        with_opportunities=with_opportunities,
        page_size=page_size,
        page_token=page_token,
    ):
        for person in page.data:
            yield person

search_pages(term: str, *, with_interaction_dates: bool = False, with_interaction_persons: bool = False, with_opportunities: bool = False, page_size: int | None = None, page_token: str | None = None) -> AsyncIterator[PaginatedResponse[Person]] async

Iterate V1 person-search result pages.

Useful for scripts that need checkpoint/resume via next_page_token.

Parameters:

Name Type Description Default
term str

Search term (name or email)

required
with_interaction_dates bool

Include interaction date data

False
with_interaction_persons bool

Include persons for interactions

False
with_opportunities bool

Include associated opportunity IDs

False
page_size int | None

Results per page (max 500)

None
page_token str | None

Resume from this pagination token

None

Yields:

Type Description
AsyncIterator[PaginatedResponse[Person]]

PaginatedResponse[Person] for each page

Source code in affinity/services/persons.py
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
async def search_pages(
    self,
    term: str,
    *,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    with_opportunities: bool = False,
    page_size: int | None = None,
    page_token: str | None = None,
) -> AsyncIterator[PaginatedResponse[Person]]:
    """
    Iterate V1 person-search result pages.

    Useful for scripts that need checkpoint/resume via `next_page_token`.

    Args:
        term: Search term (name or email)
        with_interaction_dates: Include interaction date data
        with_interaction_persons: Include persons for interactions
        with_opportunities: Include associated opportunity IDs
        page_size: Results per page (max 500)
        page_token: Resume from this pagination token

    Yields:
        PaginatedResponse[Person] for each page
    """
    requested_token = page_token
    page = await self.search(
        term,
        with_interaction_dates=with_interaction_dates,
        with_interaction_persons=with_interaction_persons,
        with_opportunities=with_opportunities,
        page_size=page_size,
        page_token=page_token,
    )
    while True:
        yield page
        next_token = page.next_page_token
        if not next_token or next_token == requested_token:
            return
        requested_token = next_token
        page = await self.search(
            term,
            with_interaction_dates=with_interaction_dates,
            with_interaction_persons=with_interaction_persons,
            with_opportunities=with_opportunities,
            page_size=page_size,
            page_token=next_token,
        )

update(person_id: PersonId, data: PersonUpdate) -> Person async

Update an existing person.

Note: To add emails/organizations, include existing values plus new ones.

Source code in affinity/services/persons.py
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
async def update(
    self,
    person_id: PersonId,
    data: PersonUpdate,
) -> Person:
    """
    Update an existing person.

    Note: To add emails/organizations, include existing values plus new ones.
    """
    payload = data.model_dump(
        by_alias=True,
        mode="json",
        exclude_unset=True,
        exclude_none=True,
    )

    result = await self._client.put(
        f"/persons/{person_id}",
        json=payload,
        v1=True,
    )

    if self._client.cache:
        self._client.cache.invalidate_prefix("person")

    return Person.model_validate(result)