Skip to content

Companies

Note: CompanyService includes two v1-only exceptions for company -> people associations: get_associated_person_ids(...) and get_associated_people(...). V2 does not expose a direct company -> people relationship endpoint, so these methods use the v1 organizations API under the hood. They are documented as exceptions and may be superseded when v2 adds parity.

Interaction Dates

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

  • Last meeting date: When the last calendar event with this company 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
  • Also the first email, first meeting and last chat message dates
from affinity import Affinity
from affinity.types import CompanyId

with Affinity(api_key="YOUR_API_KEY") as client:
    # Fetch company with interaction dates
    company = client.companies.get(
        CompanyId(123),
        with_interaction_dates=True,
        with_interaction_persons=True,  # Include person IDs for each interaction
    )

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

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

Many companies

get() with interaction dates makes one V1 call per company, plus one V2 call when field_ids or field_types is given. For many companies, use the async client's batch_get(ids, with_interaction_dates=True, ...): with field filters it reads the fields in one call per 100 ids and the dates in one call per company, so about N + N/100 calls instead of 2N. With on_error="skip" a company that can't be read is left out of the result.

For just the last and next meeting dates, the relationship-intelligence fields are cheaper: they come with the company records, one call per 100, with no per-company call:

from affinity.types import FieldType

for company in client.companies.iter(ids=ids[:100], field_types=[FieldType.RELATIONSHIP_INTELLIGENCE]):
    ...  # the last/next event fields are among company.fields

Pass at most 100 ids per call (the ids go in the URL). The other interaction dates and the interaction persons have no confirmed counterpart there, so use with_interaction_dates for those.

find() filters and sorts on Affinity's side (V2 search, beta), so only matching records are downloaded. The same methods exist on client.persons and on client.lists.entries(list_id).

find(
    where=None, *, sort=None, term=None, term_fields=None, field_ids=None,
    field_types=None, limit=None, total_count=False, cursor=None,
) -> PaginatedResponse[Company]
iter_find(where=None, *, sort=None, term=None, term_fields=None,
          field_ids=None, field_types=None) -> Iterator[Company]
find_body(body, *, field_ids=None, field_types=None, limit=None,
          total_count=False, cursor=None) -> PaginatedResponse[Company]
  • where: a Condition or a group from all_of(...) / any_of(...) (affinity.criteria).
  • sort: one Sort or a list of up to 5.
  • term: a keyword (3+ characters) matched against names, domains and emails, and against the fields in term_fields.
  • field_ids / field_types: the field values to return with each record.
  • limit: 1-100 records per page.
  • iter_find yields every matching record across pages. find_body takes a prebuilt search body (the API's SearchCriteria JSON).
from datetime import date
from affinity.criteria import Condition, Sort, all_of

page = client.companies.find(
    all_of(
        Condition("field-498220", "is-any-of", [3, 4]),
        Condition("affinity-data-last-funding-date", "is-after", date(2025, 1, 1)),
    ),
    sort=[Sort("affinity-data-total-funding-amount", "desc")],
    limit=50,
)

Next page: call find again with the same criteria and cursor=page.next_cursor. A cursor alone isn't enough: the search needs its body again.

Values: each condition's value type is read from the fields metadata when omitted (one cached request), and the operator is checked against the field. Company, person, list and dropdown fields take ids (dropdown values are option ids); dates are datetime.date or "YYYY-MM-DD" (not datetimes); relative windows are (6, "month").

Permissions: search needs the "Export All Organizations directory" permission (companies, persons) or "Export data from Lists" (list entries). Without it, find raises AuthorizationError naming the permission. Search is a read, so it's allowed in read-only mode.

search(term) is the separate name/domain search and needs no extra permission.

Bases: CompanySemanticSearchMixin, CompanyDiscoveryMixin, SingleFieldMixin, SearchMixin[Company]

Source code in affinity/services/companies.py
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 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
1006
1007
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
class CompanyService(
    CompanySemanticSearchMixin, CompanyDiscoveryMixin, SingleFieldMixin, SearchMixin[Company]
):
    _entity_path = "/companies"

    _search_model = Company

    def _search_path(self) -> str:
        return "/companies/search"

    def _search_fields(self) -> builtins.list[FieldMetadata]:
        return self.get_fields(includes=SEARCH_INCLUDES)

    """
    Service for managing companies (organizations).

    Note: Companies are called Organizations in the V1 API. This service
    uses V2 terminology throughout but routes to V1 for create/update/delete.
    """

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

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

    def list(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        limit: int | None = None,
        cursor: str | None = None,
        **_unsupported: Any,
    ) -> PaginatedResponse[Company]:
        """
        Get a page of companies.

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            limit: Maximum number of results (API default: 100)
            cursor: Cursor to resume pagination (opaque; obtained from prior responses)

        Returns:
            Paginated response with companies

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        validate_entity_field_types(field_types, endpoint="company")
        if cursor is not None:
            if any(p is not None for p in (ids, field_ids, field_types, 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:
            check_positive_limit(limit)
            ids = materialize_ids(ids)
            if no_ids(ids):
                return PaginatedResponse[Company]()
            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 limit is not None:
                params["limit"] = limit
            data = self._client.get("/companies", params=params or None)

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

    def get_first(
        self,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> Company | None:
        """
        Get the first company, or None if no results.

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

        Args:
            field_ids: Specific field IDs to include
            field_types: Field types to include

        Returns:
            First Company, or None if no results.

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        page = self.list(
            field_ids=field_ids,
            field_types=field_types,
            limit=1,
        )
        return page.data[0] if page.data else None

    def pages(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        limit: int | None = None,
        cursor: str | None = None,
        **_unsupported: Any,
    ) -> Iterator[PaginatedResponse[Company]]:
        """
        Iterate company pages (not items), yielding `PaginatedResponse[Company]`.

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

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            limit: Maximum results per page
            cursor: Cursor to resume pagination

        Yields:
            PaginatedResponse[Company] for each page
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        other_params = (ids, field_ids, field_types, 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
        guard = _CursorGuard(cursor)
        page = (
            self.list(cursor=cursor)
            if cursor is not None
            else self.list(ids=ids, field_ids=field_ids, field_types=field_types, limit=limit)
        )
        while True:
            yield page
            # Stop at the last page, or when paging can't progress (see _CursorGuard).
            if guard.last_page(requested_cursor, page):
                return
            requested_cursor = page.next_cursor
            page = self.list(cursor=requested_cursor)

    def all(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> Iterator[Company]:
        """
        Iterate through all companies with automatic pagination.

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include
            field_types: Field types to include

        Yields:
            Company objects

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")

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

        return PageIterator(fetch_page)

    def iter(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> Iterator[Company]:
        """
        Auto-paginate all companies.

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

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        return self.all(ids=ids, field_ids=field_ids, field_types=field_types)

    def get(
        self,
        company_id: CompanyId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Company:
        """
        Get a single company by ID.

        Args:
            company_id: The company ID
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            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:
            Company object with requested field data. When with_interaction_dates=True,
            the Company will have interaction_dates and interactions populated.

        Raises:
            NotFoundError: If company does not exist after all retries.

        Note:
            When combining with_interaction_dates with field_ids/field_types,
            two API calls are made internally and the results are merged.
        """
        last_error: NotFoundError | None = None
        attempts = retries + 1  # retries=0 means 1 attempt
        has_field_filters = field_ids is not None or field_types is not None

        for attempt in range(attempts):
            try:
                if with_interaction_dates:
                    # Fetch interaction data
                    v1_params: dict[str, Any] = {"with_interaction_dates": True}
                    if with_interaction_persons:
                        v1_params["with_interaction_persons"] = True
                    interaction_data = self._client.get(
                        f"/organizations/{company_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"/companies/{company_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 Company.model_validate(filtered_data)

                    # No field filtering, return interaction data directly
                    return Company.model_validate(interaction_data)

                # 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"/companies/{company_id}",
                    params=params or None,
                )
                return Company.model_validate(data)
            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 (with_interaction_dates=True)
        if last_error is not None and not with_interaction_dates:
            try:
                v1_data = self._client.get(f"/organizations/{company_id}", v1=True)
                return Company.model_validate(v1_data)
            except NotFoundError:
                pass  # V1 also failed, raise original V2 error

        raise last_error  # type: ignore[misc]

    def get_many(
        self,
        company_ids: Sequence[CompanyId],
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
    ) -> PaginatedResponse[Company]:
        """
        Fetch multiple companies by ID in a single API call.

        This is a convenience alias for ``list(ids=[...])``.

        Args:
            company_ids: Company IDs to fetch
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])

        Returns:
            Paginated response with companies

        Example:
            >>> companies = client.companies.get_many([CompanyId(1), CompanyId(2)])
            >>> for company in companies.data:
            ...     print(company.name)
        """
        return self.list(ids=company_ids, field_ids=field_ids, field_types=field_types)

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

        V1-only exception: V2 does not expose company -> people associations.
        Uses GET `/organizations/{id}` and returns `person_ids` if present.
        """
        data = self._client.get(f"/organizations/{company_id}", v1=True)
        organization = data.get("organization") if isinstance(data, dict) else None
        source = organization if isinstance(organization, dict) else data
        person_ids = None
        if isinstance(source, dict):
            person_ids = source.get("person_ids") or source.get("personIds")

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

        ids = [PersonId(int(value)) for value in person_ids if value is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    def get_associated_person_ids_batch(
        self,
        company_ids: Sequence[CompanyId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[CompanyId, builtins.list[PersonId]]:
        """
        Get person associations for multiple companies.

        Makes one V1 API call per company.

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

        Returns:
            Dict mapping company_id -> list of person_ids

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

    def get_associated_people(
        self,
        company_id: CompanyId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[Person]:
        """
        Get Person objects associated with a company.

        Uses V2 batch lookup for efficiency (1 API call per 100 persons
        instead of 1 per person).
        """
        person_ids = self.get_associated_person_ids(company_id, max_results=max_results)
        if not person_ids:
            return []

        # Use V2 batch lookup: GET /persons?ids=1&ids=2&ids=3
        # Note: person_ids is already truncated by get_associated_person_ids if max_results set
        params: dict[str, Any] = {"ids": [int(pid) for pid in person_ids]}

        people: builtins.list[Person] = []
        data = self._client.get("/persons", params=params)  # V2 batch
        for item in data.get("data", []):
            people.append(Person.model_validate(item))

        # Handle pagination if needed (>100 persons)
        # Note: max_results check is defensive - person_ids was already truncated above
        pagination = data.get("pagination") or {}
        next_url = pagination.get("nextUrl")
        while next_url and (max_results is None or len(people) < max_results):
            data = self._client.get_url(next_url)
            for item in data.get("data", []):
                people.append(Person.model_validate(item))
            next_url = (data.get("pagination") or {}).get("nextUrl")

        if max_results:
            return people[:max_results]
        return people

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

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

        Args:
            company_id: The company ID
            max_results: Maximum number of opportunity IDs to return

        Returns:
            List of OpportunityId values associated with this company
        """
        data = self._client.get(f"/organizations/{company_id}", v1=True)
        # Defensive: handle potential {"organization": {...}} wrapper
        organization = data.get("organization") if isinstance(data, dict) else None
        source = organization if isinstance(organization, 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,
        company_ids: Sequence[CompanyId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[CompanyId, builtins.list[OpportunityId]]:
        """
        Get opportunity associations for multiple companies.

        Makes one V1 API call per company.

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

        Returns:
            Dict mapping company_id -> list of opportunity_ids

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

    def get_list_entries(
        self,
        company_id: CompanyId,
        *,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[ListEntry]:
        """
        Get all list entries for a company across all lists.

        Returns comprehensive field data for each list entry. Each entry's ``entity_id`` is
        ``company_id`` and its ``entity_type`` is ``EntityType.ORGANIZATION``; ``entity`` is
        ``None`` (this endpoint doesn't embed the company). A ``cursor`` must come from this
        company's entries.
        """
        path = f"/companies/{company_id}/list-entries"
        if cursor is not None:
            if limit is not None:
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context. Start a new pagination sequence without a cursor to change "
                    "parameters."
                )
            check_list_entries_cursor(cursor, path)
            data = self._client.get_url(cursor)
        else:
            params: dict[str, Any] = {}
            check_positive_limit(limit)
            if limit is not None:
                params["limit"] = limit
            data = self._client.get(path, params=params or None)

        return entity_list_entries_page(
            data, entity_id=company_id, entity_type=EntityType.ORGANIZATION
        )

    def get_lists(
        self,
        company_id: CompanyId,
        *,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[ListSummary]:
        """Get all lists that contain this company."""
        if cursor is not None:
            if limit is not None:
                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] = {}
            check_positive_limit(limit)
            if limit is not None:
                params["limit"] = limit
            data = self._client.get(
                f"/companies/{company_id}/lists",
                params=params or None,
            )

        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,
        *,
        filter: str | None = None,
        includes: Sequence[str] | None = None,
    ) -> builtins.list[FieldMetadata]:
        """
        Get metadata about company fields.

        Cached for performance.

        Args:
            filter: Filter on the field name: ``name="Location"`` (exact) or ``name=~Loc``
                (substring); both case-sensitive. Combine clauses with ``|``. Only ``name``
                is filterable; anything else is rejected with 400.
            includes: Extra properties per field: ``"filterability"``, ``"sortability"``
                (read them via ``is_filterable`` / ``is_sortable``).
        """
        params, cache_key = build_fields_query(
            "company_fields:_all_",
            filter=filter,
            includes=includes,
        )

        data = self._client.get_all_pages(
            "/companies/fields",
            params=params or None,
            cache_key=cache_key,
            cache_ttl=300,
        )

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

    def get_field_dropdown_options(
        self, field_id: AnyFieldId, *, with_status_types: bool = False
    ) -> builtins.list[DropdownOption]:
        """All options of a company dropdown, ranked-dropdown or status field (every page).

        Options with ``type``, ``rank``, ``color`` and (status fields) ``status_category`` /
        ``win_rate``. Options of global company fields can only be read; list-specific fields'
        options are managed through ``client.lists``. ``with_status_types=True``: see
        ``lists.get_field_dropdown_options``.
        """
        data = self._client.get_all_pages(
            options_path(field_id, list_id=None, entity="companies"),
            params={"limit": 100},
            min_api_version=DROPDOWN_OPTION_WRITES_MIN_API_VERSION if with_status_types else None,
        )
        return parse_options(data)

    def get_field_values(
        self,
        company_id: CompanyId,
        *,
        ids: Sequence[AnyFieldId | str] | None = None,
    ) -> FieldValues:
        """
        Field values of one company, keyed by field id (``GET /v2/companies/{id}/fields``).

        Args:
            company_id: The company.
            ids: Only these fields (server-side filter); all fields when omitted.
        """
        params = {"ids": [str(fid) for fid in ids]} if ids else None
        data = self._client.get_all_pages(f"/companies/{company_id}/fields", params=params)
        return FieldValues.model_validate(data.get("data", []))

    def batch_update_fields(
        self,
        company_id: CompanyId,
        updates: Mapping[AnyFieldId | str, Any],
        *,
        value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None,
    ) -> BatchOperationResponse:
        """
        Update several field values of one company in one request.

        Affinity applies the whole batch or none of it; each update replaces the field's value
        and ``None`` (with a type) clears it. Global, enriched and Source of Introduction
        fields are all writable. At most 100 updates, and 100 values per multi-value field.

        Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an
        unpinned client sends that version for this call; a client pinned to an older version
        raises ``ApiVersionTooOldError`` without sending anything.

        Args:
            company_id: The company.
            updates: Field id -> new value. Values are auto-typed (str→text, int/float→number,
                datetime/date→datetime) unless the field has an entry in ``value_types``.
            value_types: Field id -> value type (e.g. ``"dropdown-multi"``); needed for lists
                (multi-value fields) and ``None`` (clear).
        """
        items = _batch_update_items(updates, value_types)
        result = self._client.patch(
            f"/companies/{company_id}/fields",
            json={"operation": "update-fields", "updates": items},
            min_api_version=FIELD_WRITES_MIN_API_VERSION,
        )
        return BatchOperationResponse.model_validate(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[Company]:
        """
        Search for companies by name or domain.

        Uses V1 API for search functionality not available in V2.

        Args:
            term: Search term (name or domain)
            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:
            Dict with 'organizations' and 'next_page_token'
        """
        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("/organizations", params=params, v1=True)
        items = [Company.model_validate(o) for o in data.get("organizations", [])]
        return PaginatedResponse[Company](
            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[Company]]:
        """
        Iterate V1 company-search result pages.

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

        Args:
            term: Search term (name or domain)
            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[Company] 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[Company]:
        """
        Iterate all V1 company-search results with automatic pagination.

        Args:
            term: Search term (name or domain)
            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:
            Company 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,
        *,
        domain: str | None = None,
        name: str | None = None,
    ) -> Company | None:
        """
        Find a single company by domain 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:
            domain: Domain to search for (e.g., "acme.com")
            name: Company name to search for

        Returns:
            The matching Company, or None if not found

        Raises:
            ValueError: If neither domain nor name is provided

        Note:
            If multiple matches are found, returns the first one.
            For disambiguation, use search() directly.
        """
        if not domain and not name:
            raise ValueError("Must provide either domain or name")

        term = domain or name or ""
        result = self.search(term, page_size=10)

        for company in result.data:
            if domain and company.domain and company.domain.lower() == domain.lower():
                return company
            if name and company.name and company.name.lower() == name.lower():
                return company

        return None

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

    _DEDUP_PAGE_CAP = 3  # 3 pages x 500 = 1500 fuzzy results scanned per search term

    def create(self, data: CompanyCreate, *, if_not_exists: bool = True) -> Company:
        """
        Create a new company.

        Args:
            data: Company creation data
            if_not_exists: If True (default), check for an existing company with
                the same name (case-insensitive exact match) OR the same domain
                (matched against the company's primary domain AND all entries
                in its `domains` list). Globals in Affinity's shared directory
                are treated as duplicates — per the API docs, POST /organizations
                always creates a tenant-scoped copy, so creating against an
                existing global would produce a genuine duplicate. Raises
                DuplicateEntityError carrying the existing company's ID and
                `existing_is_global` flag, so callers can use the global ID
                directly (e.g., via List Entries) instead of POSTing a copy.
                Uses V1 search_pages() with page_size=500, capped at 3 pages.
                Set to False to skip the check and create unconditionally.

        Returns:
            Created company

        Raises:
            DuplicateEntityError: When if_not_exists=True and an exact-name or
                exact-domain match already exists (tenant-scoped OR global).

        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 Company 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
        """
        if if_not_exists:
            existing = self._find_exact_duplicate(name=data.name, domain=data.domain)
            if existing is not None:
                if existing.is_global:
                    message = (
                        f"A global Affinity directory record matches name={data.name!r} "
                        f"or domain={data.domain!r} (id={existing.id}). Global records "
                        f"are shared across tenants — use this ID directly (e.g., via "
                        f"List Entries) instead of creating a tenant-scoped duplicate."
                    )
                else:
                    message = (
                        f"Company with name={data.name!r} or domain={data.domain!r} "
                        f"already exists (id={existing.id})"
                    )
                raise DuplicateEntityError(
                    message,
                    entity_type="company",
                    existing_id=int(existing.id),
                    existing_name=existing.name,
                    existing_domain=existing.domain,
                    existing_is_global=bool(existing.is_global),
                )

        payload = data.model_dump(by_alias=True, mode="json", exclude_none=True)
        if not data.person_ids:
            payload.pop("person_ids", None)

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

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

        return Company.model_validate(result)

    @staticmethod
    def _company_matches(company: Company, name_lower: str, domain_lower: str | None) -> bool:
        """True iff company's name or any domain matches exactly (case-insensitive)."""
        if company.name and company.name.lower() == name_lower:
            return True
        if domain_lower:
            if company.domain and company.domain.lower() == domain_lower:
                return True
            for d in company.domains or []:
                if d and d.lower() == domain_lower:
                    return True
        return False

    def _find_exact_duplicate(self, *, name: str, domain: str | None) -> Company | None:
        """Search V1 for an exact-name or exact-domain match. Returns None if no match.

        Domain-first search order: domains are globally more unique than names,
        so if a domain is supplied, we search by domain first. Falls back to a
        name search only when the domain search came up empty and the name
        differs from the domain string.

        Iterates at most `_DEDUP_PAGE_CAP` pages per term (1500 fuzzy results).
        """
        name_lower = name.strip().lower()
        domain_lower = domain.strip().lower() if domain else None

        def _scan(term: str) -> Company | None:
            for page_num, page in enumerate(self.search_pages(term, page_size=500)):
                for company in page.data:
                    if self._company_matches(company, name_lower, domain_lower):
                        return company
                if page_num + 1 >= self._DEDUP_PAGE_CAP:
                    break
                if not page.next_page_token:
                    break
            return None

        if domain_lower:
            # domain is guaranteed non-None when domain_lower is set
            hit = _scan(domain or "")
            if hit is not None:
                return hit
            if name_lower and name_lower != domain_lower:
                return _scan(name)
            return None

        return _scan(name)

    def update(
        self,
        company_id: CompanyId,
        data: CompanyUpdate,
    ) -> Company:
        """
        Update an existing company.

        Note: Cannot update name/domain of global companies.
        """
        payload = data.model_dump(
            by_alias=True,
            mode="json",
            exclude_unset=True,
            exclude_none=True,
        )

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

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

        return Company.model_validate(result)

    def delete(self, company_id: CompanyId) -> bool:
        """
        Delete a company.

        Note: Cannot delete global companies.
        """
        result = self._client.delete(f"/organizations/{company_id}", v1=True)
        invalidate_all_list_sizes(self._client)

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

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

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

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

        Returns a task URL to check merge status.
        """
        result = self._client.post(
            "/company-merges",
            json={
                "primaryCompanyId": int(primary_id),
                "duplicateCompanyId": int(duplicate_id),
            },
        )
        return merge_task_url(result, "company")

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

    # =========================================================================
    # Merge history and relationships (V2)
    # =========================================================================

    def list_merges(
        self,
        *,
        status: str | None = None,
        task_id: str | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[CompanyMergeState]:
        """One page of past company merges, newest first.

        ``status`` is ``"in-progress"``, ``"success"`` or ``"failed"``; ``task_id`` (or the task
        URL a merge returned) limits it to one merge task. Needs the "Manage duplicates"
        permission and the organization admin role (otherwise ``AuthorizationError``).
        """
        check_cursor_alone(cursor, status, task_id, limit)
        if cursor is not None:
            return page_of(CompanyMergeState, self._client.get_url(cursor))
        params = merge_params(status=status, task_id=task_id, limit=limit)
        return page_of(
            CompanyMergeState, self._client.get("/company-merges", params=params or None)
        )

    def iter_merges(
        self, *, status: str | None = None, task_id: str | None = None
    ) -> Iterator[CompanyMergeState]:
        """All past company merges matching the filters (every page)."""

        def fetch_page(next_url: str | None) -> PaginatedResponse[CompanyMergeState]:
            if next_url:
                return self.list_merges(cursor=next_url)
            return self.list_merges(status=status, task_id=task_id)

        return PageIterator(fetch_page)

    def get_merge_state(self, merge_id: int) -> CompanyMergeState:
        """One past company merge (see :meth:`list_merges`)."""
        return CompanyMergeState.model_validate(
            self._client.get(f"/company-merges/{int(merge_id)}")
        )

    def list_relationships(
        self,
        company_id: CompanyId,
        *,
        min_score: float | None = None,
        order: Literal["asc", "desc"] = "desc",
        limit: int | None = None,
        total_count: bool = False,
        cursor: str | None = None,
    ) -> PaginatedResponse[Relationship]:
        """One page of the relationships between your team and this company's people.

        Strongest first (``order="asc"`` for weakest first). ``min_score`` (0.0-1.0) keeps
        relationships at least that strong; relationships known only from LinkedIn have score 0,
        so any ``min_score`` above 0 drops them. ``limit`` is 1-100 (API default 20). Needs
        Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).
        """
        if cursor is not None:
            if min_score is not None or limit is not None or total_count or order != "desc":
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context."
                )
            return page_of(
                Relationship,
                self._client.get_url(cursor, min_api_version=RELATIONSHIPS_MIN_API_VERSION),
            )
        params = relationship_params(
            min_score=min_score, order=order, limit=limit, total_count=total_count
        )
        return page_of(
            Relationship,
            self._client.get(
                f"/companies/{int(company_id)}/relationships",
                params=params or None,
                min_api_version=RELATIONSHIPS_MIN_API_VERSION,
            ),
        )

    def iter_relationships(
        self,
        company_id: CompanyId,
        *,
        min_score: float | None = None,
        order: Literal["asc", "desc"] = "desc",
        limit: int | None = None,
    ) -> Iterator[Relationship]:
        """All relationships for this company (every page); see :meth:`list_relationships`."""

        def fetch_page(next_url: str | None) -> PaginatedResponse[Relationship]:
            if next_url:
                return self.list_relationships(company_id, cursor=next_url)
            return self.list_relationships(
                company_id, min_score=min_score, order=order, limit=limit
            )

        return PageIterator(fetch_page)

    # =========================================================================
    # Notes (V2)
    # =========================================================================

    def list_notes(
        self,
        company_id: CompanyId,
        *,
        creator_id: int | None = None,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        updated_after: datetime | None = None,
        limit: int | None = None,
        total_count: bool = False,
        cursor: str | None = None,
    ) -> PaginatedResponse[NoteV2]:
        """One page of this company's notes as V2 notes (``NoteV2``; replies not included).

        Filters: ``creator_id``, ``created_after`` (inclusive) / ``created_before`` (exclusive),
        ``updated_after``, rounded outward to whole seconds. ``limit`` is 1-100.
        Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).
        """
        check_cursor_alone(
            cursor, creator_id, created_after, created_before, updated_after, limit, total_count
        )
        if cursor is not None:
            return page_of(
                NoteV2, self._client.get_url(cursor, min_api_version=COMPANY_NOTES_MIN_API_VERSION)
            )
        params = note_params(
            creator_id=creator_id,
            created_after=created_after,
            created_before=created_before,
            updated_after=updated_after,
            limit=limit,
            total_count=total_count,
        )
        return page_of(
            NoteV2,
            self._client.get(
                f"/companies/{int(company_id)}/notes",
                params=params or None,
                min_api_version=COMPANY_NOTES_MIN_API_VERSION,
            ),
        )

    def iter_notes(
        self,
        company_id: CompanyId,
        *,
        creator_id: int | None = None,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        updated_after: datetime | None = None,
        limit: int | None = None,
    ) -> Iterator[NoteV2]:
        """All of this company's notes (every page); see :meth:`list_notes`."""

        def fetch_page(next_url: str | None) -> PaginatedResponse[NoteV2]:
            if next_url:
                return self.list_notes(company_id, cursor=next_url)
            return self.list_notes(
                company_id,
                creator_id=creator_id,
                created_after=created_after,
                created_before=created_before,
                updated_after=updated_after,
                limit=limit,
            )

        return PageIterator(fetch_page)

all(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> Iterator[Company]

Iterate through all companies with automatic pagination.

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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

Yields:

Type Description
Company

Company objects

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def all(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> Iterator[Company]:
    """
    Iterate through all companies with automatic pagination.

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include
        field_types: Field types to include

    Yields:
        Company objects

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")

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

    return PageIterator(fetch_page)

batch_update_fields(company_id: CompanyId, updates: Mapping[AnyFieldId | str, Any], *, value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None) -> BatchOperationResponse

Update several field values of one company in one request.

Affinity applies the whole batch or none of it; each update replaces the field's value and None (with a type) clears it. Global, enriched and Source of Introduction fields are all writable. At most 100 updates, and 100 values per multi-value field.

Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an unpinned client sends that version for this call; a client pinned to an older version raises ApiVersionTooOldError without sending anything.

Parameters:

Name Type Description Default
company_id CompanyId

The company.

required
updates Mapping[AnyFieldId | str, Any]

Field id -> new value. Values are auto-typed (str→text, int/float→number, datetime/date→datetime) unless the field has an entry in value_types.

required
value_types Mapping[AnyFieldId | str, FieldValueType | str] | None

Field id -> value type (e.g. "dropdown-multi"); needed for lists (multi-value fields) and None (clear).

None
Source code in affinity/services/companies.py
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
def batch_update_fields(
    self,
    company_id: CompanyId,
    updates: Mapping[AnyFieldId | str, Any],
    *,
    value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None,
) -> BatchOperationResponse:
    """
    Update several field values of one company in one request.

    Affinity applies the whole batch or none of it; each update replaces the field's value
    and ``None`` (with a type) clears it. Global, enriched and Source of Introduction
    fields are all writable. At most 100 updates, and 100 values per multi-value field.

    Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an
    unpinned client sends that version for this call; a client pinned to an older version
    raises ``ApiVersionTooOldError`` without sending anything.

    Args:
        company_id: The company.
        updates: Field id -> new value. Values are auto-typed (str→text, int/float→number,
            datetime/date→datetime) unless the field has an entry in ``value_types``.
        value_types: Field id -> value type (e.g. ``"dropdown-multi"``); needed for lists
            (multi-value fields) and ``None`` (clear).
    """
    items = _batch_update_items(updates, value_types)
    result = self._client.patch(
        f"/companies/{company_id}/fields",
        json={"operation": "update-fields", "updates": items},
        min_api_version=FIELD_WRITES_MIN_API_VERSION,
    )
    return BatchOperationResponse.model_validate(result)

create(data: CompanyCreate, *, if_not_exists: bool = True) -> Company

Create a new company.

Parameters:

Name Type Description Default
data CompanyCreate

Company creation data

required
if_not_exists bool

If True (default), check for an existing company with the same name (case-insensitive exact match) OR the same domain (matched against the company's primary domain AND all entries in its domains list). Globals in Affinity's shared directory are treated as duplicates — per the API docs, POST /organizations always creates a tenant-scoped copy, so creating against an existing global would produce a genuine duplicate. Raises DuplicateEntityError carrying the existing company's ID and existing_is_global flag, so callers can use the global ID directly (e.g., via List Entries) instead of POSTing a copy. Uses V1 search_pages() with page_size=500, capped at 3 pages. Set to False to skip the check and create unconditionally.

True

Returns:

Type Description
Company

Created company

Raises:

Type Description
DuplicateEntityError

When if_not_exists=True and an exact-name or exact-domain match already exists (tenant-scoped OR global).

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 Company 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

Source code in affinity/services/companies.py
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
def create(self, data: CompanyCreate, *, if_not_exists: bool = True) -> Company:
    """
    Create a new company.

    Args:
        data: Company creation data
        if_not_exists: If True (default), check for an existing company with
            the same name (case-insensitive exact match) OR the same domain
            (matched against the company's primary domain AND all entries
            in its `domains` list). Globals in Affinity's shared directory
            are treated as duplicates — per the API docs, POST /organizations
            always creates a tenant-scoped copy, so creating against an
            existing global would produce a genuine duplicate. Raises
            DuplicateEntityError carrying the existing company's ID and
            `existing_is_global` flag, so callers can use the global ID
            directly (e.g., via List Entries) instead of POSTing a copy.
            Uses V1 search_pages() with page_size=500, capped at 3 pages.
            Set to False to skip the check and create unconditionally.

    Returns:
        Created company

    Raises:
        DuplicateEntityError: When if_not_exists=True and an exact-name or
            exact-domain match already exists (tenant-scoped OR global).

    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 Company 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
    """
    if if_not_exists:
        existing = self._find_exact_duplicate(name=data.name, domain=data.domain)
        if existing is not None:
            if existing.is_global:
                message = (
                    f"A global Affinity directory record matches name={data.name!r} "
                    f"or domain={data.domain!r} (id={existing.id}). Global records "
                    f"are shared across tenants — use this ID directly (e.g., via "
                    f"List Entries) instead of creating a tenant-scoped duplicate."
                )
            else:
                message = (
                    f"Company with name={data.name!r} or domain={data.domain!r} "
                    f"already exists (id={existing.id})"
                )
            raise DuplicateEntityError(
                message,
                entity_type="company",
                existing_id=int(existing.id),
                existing_name=existing.name,
                existing_domain=existing.domain,
                existing_is_global=bool(existing.is_global),
            )

    payload = data.model_dump(by_alias=True, mode="json", exclude_none=True)
    if not data.person_ids:
        payload.pop("person_ids", None)

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

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

    return Company.model_validate(result)

delete(company_id: CompanyId) -> bool

Delete a company.

Note: Cannot delete global companies.

Source code in affinity/services/companies.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
def delete(self, company_id: CompanyId) -> bool:
    """
    Delete a company.

    Note: Cannot delete global companies.
    """
    result = self._client.delete(f"/organizations/{company_id}", v1=True)
    invalidate_all_list_sizes(self._client)

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

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

get(company_id: CompanyId, *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, retries: int = 0, with_interaction_dates: bool = False, with_interaction_persons: bool = False) -> Company

Get a single company by ID.

Parameters:

Name Type Description Default
company_id CompanyId

The company 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
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
Company

Company object with requested field data. When with_interaction_dates=True,

Company

the Company will have interaction_dates and interactions populated.

Raises:

Type Description
NotFoundError

If company does not exist after all retries.

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/companies.py
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
def get(
    self,
    company_id: CompanyId,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    retries: int = 0,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
) -> Company:
    """
    Get a single company by ID.

    Args:
        company_id: The company ID
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        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:
        Company object with requested field data. When with_interaction_dates=True,
        the Company will have interaction_dates and interactions populated.

    Raises:
        NotFoundError: If company does not exist after all retries.

    Note:
        When combining with_interaction_dates with field_ids/field_types,
        two API calls are made internally and the results are merged.
    """
    last_error: NotFoundError | None = None
    attempts = retries + 1  # retries=0 means 1 attempt
    has_field_filters = field_ids is not None or field_types is not None

    for attempt in range(attempts):
        try:
            if with_interaction_dates:
                # Fetch interaction data
                v1_params: dict[str, Any] = {"with_interaction_dates": True}
                if with_interaction_persons:
                    v1_params["with_interaction_persons"] = True
                interaction_data = self._client.get(
                    f"/organizations/{company_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"/companies/{company_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 Company.model_validate(filtered_data)

                # No field filtering, return interaction data directly
                return Company.model_validate(interaction_data)

            # 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"/companies/{company_id}",
                params=params or None,
            )
            return Company.model_validate(data)
        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 (with_interaction_dates=True)
    if last_error is not None and not with_interaction_dates:
        try:
            v1_data = self._client.get(f"/organizations/{company_id}", v1=True)
            return Company.model_validate(v1_data)
        except NotFoundError:
            pass  # V1 also failed, raise original V2 error

    raise last_error  # type: ignore[misc]

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

Get associated opportunity IDs for a company.

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

Parameters:

Name Type Description Default
company_id CompanyId

The company 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 company

Source code in affinity/services/companies.py
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
def get_associated_opportunity_ids(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[OpportunityId]:
    """
    Get associated opportunity IDs for a company.

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

    Args:
        company_id: The company ID
        max_results: Maximum number of opportunity IDs to return

    Returns:
        List of OpportunityId values associated with this company
    """
    data = self._client.get(f"/organizations/{company_id}", v1=True)
    # Defensive: handle potential {"organization": {...}} wrapper
    organization = data.get("organization") if isinstance(data, dict) else None
    source = organization if isinstance(organization, 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(company_ids: Sequence[CompanyId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[CompanyId, builtins.list[OpportunityId]]

Get opportunity associations for multiple companies.

Makes one V1 API call per company.

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Sequence of company IDs to fetch

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

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

'raise'

Returns:

Type Description
dict[CompanyId, list[OpportunityId]]

Dict mapping company_id -> list of opportunity_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/companies.py
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
def get_associated_opportunity_ids_batch(
    self,
    company_ids: Sequence[CompanyId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[CompanyId, builtins.list[OpportunityId]]:
    """
    Get opportunity associations for multiple companies.

    Makes one V1 API call per company.

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

    Returns:
        Dict mapping company_id -> list of opportunity_ids

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

get_associated_people(company_id: CompanyId, *, max_results: int | None = None) -> builtins.list[Person]

Get Person objects associated with a company.

Uses V2 batch lookup for efficiency (1 API call per 100 persons instead of 1 per person).

Source code in affinity/services/companies.py
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
def get_associated_people(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[Person]:
    """
    Get Person objects associated with a company.

    Uses V2 batch lookup for efficiency (1 API call per 100 persons
    instead of 1 per person).
    """
    person_ids = self.get_associated_person_ids(company_id, max_results=max_results)
    if not person_ids:
        return []

    # Use V2 batch lookup: GET /persons?ids=1&ids=2&ids=3
    # Note: person_ids is already truncated by get_associated_person_ids if max_results set
    params: dict[str, Any] = {"ids": [int(pid) for pid in person_ids]}

    people: builtins.list[Person] = []
    data = self._client.get("/persons", params=params)  # V2 batch
    for item in data.get("data", []):
        people.append(Person.model_validate(item))

    # Handle pagination if needed (>100 persons)
    # Note: max_results check is defensive - person_ids was already truncated above
    pagination = data.get("pagination") or {}
    next_url = pagination.get("nextUrl")
    while next_url and (max_results is None or len(people) < max_results):
        data = self._client.get_url(next_url)
        for item in data.get("data", []):
            people.append(Person.model_validate(item))
        next_url = (data.get("pagination") or {}).get("nextUrl")

    if max_results:
        return people[:max_results]
    return people

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

Get associated person IDs for a company.

V1-only exception: V2 does not expose company -> people associations. Uses GET /organizations/{id} and returns person_ids if present.

Source code in affinity/services/companies.py
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
def get_associated_person_ids(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[PersonId]:
    """
    Get associated person IDs for a company.

    V1-only exception: V2 does not expose company -> people associations.
    Uses GET `/organizations/{id}` and returns `person_ids` if present.
    """
    data = self._client.get(f"/organizations/{company_id}", v1=True)
    organization = data.get("organization") if isinstance(data, dict) else None
    source = organization if isinstance(organization, dict) else data
    person_ids = None
    if isinstance(source, dict):
        person_ids = source.get("person_ids") or source.get("personIds")

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

    ids = [PersonId(int(value)) for value in person_ids if value is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

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

Get person associations for multiple companies.

Makes one V1 API call per company.

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Sequence of company IDs to fetch

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

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

'raise'

Returns:

Type Description
dict[CompanyId, list[PersonId]]

Dict mapping company_id -> list of person_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/companies.py
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
def get_associated_person_ids_batch(
    self,
    company_ids: Sequence[CompanyId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[CompanyId, builtins.list[PersonId]]:
    """
    Get person associations for multiple companies.

    Makes one V1 API call per company.

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

    Returns:
        Dict mapping company_id -> list of person_ids

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

get_field_dropdown_options(field_id: AnyFieldId, *, with_status_types: bool = False) -> builtins.list[DropdownOption]

All options of a company dropdown, ranked-dropdown or status field (every page).

Options with type, rank, color and (status fields) status_category / win_rate. Options of global company fields can only be read; list-specific fields' options are managed through client.lists. with_status_types=True: see lists.get_field_dropdown_options.

Source code in affinity/services/companies.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def get_field_dropdown_options(
    self, field_id: AnyFieldId, *, with_status_types: bool = False
) -> builtins.list[DropdownOption]:
    """All options of a company dropdown, ranked-dropdown or status field (every page).

    Options with ``type``, ``rank``, ``color`` and (status fields) ``status_category`` /
    ``win_rate``. Options of global company fields can only be read; list-specific fields'
    options are managed through ``client.lists``. ``with_status_types=True``: see
    ``lists.get_field_dropdown_options``.
    """
    data = self._client.get_all_pages(
        options_path(field_id, list_id=None, entity="companies"),
        params={"limit": 100},
        min_api_version=DROPDOWN_OPTION_WRITES_MIN_API_VERSION if with_status_types else None,
    )
    return parse_options(data)

get_field_values(company_id: CompanyId, *, ids: Sequence[AnyFieldId | str] | None = None) -> FieldValues

Field values of one company, keyed by field id (GET /v2/companies/{id}/fields).

Parameters:

Name Type Description Default
company_id CompanyId

The company.

required
ids Sequence[AnyFieldId | str] | None

Only these fields (server-side filter); all fields when omitted.

None
Source code in affinity/services/companies.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
def get_field_values(
    self,
    company_id: CompanyId,
    *,
    ids: Sequence[AnyFieldId | str] | None = None,
) -> FieldValues:
    """
    Field values of one company, keyed by field id (``GET /v2/companies/{id}/fields``).

    Args:
        company_id: The company.
        ids: Only these fields (server-side filter); all fields when omitted.
    """
    params = {"ids": [str(fid) for fid in ids]} if ids else None
    data = self._client.get_all_pages(f"/companies/{company_id}/fields", params=params)
    return FieldValues.model_validate(data.get("data", []))

get_fields(*, filter: str | None = None, includes: Sequence[str] | None = None) -> builtins.list[FieldMetadata]

Get metadata about company fields.

Cached for performance.

Parameters:

Name Type Description Default
filter str | None

Filter on the field name: name="Location" (exact) or name=~Loc (substring); both case-sensitive. Combine clauses with |. Only name is filterable; anything else is rejected with 400.

None
includes Sequence[str] | None

Extra properties per field: "filterability", "sortability" (read them via is_filterable / is_sortable).

None
Source code in affinity/services/companies.py
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
def get_fields(
    self,
    *,
    filter: str | None = None,
    includes: Sequence[str] | None = None,
) -> builtins.list[FieldMetadata]:
    """
    Get metadata about company fields.

    Cached for performance.

    Args:
        filter: Filter on the field name: ``name="Location"`` (exact) or ``name=~Loc``
            (substring); both case-sensitive. Combine clauses with ``|``. Only ``name``
            is filterable; anything else is rejected with 400.
        includes: Extra properties per field: ``"filterability"``, ``"sortability"``
            (read them via ``is_filterable`` / ``is_sortable``).
    """
    params, cache_key = build_fields_query(
        "company_fields:_all_",
        filter=filter,
        includes=includes,
    )

    data = self._client.get_all_pages(
        "/companies/fields",
        params=params or None,
        cache_key=cache_key,
        cache_ttl=300,
    )

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

get_first(*, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> Company | None

Get the first company, or None if no results.

This is a convenience method equivalent to

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

Parameters:

Name Type Description Default
field_ids Sequence[AnyFieldId] | None

Specific field IDs to include

None
field_types Sequence[FieldType] | None

Field types to include

None

Returns:

Type Description
Company | None

First Company, or None if no results.

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def get_first(
    self,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> Company | None:
    """
    Get the first company, or None if no results.

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

    Args:
        field_ids: Specific field IDs to include
        field_types: Field types to include

    Returns:
        First Company, or None if no results.

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    page = self.list(
        field_ids=field_ids,
        field_types=field_types,
        limit=1,
    )
    return page.data[0] if page.data else None

get_list_entries(company_id: CompanyId, *, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[ListEntry]

Get all list entries for a company across all lists.

Returns comprehensive field data for each list entry. Each entry's entity_id is company_id and its entity_type is EntityType.ORGANIZATION; entity is None (this endpoint doesn't embed the company). A cursor must come from this company's entries.

Source code in affinity/services/companies.py
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
def get_list_entries(
    self,
    company_id: CompanyId,
    *,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[ListEntry]:
    """
    Get all list entries for a company across all lists.

    Returns comprehensive field data for each list entry. Each entry's ``entity_id`` is
    ``company_id`` and its ``entity_type`` is ``EntityType.ORGANIZATION``; ``entity`` is
    ``None`` (this endpoint doesn't embed the company). A ``cursor`` must come from this
    company's entries.
    """
    path = f"/companies/{company_id}/list-entries"
    if cursor is not None:
        if limit is not None:
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context. Start a new pagination sequence without a cursor to change "
                "parameters."
            )
        check_list_entries_cursor(cursor, path)
        data = self._client.get_url(cursor)
    else:
        params: dict[str, Any] = {}
        check_positive_limit(limit)
        if limit is not None:
            params["limit"] = limit
        data = self._client.get(path, params=params or None)

    return entity_list_entries_page(
        data, entity_id=company_id, entity_type=EntityType.ORGANIZATION
    )

get_lists(company_id: CompanyId, *, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[ListSummary]

Get all lists that contain this company.

Source code in affinity/services/companies.py
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
def get_lists(
    self,
    company_id: CompanyId,
    *,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[ListSummary]:
    """Get all lists that contain this company."""
    if cursor is not None:
        if limit is not None:
            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] = {}
        check_positive_limit(limit)
        if limit is not None:
            params["limit"] = limit
        data = self._client.get(
            f"/companies/{company_id}/lists",
            params=params or None,
        )

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

get_many(company_ids: Sequence[CompanyId], *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None) -> PaginatedResponse[Company]

Fetch multiple companies by ID in a single API call.

This is a convenience alias for list(ids=[...]).

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Company IDs to fetch

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

Returns:

Type Description
PaginatedResponse[Company]

Paginated response with companies

Example

companies = client.companies.get_many([CompanyId(1), CompanyId(2)]) for company in companies.data: ... print(company.name)

Source code in affinity/services/companies.py
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
def get_many(
    self,
    company_ids: Sequence[CompanyId],
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
) -> PaginatedResponse[Company]:
    """
    Fetch multiple companies by ID in a single API call.

    This is a convenience alias for ``list(ids=[...])``.

    Args:
        company_ids: Company IDs to fetch
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])

    Returns:
        Paginated response with companies

    Example:
        >>> companies = client.companies.get_many([CompanyId(1), CompanyId(2)])
        >>> for company in companies.data:
        ...     print(company.name)
    """
    return self.list(ids=company_ids, field_ids=field_ids, field_types=field_types)

get_merge_state(merge_id: int) -> CompanyMergeState

One past company merge (see :meth:list_merges).

Source code in affinity/services/companies.py
1241
1242
1243
1244
1245
def get_merge_state(self, merge_id: int) -> CompanyMergeState:
    """One past company merge (see :meth:`list_merges`)."""
    return CompanyMergeState.model_validate(
        self._client.get(f"/company-merges/{int(merge_id)}")
    )

get_merge_status(task_id: str) -> MergeTask

Check the status of a merge operation.

Source code in affinity/services/companies.py
1198
1199
1200
1201
def get_merge_status(self, task_id: str) -> MergeTask:
    """Check the status of a merge operation."""
    data = self._client.get(f"/tasks/company-merges/{task_id}")
    return MergeTask.model_validate(data)

iter(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> Iterator[Company]

Auto-paginate all companies.

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

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def iter(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> Iterator[Company]:
    """
    Auto-paginate all companies.

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

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    return self.all(ids=ids, field_ids=field_ids, field_types=field_types)

iter_merges(*, status: str | None = None, task_id: str | None = None) -> Iterator[CompanyMergeState]

All past company merges matching the filters (every page).

Source code in affinity/services/companies.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
def iter_merges(
    self, *, status: str | None = None, task_id: str | None = None
) -> Iterator[CompanyMergeState]:
    """All past company merges matching the filters (every page)."""

    def fetch_page(next_url: str | None) -> PaginatedResponse[CompanyMergeState]:
        if next_url:
            return self.list_merges(cursor=next_url)
        return self.list_merges(status=status, task_id=task_id)

    return PageIterator(fetch_page)

iter_notes(company_id: CompanyId, *, creator_id: int | None = None, created_after: datetime | None = None, created_before: datetime | None = None, updated_after: datetime | None = None, limit: int | None = None) -> Iterator[NoteV2]

All of this company's notes (every page); see :meth:list_notes.

Source code in affinity/services/companies.py
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
def iter_notes(
    self,
    company_id: CompanyId,
    *,
    creator_id: int | None = None,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    updated_after: datetime | None = None,
    limit: int | None = None,
) -> Iterator[NoteV2]:
    """All of this company's notes (every page); see :meth:`list_notes`."""

    def fetch_page(next_url: str | None) -> PaginatedResponse[NoteV2]:
        if next_url:
            return self.list_notes(company_id, cursor=next_url)
        return self.list_notes(
            company_id,
            creator_id=creator_id,
            created_after=created_after,
            created_before=created_before,
            updated_after=updated_after,
            limit=limit,
        )

    return PageIterator(fetch_page)

iter_relationships(company_id: CompanyId, *, min_score: float | None = None, order: Literal['asc', 'desc'] = 'desc', limit: int | None = None) -> Iterator[Relationship]

All relationships for this company (every page); see :meth:list_relationships.

Source code in affinity/services/companies.py
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
def iter_relationships(
    self,
    company_id: CompanyId,
    *,
    min_score: float | None = None,
    order: Literal["asc", "desc"] = "desc",
    limit: int | None = None,
) -> Iterator[Relationship]:
    """All relationships for this company (every page); see :meth:`list_relationships`."""

    def fetch_page(next_url: str | None) -> PaginatedResponse[Relationship]:
        if next_url:
            return self.list_relationships(company_id, cursor=next_url)
        return self.list_relationships(
            company_id, min_score=min_score, order=order, limit=limit
        )

    return PageIterator(fetch_page)

list(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, limit: int | None = None, cursor: str | None = None, **_unsupported: Any) -> PaginatedResponse[Company]

Get a page of companies.

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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 (e.g., ["enriched", "global"])

None
limit int | None

Maximum number of results (API default: 100)

None
cursor str | None

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

None

Returns:

Type Description
PaginatedResponse[Company]

Paginated response with companies

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def list(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    limit: int | None = None,
    cursor: str | None = None,
    **_unsupported: Any,
) -> PaginatedResponse[Company]:
    """
    Get a page of companies.

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        limit: Maximum number of results (API default: 100)
        cursor: Cursor to resume pagination (opaque; obtained from prior responses)

    Returns:
        Paginated response with companies

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    validate_entity_field_types(field_types, endpoint="company")
    if cursor is not None:
        if any(p is not None for p in (ids, field_ids, field_types, 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:
        check_positive_limit(limit)
        ids = materialize_ids(ids)
        if no_ids(ids):
            return PaginatedResponse[Company]()
        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 limit is not None:
            params["limit"] = limit
        data = self._client.get("/companies", params=params or None)

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

list_merges(*, status: str | None = None, task_id: str | None = None, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[CompanyMergeState]

One page of past company merges, newest first.

status is "in-progress", "success" or "failed"; task_id (or the task URL a merge returned) limits it to one merge task. Needs the "Manage duplicates" permission and the organization admin role (otherwise AuthorizationError).

Source code in affinity/services/companies.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def list_merges(
    self,
    *,
    status: str | None = None,
    task_id: str | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[CompanyMergeState]:
    """One page of past company merges, newest first.

    ``status`` is ``"in-progress"``, ``"success"`` or ``"failed"``; ``task_id`` (or the task
    URL a merge returned) limits it to one merge task. Needs the "Manage duplicates"
    permission and the organization admin role (otherwise ``AuthorizationError``).
    """
    check_cursor_alone(cursor, status, task_id, limit)
    if cursor is not None:
        return page_of(CompanyMergeState, self._client.get_url(cursor))
    params = merge_params(status=status, task_id=task_id, limit=limit)
    return page_of(
        CompanyMergeState, self._client.get("/company-merges", params=params or None)
    )

list_notes(company_id: CompanyId, *, creator_id: int | None = None, created_after: datetime | None = None, created_before: datetime | None = None, updated_after: datetime | None = None, limit: int | None = None, total_count: bool = False, cursor: str | None = None) -> PaginatedResponse[NoteV2]

One page of this company's notes as V2 notes (NoteV2; replies not included).

Filters: creator_id, created_after (inclusive) / created_before (exclusive), updated_after, rounded outward to whole seconds. limit is 1-100. Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).

Source code in affinity/services/companies.py
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
def list_notes(
    self,
    company_id: CompanyId,
    *,
    creator_id: int | None = None,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    updated_after: datetime | None = None,
    limit: int | None = None,
    total_count: bool = False,
    cursor: str | None = None,
) -> PaginatedResponse[NoteV2]:
    """One page of this company's notes as V2 notes (``NoteV2``; replies not included).

    Filters: ``creator_id``, ``created_after`` (inclusive) / ``created_before`` (exclusive),
    ``updated_after``, rounded outward to whole seconds. ``limit`` is 1-100.
    Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).
    """
    check_cursor_alone(
        cursor, creator_id, created_after, created_before, updated_after, limit, total_count
    )
    if cursor is not None:
        return page_of(
            NoteV2, self._client.get_url(cursor, min_api_version=COMPANY_NOTES_MIN_API_VERSION)
        )
    params = note_params(
        creator_id=creator_id,
        created_after=created_after,
        created_before=created_before,
        updated_after=updated_after,
        limit=limit,
        total_count=total_count,
    )
    return page_of(
        NoteV2,
        self._client.get(
            f"/companies/{int(company_id)}/notes",
            params=params or None,
            min_api_version=COMPANY_NOTES_MIN_API_VERSION,
        ),
    )

list_relationships(company_id: CompanyId, *, min_score: float | None = None, order: Literal['asc', 'desc'] = 'desc', limit: int | None = None, total_count: bool = False, cursor: str | None = None) -> PaginatedResponse[Relationship]

One page of the relationships between your team and this company's people.

Strongest first (order="asc" for weakest first). min_score (0.0-1.0) keeps relationships at least that strong; relationships known only from LinkedIn have score 0, so any min_score above 0 drops them. limit is 1-100 (API default 20). Needs Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).

Source code in affinity/services/companies.py
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
def list_relationships(
    self,
    company_id: CompanyId,
    *,
    min_score: float | None = None,
    order: Literal["asc", "desc"] = "desc",
    limit: int | None = None,
    total_count: bool = False,
    cursor: str | None = None,
) -> PaginatedResponse[Relationship]:
    """One page of the relationships between your team and this company's people.

    Strongest first (``order="asc"`` for weakest first). ``min_score`` (0.0-1.0) keeps
    relationships at least that strong; relationships known only from LinkedIn have score 0,
    so any ``min_score`` above 0 drops them. ``limit`` is 1-100 (API default 20). Needs
    Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).
    """
    if cursor is not None:
        if min_score is not None or limit is not None or total_count or order != "desc":
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context."
            )
        return page_of(
            Relationship,
            self._client.get_url(cursor, min_api_version=RELATIONSHIPS_MIN_API_VERSION),
        )
    params = relationship_params(
        min_score=min_score, order=order, limit=limit, total_count=total_count
    )
    return page_of(
        Relationship,
        self._client.get(
            f"/companies/{int(company_id)}/relationships",
            params=params or None,
            min_api_version=RELATIONSHIPS_MIN_API_VERSION,
        ),
    )

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

Merge a duplicate company into a primary company.

Returns a task URL to check merge status.

Source code in affinity/services/companies.py
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
def merge(
    self,
    primary_id: CompanyId,
    duplicate_id: CompanyId,
) -> str:
    """
    Merge a duplicate company into a primary company.

    Returns a task URL to check merge status.
    """
    result = self._client.post(
        "/company-merges",
        json={
            "primaryCompanyId": int(primary_id),
            "duplicateCompanyId": int(duplicate_id),
        },
    )
    return merge_task_url(result, "company")

pages(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, limit: int | None = None, cursor: str | None = None, **_unsupported: Any) -> Iterator[PaginatedResponse[Company]]

Iterate company pages (not items), yielding PaginatedResponse[Company].

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

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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 (e.g., ["enriched", "global"])

None
limit int | None

Maximum results per page

None
cursor str | None

Cursor to resume pagination

None

Yields:

Type Description
PaginatedResponse[Company]

PaginatedResponse[Company] for each page

Source code in affinity/services/companies.py
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
def pages(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    limit: int | None = None,
    cursor: str | None = None,
    **_unsupported: Any,
) -> Iterator[PaginatedResponse[Company]]:
    """
    Iterate company pages (not items), yielding `PaginatedResponse[Company]`.

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

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        limit: Maximum results per page
        cursor: Cursor to resume pagination

    Yields:
        PaginatedResponse[Company] for each page
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    other_params = (ids, field_ids, field_types, 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
    guard = _CursorGuard(cursor)
    page = (
        self.list(cursor=cursor)
        if cursor is not None
        else self.list(ids=ids, field_ids=field_ids, field_types=field_types, limit=limit)
    )
    while True:
        yield page
        # Stop at the last page, or when paging can't progress (see _CursorGuard).
        if guard.last_page(requested_cursor, page):
            return
        requested_cursor = page.next_cursor
        page = self.list(cursor=requested_cursor)

resolve(*, domain: str | None = None, name: str | None = None) -> Company | None

Find a single company by domain 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
domain str | None

Domain to search for (e.g., "acme.com")

None
name str | None

Company name to search for

None

Returns:

Type Description
Company | None

The matching Company, or None if not found

Raises:

Type Description
ValueError

If neither domain nor name is provided

Note

If multiple matches are found, returns the first one. For disambiguation, use search() directly.

Source code in affinity/services/companies.py
 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
1006
1007
1008
def resolve(
    self,
    *,
    domain: str | None = None,
    name: str | None = None,
) -> Company | None:
    """
    Find a single company by domain 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:
        domain: Domain to search for (e.g., "acme.com")
        name: Company name to search for

    Returns:
        The matching Company, or None if not found

    Raises:
        ValueError: If neither domain nor name is provided

    Note:
        If multiple matches are found, returns the first one.
        For disambiguation, use search() directly.
    """
    if not domain and not name:
        raise ValueError("Must provide either domain or name")

    term = domain or name or ""
    result = self.search(term, page_size=10)

    for company in result.data:
        if domain and company.domain and company.domain.lower() == domain.lower():
            return company
        if name and company.name and company.name.lower() == name.lower():
            return company

    return None

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[Company]

Search for companies by name or domain.

Uses V1 API for search functionality not available in V2.

Parameters:

Name Type Description Default
term str

Search term (name or domain)

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[Company]

Dict with 'organizations' and 'next_page_token'

Source code in affinity/services/companies.py
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
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[Company]:
    """
    Search for companies by name or domain.

    Uses V1 API for search functionality not available in V2.

    Args:
        term: Search term (name or domain)
        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:
        Dict with 'organizations' and 'next_page_token'
    """
    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("/organizations", params=params, v1=True)
    items = [Company.model_validate(o) for o in data.get("organizations", [])]
    return PaginatedResponse[Company](
        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[Company]

Iterate all V1 company-search results with automatic pagination.

Parameters:

Name Type Description Default
term str

Search term (name or domain)

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
Company

Company objects matching the search term

Source code in affinity/services/companies.py
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
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[Company]:
    """
    Iterate all V1 company-search results with automatic pagination.

    Args:
        term: Search term (name or domain)
        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:
        Company 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[Company]]

Iterate V1 company-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 domain)

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[Company]

PaginatedResponse[Company] for each page

Source code in affinity/services/companies.py
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
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[Company]]:
    """
    Iterate V1 company-search result pages.

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

    Args:
        term: Search term (name or domain)
        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[Company] 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(company_id: CompanyId, data: CompanyUpdate) -> Company

Update an existing company.

Note: Cannot update name/domain of global companies.

Source code in affinity/services/companies.py
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
def update(
    self,
    company_id: CompanyId,
    data: CompanyUpdate,
) -> Company:
    """
    Update an existing company.

    Note: Cannot update name/domain of global companies.
    """
    payload = data.model_dump(
        by_alias=True,
        mode="json",
        exclude_unset=True,
        exclude_none=True,
    )

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

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

    return Company.model_validate(result)

Bases: AsyncCompanySemanticSearchMixin, AsyncCompanyDiscoveryMixin, AsyncSingleFieldMixin, AsyncSearchMixin[Company]

Source code in affinity/services/companies.py
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
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
class AsyncCompanyService(
    AsyncCompanySemanticSearchMixin,
    AsyncCompanyDiscoveryMixin,
    AsyncSingleFieldMixin,
    AsyncSearchMixin[Company],
):
    _entity_path = "/companies"

    _search_model = Company

    def _search_path(self) -> str:
        return "/companies/search"

    async def _search_fields(self) -> builtins.list[FieldMetadata]:
        return await self.get_fields(includes=SEARCH_INCLUDES)

    """
    Async version of CompanyService.

    Mirrors sync behavior for V2 reads, V1 writes, and V1 search helpers.
    """

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

    async def list(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        limit: int | None = None,
        cursor: str | None = None,
        **_unsupported: Any,
    ) -> PaginatedResponse[Company]:
        """
        Get a page of companies.

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            limit: Maximum number of results (API default: 100)
            cursor: Cursor to resume pagination (opaque; obtained from prior responses)

        Returns:
            Paginated response with companies

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        validate_entity_field_types(field_types, endpoint="company")
        if cursor is not None:
            if any(p is not None for p in (ids, field_ids, field_types, 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:
            check_positive_limit(limit)
            ids = materialize_ids(ids)
            if no_ids(ids):
                return PaginatedResponse[Company]()
            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 limit is not None:
                params["limit"] = limit
            data = await self._client.get("/companies", params=params or None)

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

    async def get_first(
        self,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> Company | None:
        """
        Get the first company from the list endpoint, or None if no results.

        See CompanyService.get_first() for details.

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        page = await self.list(
            field_ids=field_ids,
            field_types=field_types,
            limit=1,
        )
        return page.data[0] if page.data else None

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

        Unlike get_many() which uses the API's batch endpoint, this method
        makes individual get() calls with bounded concurrency. Use this when
        you need parameters not supported by the batch endpoint (e.g.,
        with_interaction_dates=True).

        Calls: one per id. With with_interaction_dates and field_ids/field_types, the fields
        come from one call per 100 ids and the dates from one V1 call per id (about N + N/100
        calls, not 2N). For just the last and next event dates of many companies, the
        relationship-intelligence fields are cheaper: ``iter(ids=<up to 100 ids>,
        field_types=[FieldType.RELATIONSHIP_INTELLIGENCE])`` reads them in one call per 100
        ids, without the V1 calls (the other interaction dates and interaction persons have
        no confirmed V2 counterpart).

        Args:
            company_ids: Company IDs to fetch
            field_ids: Specific field IDs to include
            field_types: Field types to include
            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 company_id -> Company for successfully fetched companies.

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

        unique_ids = list(dict.fromkeys(company_ids))
        if with_interaction_dates and (field_ids is not None or field_types is not None):
            # One V2 call per 100 ids for the fields, one V1 call per id for the dates
            v1_params: dict[str, Any] = {"with_interaction_dates": True}
            if with_interaction_persons:
                v1_params["with_interaction_persons"] = True
            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]
            return await batch_get_with_dates(
                self._client,
                unique_ids,
                v1_path="/organizations",
                v2_path="/companies",
                kind="Company",
                v1_params=v1_params,
                v2_params=v2_params,
                max_concurrent=max_concurrent,
                on_error=on_error,
                get_one=lambda record_id: self.get(
                    record_id,
                    field_ids=field_ids,
                    field_types=field_types,
                    with_interaction_dates=True,
                    with_interaction_persons=with_interaction_persons,
                ),
                build=Company.model_validate,
            )
        results: dict[CompanyId, Company] = {}

        async def fetch_one(cid: CompanyId) -> tuple[CompanyId, Company | None]:
            try:
                company = await self.get(
                    cid,
                    field_ids=field_ids,
                    field_types=field_types,
                    with_interaction_dates=with_interaction_dates,
                    with_interaction_persons=with_interaction_persons,
                )
                return (cid, company)
            except AffinityError:
                if on_error == "raise":
                    raise
                return (cid, None)

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

        return results

    def pages(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        limit: int | None = None,
        cursor: str | None = None,
        **_unsupported: Any,
    ) -> AsyncIterator[PaginatedResponse[Company]]:
        """
        Iterate company pages (not items), yielding `PaginatedResponse[Company]`.

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

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            limit: Maximum results per page
            cursor: Cursor to resume pagination

        Returns:
            AsyncIterator of PaginatedResponse[Company]

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        return self._pages_iter(
            ids=ids,
            field_ids=field_ids,
            field_types=field_types,
            limit=limit,
            cursor=cursor,
        )

    async def _pages_iter(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> AsyncIterator[PaginatedResponse[Company]]:
        other_params = (ids, field_ids, field_types, 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
        guard = _CursorGuard(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,
                limit=limit,
            )
        while True:
            yield page
            # Stop at the last page, or when paging can't progress (see _CursorGuard).
            if guard.last_page(requested_cursor, page):
                return
            requested_cursor = page.next_cursor
            page = await self.list(cursor=requested_cursor)

    def all(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> AsyncIterator[Company]:
        """
        Iterate through all companies with automatic pagination.

        Args:
            ids: Specific company IDs to fetch (batch lookup)
            field_ids: Specific field IDs to include
            field_types: Field types to include

        Yields:
            Company objects

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")

        async def fetch_page(next_url: str | None) -> PaginatedResponse[Company]:
            if next_url:
                data = await self._client.get_url(next_url)
                return PaginatedResponse[Company](
                    data=[Company.model_validate(c) for c 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)

        return AsyncPageIterator(fetch_page)

    def iter(
        self,
        *,
        ids: Sequence[CompanyId] | None = None,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        **_unsupported: Any,
    ) -> AsyncIterator[Company]:
        """
        Auto-paginate all companies.

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

        Note:
            The V2 /companies endpoint silently ignores any ``filter=`` parameter —
            passing one would return unfiltered results without warning. This method
            therefore rejects ``filter=`` with a ``ValueError``. To search companies
            by name or domain use ``client.companies.search_pages(term)``. To filter
            by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
        """
        if "filter" in _unsupported:
            raise ValueError(
                "V2 /companies does not support server-side filter. "
                "To search by name/domain use client.companies.search_pages(term). "
                "To filter by list-specific fields use "
                "client.lists.entries(list_id).list(filter=...)."
            )
        if _unsupported:
            raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
        return self.all(ids=ids, field_ids=field_ids, field_types=field_types)

    async def get(
        self,
        company_id: CompanyId,
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
        retries: int = 0,
        with_interaction_dates: bool = False,
        with_interaction_persons: bool = False,
    ) -> Company:
        """
        Get a single company by ID.

        Args:
            company_id: The company ID
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])
            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:
            Company object with requested field data. When with_interaction_dates=True,
            the Company will have interaction_dates and interactions populated.

        Raises:
            NotFoundError: If company does not exist after all retries.

        Note:
            When combining with_interaction_dates with field_ids/field_types,
            two API calls are made internally and the results are merged.
        """
        last_error: NotFoundError | None = None
        attempts = retries + 1  # retries=0 means 1 attempt
        has_field_filters = field_ids is not None or field_types is not None

        for attempt in range(attempts):
            try:
                if with_interaction_dates:
                    # Fetch interaction data
                    v1_params: dict[str, Any] = {"with_interaction_dates": True}
                    if with_interaction_persons:
                        v1_params["with_interaction_persons"] = True
                    interaction_data = await self._client.get(
                        f"/organizations/{company_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"/companies/{company_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 Company.model_validate(filtered_data)

                    # No field filtering, return interaction data directly
                    return Company.model_validate(interaction_data)

                # 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"/companies/{company_id}", params=params or None)
                return Company.model_validate(data)
            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 (with_interaction_dates=True)
        if last_error is not None and not with_interaction_dates:
            try:
                v1_data = await self._client.get(f"/organizations/{company_id}", v1=True)
                return Company.model_validate(v1_data)
            except NotFoundError:
                pass  # V1 also failed, raise original V2 error

        raise last_error  # type: ignore[misc]

    async def get_many(
        self,
        company_ids: Sequence[CompanyId],
        *,
        field_ids: Sequence[AnyFieldId] | None = None,
        field_types: Sequence[FieldType] | None = None,
    ) -> PaginatedResponse[Company]:
        """
        Fetch multiple companies by ID in a single API call.

        This is a convenience alias for ``list(ids=[...])``.

        Args:
            company_ids: Company IDs to fetch
            field_ids: Specific field IDs to include in response
            field_types: Field types to include (e.g., ["enriched", "global"])

        Returns:
            Paginated response with companies

        Example:
            >>> companies = await client.companies.get_many([CompanyId(1), CompanyId(2)])
            >>> for company in companies.data:
            ...     print(company.name)
        """
        return await self.list(ids=company_ids, field_ids=field_ids, field_types=field_types)

    async def get_list_entries(
        self,
        company_id: CompanyId,
        *,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[ListEntry]:
        """
        Get all list entries for a company across all lists.

        Returns comprehensive field data for each list entry. Each entry's ``entity_id`` is
        ``company_id`` and its ``entity_type`` is ``EntityType.ORGANIZATION``; ``entity`` is
        ``None`` (this endpoint doesn't embed the company). A ``cursor`` must come from this
        company's entries.
        """
        path = f"/companies/{company_id}/list-entries"
        if cursor is not None:
            if limit is not None:
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context. Start a new pagination sequence without a cursor to change "
                    "parameters."
                )
            check_list_entries_cursor(cursor, path)
            data = await self._client.get_url(cursor)
        else:
            params: dict[str, Any] = {}
            check_positive_limit(limit)
            if limit is not None:
                params["limit"] = limit
            data = await self._client.get(path, params=params or None)

        return entity_list_entries_page(
            data, entity_id=company_id, entity_type=EntityType.ORGANIZATION
        )

    async def get_lists(
        self,
        company_id: CompanyId,
        *,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[ListSummary]:
        """Get all lists that contain this company."""
        if cursor is not None:
            if limit is not None:
                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] = {}
            check_positive_limit(limit)
            if limit is not None:
                params["limit"] = limit
            data = await self._client.get(
                f"/companies/{company_id}/lists",
                params=params or None,
            )

        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,
        *,
        filter: str | None = None,
        includes: Sequence[str] | None = None,
    ) -> builtins.list[FieldMetadata]:
        """
        Get metadata about company fields.

        Cached for performance.

        Args:
            filter: Filter on the field name: ``name="Location"`` (exact) or ``name=~Loc``
                (substring); both case-sensitive. Combine clauses with ``|``. Only ``name``
                is filterable; anything else is rejected with 400.
            includes: Extra properties per field: ``"filterability"``, ``"sortability"``
                (read them via ``is_filterable`` / ``is_sortable``).
        """
        params, cache_key = build_fields_query(
            "company_fields:_all_",
            filter=filter,
            includes=includes,
        )

        data = await self._client.get_all_pages(
            "/companies/fields",
            params=params or None,
            cache_key=cache_key,
            cache_ttl=300,
        )

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

    async def get_field_dropdown_options(
        self, field_id: AnyFieldId, *, with_status_types: bool = False
    ) -> builtins.list[DropdownOption]:
        """All options of a company dropdown, ranked-dropdown or status field (every page).

        Options with ``type``, ``rank``, ``color`` and (status fields) ``status_category`` /
        ``win_rate``. Options of global company fields can only be read; list-specific fields'
        options are managed through ``client.lists``. ``with_status_types=True``: see
        ``lists.get_field_dropdown_options``.
        """
        data = await self._client.get_all_pages(
            options_path(field_id, list_id=None, entity="companies"),
            params={"limit": 100},
            min_api_version=DROPDOWN_OPTION_WRITES_MIN_API_VERSION if with_status_types else None,
        )
        return parse_options(data)

    async def get_field_values(
        self,
        company_id: CompanyId,
        *,
        ids: Sequence[AnyFieldId | str] | None = None,
    ) -> FieldValues:
        """
        Field values of one company, keyed by field id (``GET /v2/companies/{id}/fields``).

        Args:
            company_id: The company.
            ids: Only these fields (server-side filter); all fields when omitted.
        """
        params = {"ids": [str(fid) for fid in ids]} if ids else None
        data = await self._client.get_all_pages(f"/companies/{company_id}/fields", params=params)
        return FieldValues.model_validate(data.get("data", []))

    async def batch_update_fields(
        self,
        company_id: CompanyId,
        updates: Mapping[AnyFieldId | str, Any],
        *,
        value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None,
    ) -> BatchOperationResponse:
        """
        Update several field values of one company in one request.

        Affinity applies the whole batch or none of it; each update replaces the field's value
        and ``None`` (with a type) clears it. Global, enriched and Source of Introduction
        fields are all writable. At most 100 updates, and 100 values per multi-value field.

        Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an
        unpinned client sends that version for this call; a client pinned to an older version
        raises ``ApiVersionTooOldError`` without sending anything.

        Args:
            company_id: The company.
            updates: Field id -> new value. Values are auto-typed (str→text, int/float→number,
                datetime/date→datetime) unless the field has an entry in ``value_types``.
            value_types: Field id -> value type (e.g. ``"dropdown-multi"``); needed for lists
                (multi-value fields) and ``None`` (clear).
        """
        items = _batch_update_items(updates, value_types)
        result = await self._client.patch(
            f"/companies/{company_id}/fields",
            json={"operation": "update-fields", "updates": items},
            min_api_version=FIELD_WRITES_MIN_API_VERSION,
        )
        return BatchOperationResponse.model_validate(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[Company]:
        """
        Search for companies by name or domain.

        Uses V1 API for search functionality not available in V2.
        """
        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("/organizations", params=params, v1=True)
        items = [Company.model_validate(o) for o in data.get("organizations", [])]
        return PaginatedResponse[Company](
            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[Company]]:
        """
        Iterate V1 company-search result pages.

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

        Args:
            term: Search term (name or domain)
            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[Company] 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[Company]:
        """
        Iterate all V1 company-search results with automatic pagination.

        Args:
            term: Search term (name or domain)
            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:
            Company 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 company in page.data:
                yield company

    async def resolve(
        self,
        *,
        domain: str | None = None,
        name: str | None = None,
    ) -> Company | None:
        """
        Find a single company by domain 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 domain and not name:
            raise ValueError("Must provide either domain or name")

        term = domain or name or ""
        result = await self.search(term, page_size=10)

        for company in result.data:
            if domain and company.domain and company.domain.lower() == domain.lower():
                return company
            if name and company.name and company.name.lower() == name.lower():
                return company

        return None

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

        V1-only exception: V2 does not expose company -> people associations.
        Uses GET `/organizations/{id}` and returns `person_ids` if present.
        """
        data = await self._client.get(f"/organizations/{company_id}", v1=True)
        organization = data.get("organization") if isinstance(data, dict) else None
        source = organization if isinstance(organization, dict) else data
        person_ids = None
        if isinstance(source, dict):
            person_ids = source.get("person_ids") or source.get("personIds")

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

        ids = [PersonId(int(value)) for value in person_ids if value is not None]
        if max_results is not None and max_results >= 0:
            return ids[:max_results]
        return ids

    async def get_associated_person_ids_batch(
        self,
        company_ids: Sequence[CompanyId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[CompanyId, builtins.list[PersonId]]:
        """
        Get person associations for multiple companies.

        Makes one V1 API call per company.

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

        Returns:
            Dict mapping company_id -> list of person_ids

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

    async def get_associated_people(
        self,
        company_id: CompanyId,
        *,
        max_results: int | None = None,
    ) -> builtins.list[Person]:
        """
        Get Person objects associated with a company.

        Uses V2 batch lookup for efficiency (1 API call per 100 persons
        instead of 1 per person).
        """
        person_ids = await self.get_associated_person_ids(company_id, max_results=max_results)
        if not person_ids:
            return []

        # Use V2 batch lookup: GET /persons?ids=1&ids=2&ids=3
        # Note: person_ids is already truncated by get_associated_person_ids if max_results set
        params: dict[str, Any] = {"ids": [int(pid) for pid in person_ids]}

        people: builtins.list[Person] = []
        data = await self._client.get("/persons", params=params)  # V2 batch
        for item in data.get("data", []):
            people.append(Person.model_validate(item))

        # Handle pagination if needed (>100 persons)
        # Note: max_results check is defensive - person_ids was already truncated above
        pagination = data.get("pagination") or {}
        next_url = pagination.get("nextUrl")
        while next_url and (max_results is None or len(people) < max_results):
            data = await self._client.get_url(next_url)
            for item in data.get("data", []):
                people.append(Person.model_validate(item))
            next_url = (data.get("pagination") or {}).get("nextUrl")

        if max_results:
            return people[:max_results]
        return people

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

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

        Args:
            company_id: The company ID
            max_results: Maximum number of opportunity IDs to return

        Returns:
            List of OpportunityId values associated with this company
        """
        data = await self._client.get(f"/organizations/{company_id}", v1=True)
        # Defensive: handle potential {"organization": {...}} wrapper
        organization = data.get("organization") if isinstance(data, dict) else None
        source = organization if isinstance(organization, 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,
        company_ids: Sequence[CompanyId],
        *,
        on_error: Literal["raise", "skip"] = "raise",
    ) -> dict[CompanyId, builtins.list[OpportunityId]]:
        """
        Get opportunity associations for multiple companies.

        Makes one V1 API call per company.

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

        Returns:
            Dict mapping company_id -> list of opportunity_ids

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

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

    _DEDUP_PAGE_CAP = 3  # 3 pages x 500 = 1500 fuzzy results scanned per search term

    async def create(self, data: CompanyCreate, *, if_not_exists: bool = True) -> Company:
        """
        Create a new company.

        Args:
            data: Company creation data
            if_not_exists: If True (default), check for an existing company with
                the same name (case-insensitive exact match) OR the same domain
                (matched against the company's primary domain AND all entries
                in its `domains` list). Globals in Affinity's shared directory
                are treated as duplicates — per the API docs, POST /organizations
                always creates a tenant-scoped copy, so creating against an
                existing global would produce a genuine duplicate. Raises
                DuplicateEntityError carrying the existing company's ID and
                `existing_is_global` flag, so callers can use the global ID
                directly (e.g., via List Entries) instead of POSTing a copy.
                Uses V1 search_pages() with page_size=500, capped at 3 pages.
                Set to False to skip the check and create unconditionally.

        Returns:
            Created company

        Raises:
            DuplicateEntityError: When if_not_exists=True and an exact-name or
                exact-domain match already exists (tenant-scoped OR global).

        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 Company 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
        """
        if if_not_exists:
            existing = await self._find_exact_duplicate(name=data.name, domain=data.domain)
            if existing is not None:
                if existing.is_global:
                    message = (
                        f"A global Affinity directory record matches name={data.name!r} "
                        f"or domain={data.domain!r} (id={existing.id}). Global records "
                        f"are shared across tenants — use this ID directly (e.g., via "
                        f"List Entries) instead of creating a tenant-scoped duplicate."
                    )
                else:
                    message = (
                        f"Company with name={data.name!r} or domain={data.domain!r} "
                        f"already exists (id={existing.id})"
                    )
                raise DuplicateEntityError(
                    message,
                    entity_type="company",
                    existing_id=int(existing.id),
                    existing_name=existing.name,
                    existing_domain=existing.domain,
                    existing_is_global=bool(existing.is_global),
                )

        payload = data.model_dump(by_alias=True, mode="json", exclude_none=True)
        if not data.person_ids:
            payload.pop("person_ids", None)
        result = await self._client.post("/organizations", json=payload, v1=True)

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

        return Company.model_validate(result)

    @staticmethod
    def _company_matches(company: Company, name_lower: str, domain_lower: str | None) -> bool:
        """True iff company's name or any domain matches exactly (case-insensitive)."""
        if company.name and company.name.lower() == name_lower:
            return True
        if domain_lower:
            if company.domain and company.domain.lower() == domain_lower:
                return True
            for d in company.domains or []:
                if d and d.lower() == domain_lower:
                    return True
        return False

    async def _find_exact_duplicate(self, *, name: str, domain: str | None) -> Company | None:
        """Search V1 for an exact-name or exact-domain match. Returns None if no match.

        Domain-first search order: domains are globally more unique than names,
        so if a domain is supplied, we search by domain first. Falls back to a
        name search only when the domain search came up empty and the name
        differs from the domain string.

        Iterates at most `_DEDUP_PAGE_CAP` pages per term (1500 fuzzy results).
        """
        name_lower = name.strip().lower()
        domain_lower = domain.strip().lower() if domain else None

        async def _scan(term: str) -> Company | None:
            page_num = 0
            async for page in self.search_pages(term, page_size=500):
                for company in page.data:
                    if self._company_matches(company, name_lower, domain_lower):
                        return company
                if page_num + 1 >= self._DEDUP_PAGE_CAP:
                    break
                if not page.next_page_token:
                    break
                page_num += 1
            return None

        if domain_lower:
            # domain is guaranteed non-None when domain_lower is set
            hit = await _scan(domain or "")
            if hit is not None:
                return hit
            if name_lower and name_lower != domain_lower:
                return await _scan(name)
            return None

        return await _scan(name)

    async def update(self, company_id: CompanyId, data: CompanyUpdate) -> Company:
        """
        Update an existing company.

        Uses V1 API.
        """
        payload = data.model_dump(
            by_alias=True,
            mode="json",
            exclude_unset=True,
            exclude_none=True,
        )
        result = await self._client.put(
            f"/organizations/{company_id}",
            json=payload,
            v1=True,
        )

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

        return Company.model_validate(result)

    async def delete(self, company_id: CompanyId) -> bool:
        """
        Delete a company.

        Uses V1 API.
        """
        result = await self._client.delete(f"/organizations/{company_id}", v1=True)
        invalidate_all_list_sizes(self._client)

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

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

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

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

        Returns a task URL to check merge status.
        """
        result = await self._client.post(
            "/company-merges",
            json={
                "primaryCompanyId": int(primary_id),
                "duplicateCompanyId": int(duplicate_id),
            },
        )
        return merge_task_url(result, "company")

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

    # =========================================================================
    # Merge history and relationships (V2)
    # =========================================================================

    async def list_merges(
        self,
        *,
        status: str | None = None,
        task_id: str | None = None,
        limit: int | None = None,
        cursor: str | None = None,
    ) -> PaginatedResponse[CompanyMergeState]:
        """One page of past company merges, newest first.

        ``status`` is ``"in-progress"``, ``"success"`` or ``"failed"``; ``task_id`` (or the task
        URL a merge returned) limits it to one merge task. Needs the "Manage duplicates"
        permission and the organization admin role (otherwise ``AuthorizationError``).
        """
        check_cursor_alone(cursor, status, task_id, limit)
        if cursor is not None:
            return page_of(CompanyMergeState, await self._client.get_url(cursor))
        params = merge_params(status=status, task_id=task_id, limit=limit)
        return page_of(
            CompanyMergeState, await self._client.get("/company-merges", params=params or None)
        )

    def iter_merges(
        self, *, status: str | None = None, task_id: str | None = None
    ) -> AsyncIterator[CompanyMergeState]:
        """All past company merges matching the filters (every page)."""

        async def fetch_page(next_url: str | None) -> PaginatedResponse[CompanyMergeState]:
            if next_url:
                return await self.list_merges(cursor=next_url)
            return await self.list_merges(status=status, task_id=task_id)

        return AsyncPageIterator(fetch_page)

    async def get_merge_state(self, merge_id: int) -> CompanyMergeState:
        """One past company merge (see :meth:`list_merges`)."""
        return CompanyMergeState.model_validate(
            await self._client.get(f"/company-merges/{int(merge_id)}")
        )

    async def list_relationships(
        self,
        company_id: CompanyId,
        *,
        min_score: float | None = None,
        order: Literal["asc", "desc"] = "desc",
        limit: int | None = None,
        total_count: bool = False,
        cursor: str | None = None,
    ) -> PaginatedResponse[Relationship]:
        """One page of the relationships between your team and this company's people.

        Strongest first (``order="asc"`` for weakest first). ``min_score`` (0.0-1.0) keeps
        relationships at least that strong; relationships known only from LinkedIn have score 0,
        so any ``min_score`` above 0 drops them. ``limit`` is 1-100 (API default 20). Needs
        Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).
        """
        if cursor is not None:
            if min_score is not None or limit is not None or total_count or order != "desc":
                raise ValueError(
                    "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                    "context."
                )
            return page_of(
                Relationship,
                await self._client.get_url(cursor, min_api_version=RELATIONSHIPS_MIN_API_VERSION),
            )
        params = relationship_params(
            min_score=min_score, order=order, limit=limit, total_count=total_count
        )
        return page_of(
            Relationship,
            await self._client.get(
                f"/companies/{int(company_id)}/relationships",
                params=params or None,
                min_api_version=RELATIONSHIPS_MIN_API_VERSION,
            ),
        )

    def iter_relationships(
        self,
        company_id: CompanyId,
        *,
        min_score: float | None = None,
        order: Literal["asc", "desc"] = "desc",
        limit: int | None = None,
    ) -> AsyncIterator[Relationship]:
        """All relationships for this company (every page); see :meth:`list_relationships`."""

        async def fetch_page(next_url: str | None) -> PaginatedResponse[Relationship]:
            if next_url:
                return await self.list_relationships(company_id, cursor=next_url)
            return await self.list_relationships(
                company_id, min_score=min_score, order=order, limit=limit
            )

        return AsyncPageIterator(fetch_page)

    # =========================================================================
    # Notes (V2)
    # =========================================================================

    async def list_notes(
        self,
        company_id: CompanyId,
        *,
        creator_id: int | None = None,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        updated_after: datetime | None = None,
        limit: int | None = None,
        total_count: bool = False,
        cursor: str | None = None,
    ) -> PaginatedResponse[NoteV2]:
        """One page of this company's notes as V2 notes (``NoteV2``; replies not included).

        Filters: ``creator_id``, ``created_after`` (inclusive) / ``created_before`` (exclusive),
        ``updated_after``, rounded outward to whole seconds. ``limit`` is 1-100.
        Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).
        """
        check_cursor_alone(
            cursor, creator_id, created_after, created_before, updated_after, limit, total_count
        )
        if cursor is not None:
            return page_of(
                NoteV2,
                await self._client.get_url(cursor, min_api_version=COMPANY_NOTES_MIN_API_VERSION),
            )
        params = note_params(
            creator_id=creator_id,
            created_after=created_after,
            created_before=created_before,
            updated_after=updated_after,
            limit=limit,
            total_count=total_count,
        )
        return page_of(
            NoteV2,
            await self._client.get(
                f"/companies/{int(company_id)}/notes",
                params=params or None,
                min_api_version=COMPANY_NOTES_MIN_API_VERSION,
            ),
        )

    def iter_notes(
        self,
        company_id: CompanyId,
        *,
        creator_id: int | None = None,
        created_after: datetime | None = None,
        created_before: datetime | None = None,
        updated_after: datetime | None = None,
        limit: int | None = None,
    ) -> AsyncIterator[NoteV2]:
        """All of this company's notes (every page); see :meth:`list_notes`."""

        async def fetch_page(next_url: str | None) -> PaginatedResponse[NoteV2]:
            if next_url:
                return await self.list_notes(company_id, cursor=next_url)
            return await self.list_notes(
                company_id,
                creator_id=creator_id,
                created_after=created_after,
                created_before=created_before,
                updated_after=updated_after,
                limit=limit,
            )

        return AsyncPageIterator(fetch_page)

all(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> AsyncIterator[Company]

Iterate through all companies with automatic pagination.

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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

Yields:

Type Description
AsyncIterator[Company]

Company objects

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def all(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> AsyncIterator[Company]:
    """
    Iterate through all companies with automatic pagination.

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include
        field_types: Field types to include

    Yields:
        Company objects

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")

    async def fetch_page(next_url: str | None) -> PaginatedResponse[Company]:
        if next_url:
            data = await self._client.get_url(next_url)
            return PaginatedResponse[Company](
                data=[Company.model_validate(c) for c 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)

    return AsyncPageIterator(fetch_page)

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

Fetch multiple companies with controlled concurrency.

Unlike get_many() which uses the API's batch endpoint, this method makes individual get() calls with bounded concurrency. Use this when you need parameters not supported by the batch endpoint (e.g., with_interaction_dates=True).

Calls: one per id. With with_interaction_dates and field_ids/field_types, the fields come from one call per 100 ids and the dates from one V1 call per id (about N + N/100 calls, not 2N). For just the last and next event dates of many companies, the relationship-intelligence fields are cheaper: iter(ids=<up to 100 ids>, field_types=[FieldType.RELATIONSHIP_INTELLIGENCE]) reads them in one call per 100 ids, without the V1 calls (the other interaction dates and interaction persons have no confirmed V2 counterpart).

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Company 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
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[CompanyId, Company]

Dict mapping company_id -> Company for successfully fetched companies.

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/companies.py
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
async def batch_get(
    self,
    company_ids: Sequence[CompanyId],
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
    max_concurrent: int = 10,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[CompanyId, Company]:
    """
    Fetch multiple companies with controlled concurrency.

    Unlike get_many() which uses the API's batch endpoint, this method
    makes individual get() calls with bounded concurrency. Use this when
    you need parameters not supported by the batch endpoint (e.g.,
    with_interaction_dates=True).

    Calls: one per id. With with_interaction_dates and field_ids/field_types, the fields
    come from one call per 100 ids and the dates from one V1 call per id (about N + N/100
    calls, not 2N). For just the last and next event dates of many companies, the
    relationship-intelligence fields are cheaper: ``iter(ids=<up to 100 ids>,
    field_types=[FieldType.RELATIONSHIP_INTELLIGENCE])`` reads them in one call per 100
    ids, without the V1 calls (the other interaction dates and interaction persons have
    no confirmed V2 counterpart).

    Args:
        company_ids: Company IDs to fetch
        field_ids: Specific field IDs to include
        field_types: Field types to include
        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 company_id -> Company for successfully fetched companies.

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

    unique_ids = list(dict.fromkeys(company_ids))
    if with_interaction_dates and (field_ids is not None or field_types is not None):
        # One V2 call per 100 ids for the fields, one V1 call per id for the dates
        v1_params: dict[str, Any] = {"with_interaction_dates": True}
        if with_interaction_persons:
            v1_params["with_interaction_persons"] = True
        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]
        return await batch_get_with_dates(
            self._client,
            unique_ids,
            v1_path="/organizations",
            v2_path="/companies",
            kind="Company",
            v1_params=v1_params,
            v2_params=v2_params,
            max_concurrent=max_concurrent,
            on_error=on_error,
            get_one=lambda record_id: self.get(
                record_id,
                field_ids=field_ids,
                field_types=field_types,
                with_interaction_dates=True,
                with_interaction_persons=with_interaction_persons,
            ),
            build=Company.model_validate,
        )
    results: dict[CompanyId, Company] = {}

    async def fetch_one(cid: CompanyId) -> tuple[CompanyId, Company | None]:
        try:
            company = await self.get(
                cid,
                field_ids=field_ids,
                field_types=field_types,
                with_interaction_dates=with_interaction_dates,
                with_interaction_persons=with_interaction_persons,
            )
            return (cid, company)
        except AffinityError:
            if on_error == "raise":
                raise
            return (cid, None)

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

    return results

batch_update_fields(company_id: CompanyId, updates: Mapping[AnyFieldId | str, Any], *, value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None) -> BatchOperationResponse async

Update several field values of one company in one request.

Affinity applies the whole batch or none of it; each update replaces the field's value and None (with a type) clears it. Global, enriched and Source of Introduction fields are all writable. At most 100 updates, and 100 values per multi-value field.

Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an unpinned client sends that version for this call; a client pinned to an older version raises ApiVersionTooOldError without sending anything.

Parameters:

Name Type Description Default
company_id CompanyId

The company.

required
updates Mapping[AnyFieldId | str, Any]

Field id -> new value. Values are auto-typed (str→text, int/float→number, datetime/date→datetime) unless the field has an entry in value_types.

required
value_types Mapping[AnyFieldId | str, FieldValueType | str] | None

Field id -> value type (e.g. "dropdown-multi"); needed for lists (multi-value fields) and None (clear).

None
Source code in affinity/services/companies.py
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
async def batch_update_fields(
    self,
    company_id: CompanyId,
    updates: Mapping[AnyFieldId | str, Any],
    *,
    value_types: Mapping[AnyFieldId | str, FieldValueType | str] | None = None,
) -> BatchOperationResponse:
    """
    Update several field values of one company in one request.

    Affinity applies the whole batch or none of it; each update replaces the field's value
    and ``None`` (with a type) clears it. Global, enriched and Source of Introduction
    fields are all writable. At most 100 updates, and 100 values per multi-value field.

    Needs Affinity API version {FIELD_WRITES_MIN_API_VERSION} (out of beta there): an
    unpinned client sends that version for this call; a client pinned to an older version
    raises ``ApiVersionTooOldError`` without sending anything.

    Args:
        company_id: The company.
        updates: Field id -> new value. Values are auto-typed (str→text, int/float→number,
            datetime/date→datetime) unless the field has an entry in ``value_types``.
        value_types: Field id -> value type (e.g. ``"dropdown-multi"``); needed for lists
            (multi-value fields) and ``None`` (clear).
    """
    items = _batch_update_items(updates, value_types)
    result = await self._client.patch(
        f"/companies/{company_id}/fields",
        json={"operation": "update-fields", "updates": items},
        min_api_version=FIELD_WRITES_MIN_API_VERSION,
    )
    return BatchOperationResponse.model_validate(result)

create(data: CompanyCreate, *, if_not_exists: bool = True) -> Company async

Create a new company.

Parameters:

Name Type Description Default
data CompanyCreate

Company creation data

required
if_not_exists bool

If True (default), check for an existing company with the same name (case-insensitive exact match) OR the same domain (matched against the company's primary domain AND all entries in its domains list). Globals in Affinity's shared directory are treated as duplicates — per the API docs, POST /organizations always creates a tenant-scoped copy, so creating against an existing global would produce a genuine duplicate. Raises DuplicateEntityError carrying the existing company's ID and existing_is_global flag, so callers can use the global ID directly (e.g., via List Entries) instead of POSTing a copy. Uses V1 search_pages() with page_size=500, capped at 3 pages. Set to False to skip the check and create unconditionally.

True

Returns:

Type Description
Company

Created company

Raises:

Type Description
DuplicateEntityError

When if_not_exists=True and an exact-name or exact-domain match already exists (tenant-scoped OR global).

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 Company 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

Source code in affinity/services/companies.py
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
async def create(self, data: CompanyCreate, *, if_not_exists: bool = True) -> Company:
    """
    Create a new company.

    Args:
        data: Company creation data
        if_not_exists: If True (default), check for an existing company with
            the same name (case-insensitive exact match) OR the same domain
            (matched against the company's primary domain AND all entries
            in its `domains` list). Globals in Affinity's shared directory
            are treated as duplicates — per the API docs, POST /organizations
            always creates a tenant-scoped copy, so creating against an
            existing global would produce a genuine duplicate. Raises
            DuplicateEntityError carrying the existing company's ID and
            `existing_is_global` flag, so callers can use the global ID
            directly (e.g., via List Entries) instead of POSTing a copy.
            Uses V1 search_pages() with page_size=500, capped at 3 pages.
            Set to False to skip the check and create unconditionally.

    Returns:
        Created company

    Raises:
        DuplicateEntityError: When if_not_exists=True and an exact-name or
            exact-domain match already exists (tenant-scoped OR global).

    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 Company 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
    """
    if if_not_exists:
        existing = await self._find_exact_duplicate(name=data.name, domain=data.domain)
        if existing is not None:
            if existing.is_global:
                message = (
                    f"A global Affinity directory record matches name={data.name!r} "
                    f"or domain={data.domain!r} (id={existing.id}). Global records "
                    f"are shared across tenants — use this ID directly (e.g., via "
                    f"List Entries) instead of creating a tenant-scoped duplicate."
                )
            else:
                message = (
                    f"Company with name={data.name!r} or domain={data.domain!r} "
                    f"already exists (id={existing.id})"
                )
            raise DuplicateEntityError(
                message,
                entity_type="company",
                existing_id=int(existing.id),
                existing_name=existing.name,
                existing_domain=existing.domain,
                existing_is_global=bool(existing.is_global),
            )

    payload = data.model_dump(by_alias=True, mode="json", exclude_none=True)
    if not data.person_ids:
        payload.pop("person_ids", None)
    result = await self._client.post("/organizations", json=payload, v1=True)

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

    return Company.model_validate(result)

delete(company_id: CompanyId) -> bool async

Delete a company.

Uses V1 API.

Source code in affinity/services/companies.py
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
async def delete(self, company_id: CompanyId) -> bool:
    """
    Delete a company.

    Uses V1 API.
    """
    result = await self._client.delete(f"/organizations/{company_id}", v1=True)
    invalidate_all_list_sizes(self._client)

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

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

get(company_id: CompanyId, *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, retries: int = 0, with_interaction_dates: bool = False, with_interaction_persons: bool = False) -> Company async

Get a single company by ID.

Parameters:

Name Type Description Default
company_id CompanyId

The company 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
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
Company

Company object with requested field data. When with_interaction_dates=True,

Company

the Company will have interaction_dates and interactions populated.

Raises:

Type Description
NotFoundError

If company does not exist after all retries.

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/companies.py
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
async def get(
    self,
    company_id: CompanyId,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    retries: int = 0,
    with_interaction_dates: bool = False,
    with_interaction_persons: bool = False,
) -> Company:
    """
    Get a single company by ID.

    Args:
        company_id: The company ID
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        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:
        Company object with requested field data. When with_interaction_dates=True,
        the Company will have interaction_dates and interactions populated.

    Raises:
        NotFoundError: If company does not exist after all retries.

    Note:
        When combining with_interaction_dates with field_ids/field_types,
        two API calls are made internally and the results are merged.
    """
    last_error: NotFoundError | None = None
    attempts = retries + 1  # retries=0 means 1 attempt
    has_field_filters = field_ids is not None or field_types is not None

    for attempt in range(attempts):
        try:
            if with_interaction_dates:
                # Fetch interaction data
                v1_params: dict[str, Any] = {"with_interaction_dates": True}
                if with_interaction_persons:
                    v1_params["with_interaction_persons"] = True
                interaction_data = await self._client.get(
                    f"/organizations/{company_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"/companies/{company_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 Company.model_validate(filtered_data)

                # No field filtering, return interaction data directly
                return Company.model_validate(interaction_data)

            # 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"/companies/{company_id}", params=params or None)
            return Company.model_validate(data)
        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 (with_interaction_dates=True)
    if last_error is not None and not with_interaction_dates:
        try:
            v1_data = await self._client.get(f"/organizations/{company_id}", v1=True)
            return Company.model_validate(v1_data)
        except NotFoundError:
            pass  # V1 also failed, raise original V2 error

    raise last_error  # type: ignore[misc]

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

Get associated opportunity IDs for a company.

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

Parameters:

Name Type Description Default
company_id CompanyId

The company 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 company

Source code in affinity/services/companies.py
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
async def get_associated_opportunity_ids(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[OpportunityId]:
    """
    Get associated opportunity IDs for a company.

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

    Args:
        company_id: The company ID
        max_results: Maximum number of opportunity IDs to return

    Returns:
        List of OpportunityId values associated with this company
    """
    data = await self._client.get(f"/organizations/{company_id}", v1=True)
    # Defensive: handle potential {"organization": {...}} wrapper
    organization = data.get("organization") if isinstance(data, dict) else None
    source = organization if isinstance(organization, 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(company_ids: Sequence[CompanyId], *, on_error: Literal['raise', 'skip'] = 'raise') -> dict[CompanyId, builtins.list[OpportunityId]] async

Get opportunity associations for multiple companies.

Makes one V1 API call per company.

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Sequence of company IDs to fetch

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

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

'raise'

Returns:

Type Description
dict[CompanyId, list[OpportunityId]]

Dict mapping company_id -> list of opportunity_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/companies.py
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
async def get_associated_opportunity_ids_batch(
    self,
    company_ids: Sequence[CompanyId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[CompanyId, builtins.list[OpportunityId]]:
    """
    Get opportunity associations for multiple companies.

    Makes one V1 API call per company.

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

    Returns:
        Dict mapping company_id -> list of opportunity_ids

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

get_associated_people(company_id: CompanyId, *, max_results: int | None = None) -> builtins.list[Person] async

Get Person objects associated with a company.

Uses V2 batch lookup for efficiency (1 API call per 100 persons instead of 1 per person).

Source code in affinity/services/companies.py
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
async def get_associated_people(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[Person]:
    """
    Get Person objects associated with a company.

    Uses V2 batch lookup for efficiency (1 API call per 100 persons
    instead of 1 per person).
    """
    person_ids = await self.get_associated_person_ids(company_id, max_results=max_results)
    if not person_ids:
        return []

    # Use V2 batch lookup: GET /persons?ids=1&ids=2&ids=3
    # Note: person_ids is already truncated by get_associated_person_ids if max_results set
    params: dict[str, Any] = {"ids": [int(pid) for pid in person_ids]}

    people: builtins.list[Person] = []
    data = await self._client.get("/persons", params=params)  # V2 batch
    for item in data.get("data", []):
        people.append(Person.model_validate(item))

    # Handle pagination if needed (>100 persons)
    # Note: max_results check is defensive - person_ids was already truncated above
    pagination = data.get("pagination") or {}
    next_url = pagination.get("nextUrl")
    while next_url and (max_results is None or len(people) < max_results):
        data = await self._client.get_url(next_url)
        for item in data.get("data", []):
            people.append(Person.model_validate(item))
        next_url = (data.get("pagination") or {}).get("nextUrl")

    if max_results:
        return people[:max_results]
    return people

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

Get associated person IDs for a company.

V1-only exception: V2 does not expose company -> people associations. Uses GET /organizations/{id} and returns person_ids if present.

Source code in affinity/services/companies.py
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
async def get_associated_person_ids(
    self,
    company_id: CompanyId,
    *,
    max_results: int | None = None,
) -> builtins.list[PersonId]:
    """
    Get associated person IDs for a company.

    V1-only exception: V2 does not expose company -> people associations.
    Uses GET `/organizations/{id}` and returns `person_ids` if present.
    """
    data = await self._client.get(f"/organizations/{company_id}", v1=True)
    organization = data.get("organization") if isinstance(data, dict) else None
    source = organization if isinstance(organization, dict) else data
    person_ids = None
    if isinstance(source, dict):
        person_ids = source.get("person_ids") or source.get("personIds")

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

    ids = [PersonId(int(value)) for value in person_ids if value is not None]
    if max_results is not None and max_results >= 0:
        return ids[:max_results]
    return ids

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

Get person associations for multiple companies.

Makes one V1 API call per company.

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Sequence of company IDs to fetch

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

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

'raise'

Returns:

Type Description
dict[CompanyId, list[PersonId]]

Dict mapping company_id -> list of person_ids

Raises:

Type Description
AffinityError

If on_error="raise" and any fetch fails.

Source code in affinity/services/companies.py
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
async def get_associated_person_ids_batch(
    self,
    company_ids: Sequence[CompanyId],
    *,
    on_error: Literal["raise", "skip"] = "raise",
) -> dict[CompanyId, builtins.list[PersonId]]:
    """
    Get person associations for multiple companies.

    Makes one V1 API call per company.

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

    Returns:
        Dict mapping company_id -> list of person_ids

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

get_field_dropdown_options(field_id: AnyFieldId, *, with_status_types: bool = False) -> builtins.list[DropdownOption] async

All options of a company dropdown, ranked-dropdown or status field (every page).

Options with type, rank, color and (status fields) status_category / win_rate. Options of global company fields can only be read; list-specific fields' options are managed through client.lists. with_status_types=True: see lists.get_field_dropdown_options.

Source code in affinity/services/companies.py
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
async def get_field_dropdown_options(
    self, field_id: AnyFieldId, *, with_status_types: bool = False
) -> builtins.list[DropdownOption]:
    """All options of a company dropdown, ranked-dropdown or status field (every page).

    Options with ``type``, ``rank``, ``color`` and (status fields) ``status_category`` /
    ``win_rate``. Options of global company fields can only be read; list-specific fields'
    options are managed through ``client.lists``. ``with_status_types=True``: see
    ``lists.get_field_dropdown_options``.
    """
    data = await self._client.get_all_pages(
        options_path(field_id, list_id=None, entity="companies"),
        params={"limit": 100},
        min_api_version=DROPDOWN_OPTION_WRITES_MIN_API_VERSION if with_status_types else None,
    )
    return parse_options(data)

get_field_values(company_id: CompanyId, *, ids: Sequence[AnyFieldId | str] | None = None) -> FieldValues async

Field values of one company, keyed by field id (GET /v2/companies/{id}/fields).

Parameters:

Name Type Description Default
company_id CompanyId

The company.

required
ids Sequence[AnyFieldId | str] | None

Only these fields (server-side filter); all fields when omitted.

None
Source code in affinity/services/companies.py
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
async def get_field_values(
    self,
    company_id: CompanyId,
    *,
    ids: Sequence[AnyFieldId | str] | None = None,
) -> FieldValues:
    """
    Field values of one company, keyed by field id (``GET /v2/companies/{id}/fields``).

    Args:
        company_id: The company.
        ids: Only these fields (server-side filter); all fields when omitted.
    """
    params = {"ids": [str(fid) for fid in ids]} if ids else None
    data = await self._client.get_all_pages(f"/companies/{company_id}/fields", params=params)
    return FieldValues.model_validate(data.get("data", []))

get_fields(*, filter: str | None = None, includes: Sequence[str] | None = None) -> builtins.list[FieldMetadata] async

Get metadata about company fields.

Cached for performance.

Parameters:

Name Type Description Default
filter str | None

Filter on the field name: name="Location" (exact) or name=~Loc (substring); both case-sensitive. Combine clauses with |. Only name is filterable; anything else is rejected with 400.

None
includes Sequence[str] | None

Extra properties per field: "filterability", "sortability" (read them via is_filterable / is_sortable).

None
Source code in affinity/services/companies.py
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
async def get_fields(
    self,
    *,
    filter: str | None = None,
    includes: Sequence[str] | None = None,
) -> builtins.list[FieldMetadata]:
    """
    Get metadata about company fields.

    Cached for performance.

    Args:
        filter: Filter on the field name: ``name="Location"`` (exact) or ``name=~Loc``
            (substring); both case-sensitive. Combine clauses with ``|``. Only ``name``
            is filterable; anything else is rejected with 400.
        includes: Extra properties per field: ``"filterability"``, ``"sortability"``
            (read them via ``is_filterable`` / ``is_sortable``).
    """
    params, cache_key = build_fields_query(
        "company_fields:_all_",
        filter=filter,
        includes=includes,
    )

    data = await self._client.get_all_pages(
        "/companies/fields",
        params=params or None,
        cache_key=cache_key,
        cache_ttl=300,
    )

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

get_first(*, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> Company | None async

Get the first company from the list endpoint, or None if no results.

See CompanyService.get_first() for details.

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
async def get_first(
    self,
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> Company | None:
    """
    Get the first company from the list endpoint, or None if no results.

    See CompanyService.get_first() for details.

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    page = await self.list(
        field_ids=field_ids,
        field_types=field_types,
        limit=1,
    )
    return page.data[0] if page.data else None

get_list_entries(company_id: CompanyId, *, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[ListEntry] async

Get all list entries for a company across all lists.

Returns comprehensive field data for each list entry. Each entry's entity_id is company_id and its entity_type is EntityType.ORGANIZATION; entity is None (this endpoint doesn't embed the company). A cursor must come from this company's entries.

Source code in affinity/services/companies.py
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
async def get_list_entries(
    self,
    company_id: CompanyId,
    *,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[ListEntry]:
    """
    Get all list entries for a company across all lists.

    Returns comprehensive field data for each list entry. Each entry's ``entity_id`` is
    ``company_id`` and its ``entity_type`` is ``EntityType.ORGANIZATION``; ``entity`` is
    ``None`` (this endpoint doesn't embed the company). A ``cursor`` must come from this
    company's entries.
    """
    path = f"/companies/{company_id}/list-entries"
    if cursor is not None:
        if limit is not None:
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context. Start a new pagination sequence without a cursor to change "
                "parameters."
            )
        check_list_entries_cursor(cursor, path)
        data = await self._client.get_url(cursor)
    else:
        params: dict[str, Any] = {}
        check_positive_limit(limit)
        if limit is not None:
            params["limit"] = limit
        data = await self._client.get(path, params=params or None)

    return entity_list_entries_page(
        data, entity_id=company_id, entity_type=EntityType.ORGANIZATION
    )

get_lists(company_id: CompanyId, *, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[ListSummary] async

Get all lists that contain this company.

Source code in affinity/services/companies.py
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
async def get_lists(
    self,
    company_id: CompanyId,
    *,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[ListSummary]:
    """Get all lists that contain this company."""
    if cursor is not None:
        if limit is not None:
            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] = {}
        check_positive_limit(limit)
        if limit is not None:
            params["limit"] = limit
        data = await self._client.get(
            f"/companies/{company_id}/lists",
            params=params or None,
        )

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

get_many(company_ids: Sequence[CompanyId], *, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None) -> PaginatedResponse[Company] async

Fetch multiple companies by ID in a single API call.

This is a convenience alias for list(ids=[...]).

Parameters:

Name Type Description Default
company_ids Sequence[CompanyId]

Company IDs to fetch

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

Returns:

Type Description
PaginatedResponse[Company]

Paginated response with companies

Example

companies = await client.companies.get_many([CompanyId(1), CompanyId(2)]) for company in companies.data: ... print(company.name)

Source code in affinity/services/companies.py
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
async def get_many(
    self,
    company_ids: Sequence[CompanyId],
    *,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
) -> PaginatedResponse[Company]:
    """
    Fetch multiple companies by ID in a single API call.

    This is a convenience alias for ``list(ids=[...])``.

    Args:
        company_ids: Company IDs to fetch
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])

    Returns:
        Paginated response with companies

    Example:
        >>> companies = await client.companies.get_many([CompanyId(1), CompanyId(2)])
        >>> for company in companies.data:
        ...     print(company.name)
    """
    return await self.list(ids=company_ids, field_ids=field_ids, field_types=field_types)

get_merge_state(merge_id: int) -> CompanyMergeState async

One past company merge (see :meth:list_merges).

Source code in affinity/services/companies.py
2627
2628
2629
2630
2631
async def get_merge_state(self, merge_id: int) -> CompanyMergeState:
    """One past company merge (see :meth:`list_merges`)."""
    return CompanyMergeState.model_validate(
        await self._client.get(f"/company-merges/{int(merge_id)}")
    )

get_merge_status(task_id: str) -> MergeTask async

Check the status of a merge operation.

Source code in affinity/services/companies.py
2584
2585
2586
2587
async def get_merge_status(self, task_id: str) -> MergeTask:
    """Check the status of a merge operation."""
    data = await self._client.get(f"/tasks/company-merges/{task_id}")
    return MergeTask.model_validate(data)

iter(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, **_unsupported: Any) -> AsyncIterator[Company]

Auto-paginate all companies.

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

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def iter(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    **_unsupported: Any,
) -> AsyncIterator[Company]:
    """
    Auto-paginate all companies.

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

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    return self.all(ids=ids, field_ids=field_ids, field_types=field_types)

iter_merges(*, status: str | None = None, task_id: str | None = None) -> AsyncIterator[CompanyMergeState]

All past company merges matching the filters (every page).

Source code in affinity/services/companies.py
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
def iter_merges(
    self, *, status: str | None = None, task_id: str | None = None
) -> AsyncIterator[CompanyMergeState]:
    """All past company merges matching the filters (every page)."""

    async def fetch_page(next_url: str | None) -> PaginatedResponse[CompanyMergeState]:
        if next_url:
            return await self.list_merges(cursor=next_url)
        return await self.list_merges(status=status, task_id=task_id)

    return AsyncPageIterator(fetch_page)

iter_notes(company_id: CompanyId, *, creator_id: int | None = None, created_after: datetime | None = None, created_before: datetime | None = None, updated_after: datetime | None = None, limit: int | None = None) -> AsyncIterator[NoteV2]

All of this company's notes (every page); see :meth:list_notes.

Source code in affinity/services/companies.py
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
def iter_notes(
    self,
    company_id: CompanyId,
    *,
    creator_id: int | None = None,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    updated_after: datetime | None = None,
    limit: int | None = None,
) -> AsyncIterator[NoteV2]:
    """All of this company's notes (every page); see :meth:`list_notes`."""

    async def fetch_page(next_url: str | None) -> PaginatedResponse[NoteV2]:
        if next_url:
            return await self.list_notes(company_id, cursor=next_url)
        return await self.list_notes(
            company_id,
            creator_id=creator_id,
            created_after=created_after,
            created_before=created_before,
            updated_after=updated_after,
            limit=limit,
        )

    return AsyncPageIterator(fetch_page)

iter_relationships(company_id: CompanyId, *, min_score: float | None = None, order: Literal['asc', 'desc'] = 'desc', limit: int | None = None) -> AsyncIterator[Relationship]

All relationships for this company (every page); see :meth:list_relationships.

Source code in affinity/services/companies.py
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
def iter_relationships(
    self,
    company_id: CompanyId,
    *,
    min_score: float | None = None,
    order: Literal["asc", "desc"] = "desc",
    limit: int | None = None,
) -> AsyncIterator[Relationship]:
    """All relationships for this company (every page); see :meth:`list_relationships`."""

    async def fetch_page(next_url: str | None) -> PaginatedResponse[Relationship]:
        if next_url:
            return await self.list_relationships(company_id, cursor=next_url)
        return await self.list_relationships(
            company_id, min_score=min_score, order=order, limit=limit
        )

    return AsyncPageIterator(fetch_page)

list(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, limit: int | None = None, cursor: str | None = None, **_unsupported: Any) -> PaginatedResponse[Company] async

Get a page of companies.

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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 (e.g., ["enriched", "global"])

None
limit int | None

Maximum number of results (API default: 100)

None
cursor str | None

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

None

Returns:

Type Description
PaginatedResponse[Company]

Paginated response with companies

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
async def list(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    limit: int | None = None,
    cursor: str | None = None,
    **_unsupported: Any,
) -> PaginatedResponse[Company]:
    """
    Get a page of companies.

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        limit: Maximum number of results (API default: 100)
        cursor: Cursor to resume pagination (opaque; obtained from prior responses)

    Returns:
        Paginated response with companies

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    validate_entity_field_types(field_types, endpoint="company")
    if cursor is not None:
        if any(p is not None for p in (ids, field_ids, field_types, 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:
        check_positive_limit(limit)
        ids = materialize_ids(ids)
        if no_ids(ids):
            return PaginatedResponse[Company]()
        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 limit is not None:
            params["limit"] = limit
        data = await self._client.get("/companies", params=params or None)

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

list_merges(*, status: str | None = None, task_id: str | None = None, limit: int | None = None, cursor: str | None = None) -> PaginatedResponse[CompanyMergeState] async

One page of past company merges, newest first.

status is "in-progress", "success" or "failed"; task_id (or the task URL a merge returned) limits it to one merge task. Needs the "Manage duplicates" permission and the organization admin role (otherwise AuthorizationError).

Source code in affinity/services/companies.py
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
async def list_merges(
    self,
    *,
    status: str | None = None,
    task_id: str | None = None,
    limit: int | None = None,
    cursor: str | None = None,
) -> PaginatedResponse[CompanyMergeState]:
    """One page of past company merges, newest first.

    ``status`` is ``"in-progress"``, ``"success"`` or ``"failed"``; ``task_id`` (or the task
    URL a merge returned) limits it to one merge task. Needs the "Manage duplicates"
    permission and the organization admin role (otherwise ``AuthorizationError``).
    """
    check_cursor_alone(cursor, status, task_id, limit)
    if cursor is not None:
        return page_of(CompanyMergeState, await self._client.get_url(cursor))
    params = merge_params(status=status, task_id=task_id, limit=limit)
    return page_of(
        CompanyMergeState, await self._client.get("/company-merges", params=params or None)
    )

list_notes(company_id: CompanyId, *, creator_id: int | None = None, created_after: datetime | None = None, created_before: datetime | None = None, updated_after: datetime | None = None, limit: int | None = None, total_count: bool = False, cursor: str | None = None) -> PaginatedResponse[NoteV2] async

One page of this company's notes as V2 notes (NoteV2; replies not included).

Filters: creator_id, created_after (inclusive) / created_before (exclusive), updated_after, rounded outward to whole seconds. limit is 1-100. Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).

Source code in affinity/services/companies.py
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
async def list_notes(
    self,
    company_id: CompanyId,
    *,
    creator_id: int | None = None,
    created_after: datetime | None = None,
    created_before: datetime | None = None,
    updated_after: datetime | None = None,
    limit: int | None = None,
    total_count: bool = False,
    cursor: str | None = None,
) -> PaginatedResponse[NoteV2]:
    """One page of this company's notes as V2 notes (``NoteV2``; replies not included).

    Filters: ``creator_id``, ``created_after`` (inclusive) / ``created_before`` (exclusive),
    ``updated_after``, rounded outward to whole seconds. ``limit`` is 1-100.
    Needs Affinity API version 2026-07-15 or newer (sent for this call and every page).
    """
    check_cursor_alone(
        cursor, creator_id, created_after, created_before, updated_after, limit, total_count
    )
    if cursor is not None:
        return page_of(
            NoteV2,
            await self._client.get_url(cursor, min_api_version=COMPANY_NOTES_MIN_API_VERSION),
        )
    params = note_params(
        creator_id=creator_id,
        created_after=created_after,
        created_before=created_before,
        updated_after=updated_after,
        limit=limit,
        total_count=total_count,
    )
    return page_of(
        NoteV2,
        await self._client.get(
            f"/companies/{int(company_id)}/notes",
            params=params or None,
            min_api_version=COMPANY_NOTES_MIN_API_VERSION,
        ),
    )

list_relationships(company_id: CompanyId, *, min_score: float | None = None, order: Literal['asc', 'desc'] = 'desc', limit: int | None = None, total_count: bool = False, cursor: str | None = None) -> PaginatedResponse[Relationship] async

One page of the relationships between your team and this company's people.

Strongest first (order="asc" for weakest first). min_score (0.0-1.0) keeps relationships at least that strong; relationships known only from LinkedIn have score 0, so any min_score above 0 drops them. limit is 1-100 (API default 20). Needs Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).

Source code in affinity/services/companies.py
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
async def list_relationships(
    self,
    company_id: CompanyId,
    *,
    min_score: float | None = None,
    order: Literal["asc", "desc"] = "desc",
    limit: int | None = None,
    total_count: bool = False,
    cursor: str | None = None,
) -> PaginatedResponse[Relationship]:
    """One page of the relationships between your team and this company's people.

    Strongest first (``order="asc"`` for weakest first). ``min_score`` (0.0-1.0) keeps
    relationships at least that strong; relationships known only from LinkedIn have score 0,
    so any ``min_score`` above 0 drops them. ``limit`` is 1-100 (API default 20). Needs
    Affinity API version {RELATIONSHIPS_MIN_API_VERSION} (sent for this call and every page).
    """
    if cursor is not None:
        if min_score is not None or limit is not None or total_count or order != "desc":
            raise ValueError(
                "Cannot combine 'cursor' with other parameters; cursor encodes all query "
                "context."
            )
        return page_of(
            Relationship,
            await self._client.get_url(cursor, min_api_version=RELATIONSHIPS_MIN_API_VERSION),
        )
    params = relationship_params(
        min_score=min_score, order=order, limit=limit, total_count=total_count
    )
    return page_of(
        Relationship,
        await self._client.get(
            f"/companies/{int(company_id)}/relationships",
            params=params or None,
            min_api_version=RELATIONSHIPS_MIN_API_VERSION,
        ),
    )

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

Merge a duplicate company into a primary company.

Returns a task URL to check merge status.

Source code in affinity/services/companies.py
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
async def merge(
    self,
    primary_id: CompanyId,
    duplicate_id: CompanyId,
) -> str:
    """
    Merge a duplicate company into a primary company.

    Returns a task URL to check merge status.
    """
    result = await self._client.post(
        "/company-merges",
        json={
            "primaryCompanyId": int(primary_id),
            "duplicateCompanyId": int(duplicate_id),
        },
    )
    return merge_task_url(result, "company")

pages(*, ids: Sequence[CompanyId] | None = None, field_ids: Sequence[AnyFieldId] | None = None, field_types: Sequence[FieldType] | None = None, limit: int | None = None, cursor: str | None = None, **_unsupported: Any) -> AsyncIterator[PaginatedResponse[Company]]

Iterate company pages (not items), yielding PaginatedResponse[Company].

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

Parameters:

Name Type Description Default
ids Sequence[CompanyId] | None

Specific company 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 (e.g., ["enriched", "global"])

None
limit int | None

Maximum results per page

None
cursor str | None

Cursor to resume pagination

None

Returns:

Type Description
AsyncIterator[PaginatedResponse[Company]]

AsyncIterator of PaginatedResponse[Company]

Note

The V2 /companies endpoint silently ignores any filter= parameter — passing one would return unfiltered results without warning. This method therefore rejects filter= with a ValueError. To search companies by name or domain use client.companies.search_pages(term). To filter by list-specific fields use client.lists.entries(list_id).list(filter=...).

Source code in affinity/services/companies.py
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
def pages(
    self,
    *,
    ids: Sequence[CompanyId] | None = None,
    field_ids: Sequence[AnyFieldId] | None = None,
    field_types: Sequence[FieldType] | None = None,
    limit: int | None = None,
    cursor: str | None = None,
    **_unsupported: Any,
) -> AsyncIterator[PaginatedResponse[Company]]:
    """
    Iterate company pages (not items), yielding `PaginatedResponse[Company]`.

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

    Args:
        ids: Specific company IDs to fetch (batch lookup)
        field_ids: Specific field IDs to include in response
        field_types: Field types to include (e.g., ["enriched", "global"])
        limit: Maximum results per page
        cursor: Cursor to resume pagination

    Returns:
        AsyncIterator of PaginatedResponse[Company]

    Note:
        The V2 /companies endpoint silently ignores any ``filter=`` parameter —
        passing one would return unfiltered results without warning. This method
        therefore rejects ``filter=`` with a ``ValueError``. To search companies
        by name or domain use ``client.companies.search_pages(term)``. To filter
        by list-specific fields use ``client.lists.entries(list_id).list(filter=...)``.
    """
    if "filter" in _unsupported:
        raise ValueError(
            "V2 /companies does not support server-side filter. "
            "To search by name/domain use client.companies.search_pages(term). "
            "To filter by list-specific fields use "
            "client.lists.entries(list_id).list(filter=...)."
        )
    if _unsupported:
        raise TypeError(f"Unexpected keyword arguments: {list(_unsupported)}")
    return self._pages_iter(
        ids=ids,
        field_ids=field_ids,
        field_types=field_types,
        limit=limit,
        cursor=cursor,
    )

resolve(*, domain: str | None = None, name: str | None = None) -> Company | None async

Find a single company by domain 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/companies.py
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
async def resolve(
    self,
    *,
    domain: str | None = None,
    name: str | None = None,
) -> Company | None:
    """
    Find a single company by domain 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 domain and not name:
        raise ValueError("Must provide either domain or name")

    term = domain or name or ""
    result = await self.search(term, page_size=10)

    for company in result.data:
        if domain and company.domain and company.domain.lower() == domain.lower():
            return company
        if name and company.name and company.name.lower() == name.lower():
            return company

    return None

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[Company] async

Search for companies by name or domain.

Uses V1 API for search functionality not available in V2.

Source code in affinity/services/companies.py
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
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[Company]:
    """
    Search for companies by name or domain.

    Uses V1 API for search functionality not available in V2.
    """
    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("/organizations", params=params, v1=True)
    items = [Company.model_validate(o) for o in data.get("organizations", [])]
    return PaginatedResponse[Company](
        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[Company] async

Iterate all V1 company-search results with automatic pagination.

Parameters:

Name Type Description Default
term str

Search term (name or domain)

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[Company]

Company objects matching the search term

Source code in affinity/services/companies.py
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
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[Company]:
    """
    Iterate all V1 company-search results with automatic pagination.

    Args:
        term: Search term (name or domain)
        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:
        Company 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 company in page.data:
            yield company

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[Company]] async

Iterate V1 company-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 domain)

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[Company]]

PaginatedResponse[Company] for each page

Source code in affinity/services/companies.py
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
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[Company]]:
    """
    Iterate V1 company-search result pages.

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

    Args:
        term: Search term (name or domain)
        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[Company] 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(company_id: CompanyId, data: CompanyUpdate) -> Company async

Update an existing company.

Uses V1 API.

Source code in affinity/services/companies.py
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
async def update(self, company_id: CompanyId, data: CompanyUpdate) -> Company:
    """
    Update an existing company.

    Uses V1 API.
    """
    payload = data.model_dump(
        by_alias=True,
        mode="json",
        exclude_unset=True,
        exclude_none=True,
    )
    result = await self._client.put(
        f"/organizations/{company_id}",
        json=payload,
        v1=True,
    )

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

    return Company.model_validate(result)