folio-data-import 0.5.2__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: folio_data_import
3
- Version: 0.5.2
3
+ Version: 0.6.0
4
4
  Summary: A python module to perform bulk import of data into a FOLIO environment. Currently supports MARC and user data import.
5
5
  Author: Brooks Travis
6
6
  Author-email: Brooks Travis <brooks.travis@gmail.com>
@@ -177,6 +177,20 @@ folio-data-import users --user-file users.jsonl --user-match-key username
177
177
  folio-data-import users --user-file users.jsonl --default-preferred-contact-type email
178
178
  ```
179
179
 
180
+ **Update Behavior:** Control how existing records are updated:
181
+
182
+ > **⚠️ Breaking change in v0.6.0:** Prior versions incorrectly merged incoming records into existing records, preserving fields absent from the incoming data. Starting in v0.6.0, the default behavior is full replacement — fields not present in the incoming record are removed. If you depend on the previous merge behavior, use `--update-only-present-fields`.
183
+
184
+ - **Full replacement** (default): The incoming record completely replaces the existing record. Fields present in the existing record but absent from the incoming record are removed. The preferred contact type is preserved from the existing record when not specified in the incoming record.
185
+ ```shell
186
+ folio-data-import users --user-file users.jsonl
187
+ ```
188
+
189
+ - **Partial update**: Only fields present in the incoming record are updated; missing fields are preserved from the existing record.
190
+ ```shell
191
+ folio-data-import users --user-file users.jsonl --update-only-present-fields
192
+ ```
193
+
180
194
  **Field Protection:** Protect specific fields from being updated:
181
195
 
182
196
  - **Job-level protection** (applies to all records):
@@ -195,6 +209,16 @@ folio-data-import users --user-file users.jsonl --default-preferred-contact-type
195
209
  }
196
210
  ```
197
211
 
212
+ **User Deletion:** Delete users listed in the input file(s) instead of creating or updating them:
213
+ ```shell
214
+ folio-data-import users --user-file users.jsonl --delete-all
215
+ ```
216
+
217
+ - Only users that exist in FOLIO and match via the configured match key are deleted
218
+ - Staff and system users are automatically skipped to prevent accidental removal
219
+ - Associated request preferences, permission user records, and service point assignments are also removed
220
+ - An interactive confirmation prompt is displayed before deletions begin; use `--yes`/`-y` to skip it (required in non-interactive environments)
221
+
198
222
  #### Input Format
199
223
 
200
224
  JSON Lines format - one user object in the style<sup>*</sup> of [mod-user-import](https://github.com/folio-org/mod-user-import) (with extended support mentioned above) per line
@@ -149,6 +149,20 @@ folio-data-import users --user-file users.jsonl --user-match-key username
149
149
  folio-data-import users --user-file users.jsonl --default-preferred-contact-type email
150
150
  ```
151
151
 
152
+ **Update Behavior:** Control how existing records are updated:
153
+
154
+ > **⚠️ Breaking change in v0.6.0:** Prior versions incorrectly merged incoming records into existing records, preserving fields absent from the incoming data. Starting in v0.6.0, the default behavior is full replacement — fields not present in the incoming record are removed. If you depend on the previous merge behavior, use `--update-only-present-fields`.
155
+
156
+ - **Full replacement** (default): The incoming record completely replaces the existing record. Fields present in the existing record but absent from the incoming record are removed. The preferred contact type is preserved from the existing record when not specified in the incoming record.
157
+ ```shell
158
+ folio-data-import users --user-file users.jsonl
159
+ ```
160
+
161
+ - **Partial update**: Only fields present in the incoming record are updated; missing fields are preserved from the existing record.
162
+ ```shell
163
+ folio-data-import users --user-file users.jsonl --update-only-present-fields
164
+ ```
165
+
152
166
  **Field Protection:** Protect specific fields from being updated:
153
167
 
154
168
  - **Job-level protection** (applies to all records):
@@ -167,6 +181,16 @@ folio-data-import users --user-file users.jsonl --default-preferred-contact-type
167
181
  }
168
182
  ```
169
183
 
184
+ **User Deletion:** Delete users listed in the input file(s) instead of creating or updating them:
185
+ ```shell
186
+ folio-data-import users --user-file users.jsonl --delete-all
187
+ ```
188
+
189
+ - Only users that exist in FOLIO and match via the configured match key are deleted
190
+ - Staff and system users are automatically skipped to prevent accidental removal
191
+ - Associated request preferences, permission user records, and service point assignments are also removed
192
+ - An interactive confirmation prompt is displayed before deletions begin; use `--yes`/`-y` to skip it (required in non-interactive environments)
193
+
170
194
  #### Input Format
171
195
 
172
196
  JSON Lines format - one user object in the style<sup>*</sup> of [mod-user-import](https://github.com/folio-org/mod-user-import) (with extended support mentioned above) per line
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "folio_data_import"
3
- version = "0.5.2"
3
+ version = "0.6.0"
4
4
  description = "A python module to perform bulk import of data into a FOLIO environment. Currently supports MARC and user data import."
5
5
  authors = [{ name = "Brooks Travis", email = "brooks.travis@gmail.com" }]
6
6
  license = "MIT"
@@ -19,6 +19,7 @@ import cyclopts
19
19
  import folioclient
20
20
  import httpx
21
21
  from folioclient import FolioClient
22
+ from folioclient.exceptions import folio_errors
22
23
  from pydantic import BaseModel, Field
23
24
 
24
25
  from folio_data_import import get_folio_connection_parameters, set_up_cli_logging
@@ -650,6 +651,7 @@ class BatchPoster:
650
651
  if "id" in record and record["id"] in existing_records:
651
652
  self.prepare_record_for_upsert(record, existing_records[record["id"]])
652
653
 
654
+ @folio_errors
653
655
  async def post_batch(self, batch: List[dict]) -> tuple[httpx.Response, int, int]:
654
656
  """
655
657
  Post a batch of records to FOLIO.
@@ -45,6 +45,7 @@ PREFERRED_CONTACT_TYPES_MAP = {
45
45
 
46
46
 
47
47
  USER_MATCH_KEYS = ["username", "barcode", "externalSystemId"]
48
+ PROTECTED_USER_TYPES = ["staff", "system", "shadow", "dcb"]
48
49
 
49
50
 
50
51
  class UserImporterStats(BaseModel):
@@ -53,6 +54,7 @@ class UserImporterStats(BaseModel):
53
54
  created: int = 0
54
55
  updated: int = 0
55
56
  failed: int = 0
57
+ deleted: int = 0
56
58
 
57
59
 
58
60
  class UserImporter: # noqa: R0902
@@ -143,6 +145,13 @@ class UserImporter: # noqa: R0902
143
145
  description="Disable the progress bar display",
144
146
  ),
145
147
  ] = False
148
+ delete_all: Annotated[
149
+ bool,
150
+ Field(
151
+ title="Delete all users in file(s)",
152
+ description="Whether to delete existing users, rather than create/update.",
153
+ ),
154
+ ] = False
146
155
 
147
156
  logfile: AsyncTextIOWrapper
148
157
  errorfile: AsyncTextIOWrapper
@@ -475,7 +484,7 @@ class UserImporter: # noqa: R0902
475
484
  if existing_personal:
476
485
  existing_user["personal"] = existing_personal
477
486
  else:
478
- existing_user.update(user_obj)
487
+ existing_user = {"id": existing_user["id"], **user_obj}
479
488
  if "personal" in existing_user:
480
489
  existing_user["personal"].update(preferred_contact_type)
481
490
  else:
@@ -769,6 +778,59 @@ class UserImporter: # noqa: R0902
769
778
  )
770
779
  response.raise_for_status()
771
780
 
781
+ async def delete_user(
782
+ self, existing_user, existing_rp, existing_pu, existing_spu, line_number: int
783
+ ) -> None:
784
+ """
785
+ Deletes a user and associated objects.
786
+
787
+ Args:
788
+ existing_user (dict): The existing user object to be deleted.
789
+ existing_rp (dict): The existing request preference object associated with the user.
790
+ existing_pu (dict): The existing permission user object associated with the user.
791
+ existing_spu (dict): The existing service points user object associated with the user.
792
+ line_number (int): The line number in the input file for logging purposes.
793
+ Returns:
794
+ None
795
+ """
796
+ if existing_user.get("type", "") in PROTECTED_USER_TYPES:
797
+ logger.warning(
798
+ f"Row {line_number}: User {existing_user['id']} "
799
+ f"is of type {existing_user.get('type', '')}, "
800
+ "skipping deletion\n"
801
+ )
802
+ return
803
+ try:
804
+ if existing_user:
805
+ await self.folio_client.folio_delete_async(
806
+ f"/users/{existing_user['id']}",
807
+ )
808
+ if existing_rp:
809
+ await self.folio_client.folio_delete_async(
810
+ f"/request-preference-storage/request-preference/{existing_rp.get('id', '')}"
811
+ )
812
+ if existing_pu:
813
+ await self.folio_client.folio_delete_async(
814
+ f"/perms/users/{existing_pu.get('id', '')}"
815
+ )
816
+ if existing_spu:
817
+ await self.folio_client.folio_delete_async(
818
+ f"/service-points-users/{existing_spu.get('id', '')}"
819
+ )
820
+
821
+ if existing_user:
822
+ logger.debug(f"Row {line_number}: Deleted user {existing_user['id']}\n")
823
+
824
+ async with self.lock:
825
+ self.stats.deleted += 1
826
+ except folioclient.FolioError as ee:
827
+ logger.error(
828
+ f"Row {line_number}: Failed to delete user {existing_user['id']}: "
829
+ f"{str(getattr(getattr(ee, 'response', str(ee)), 'text', str(ee)))}\n"
830
+ )
831
+ async with self.lock:
832
+ self.stats.failed += 1
833
+
772
834
  async def process_line(
773
835
  self,
774
836
  user: str,
@@ -799,6 +861,12 @@ class UserImporter: # noqa: R0902
799
861
  existing_pu,
800
862
  existing_spu,
801
863
  ) = await self.process_existing_user(user_obj)
864
+ if self.config.delete_all:
865
+ if existing_user:
866
+ await self.delete_user(
867
+ existing_user, existing_rp, existing_pu, existing_spu, line_number
868
+ )
869
+ return
802
870
  await self.map_address_types(user_obj, line_number)
803
871
  await self.map_patron_groups(user_obj, line_number)
804
872
  await self.map_departments(user_obj, line_number)
@@ -970,10 +1038,11 @@ class UserImporter: # noqa: R0902
970
1038
  total_lines = sum(buf.count(b"\n") for buf in iter(lambda: f.read(1024 * 1024), b""))
971
1039
 
972
1040
  with self.reporter:
1041
+ description = "Deleting users" if self.config.delete_all else "Importing users"
973
1042
  task_id = self.reporter.start_task(
974
1043
  "users",
975
1044
  total=total_lines,
976
- description="Importing users",
1045
+ description=description,
977
1046
  )
978
1047
  openfile.seek(0)
979
1048
  tasks = []
@@ -984,6 +1053,55 @@ class UserImporter: # noqa: R0902
984
1053
  await asyncio.gather(*tasks)
985
1054
  duration = time.time() - start
986
1055
  async with self.lock:
1056
+ if self.config.delete_all:
1057
+ self.reporter.update_task(
1058
+ task_id,
1059
+ advance=len(tasks),
1060
+ deleted=self.stats.deleted,
1061
+ failed=self.stats.failed,
1062
+ )
1063
+ message = (
1064
+ f"{dt.now().isoformat(sep=' ', timespec='milliseconds')}: "
1065
+ f"Batch of {self.config.batch_size} users processed in "
1066
+ f"{duration:.2f} seconds. - Users deleted: {self.stats.deleted}"
1067
+ f" - Users failed: {self.stats.failed}"
1068
+ )
1069
+ else:
1070
+ self.reporter.update_task(
1071
+ task_id,
1072
+ advance=len(tasks),
1073
+ created=self.stats.created,
1074
+ updated=self.stats.updated,
1075
+ failed=self.stats.failed,
1076
+ )
1077
+ message = (
1078
+ f"{dt.now().isoformat(sep=' ', timespec='milliseconds')}: "
1079
+ f"Batch of {self.config.batch_size} users processed in "
1080
+ f"{duration:.2f} seconds. - Users created: {self.stats.created}"
1081
+ f" - Users updated: {self.stats.updated} - Users failed: "
1082
+ f"{self.stats.failed}"
1083
+ )
1084
+ logger.info(message)
1085
+ tasks = []
1086
+ if tasks:
1087
+ start = time.time()
1088
+ await asyncio.gather(*tasks)
1089
+ duration = time.time() - start
1090
+ async with self.lock:
1091
+ if self.config.delete_all:
1092
+ self.reporter.update_task(
1093
+ task_id,
1094
+ advance=len(tasks),
1095
+ deleted=self.stats.deleted,
1096
+ failed=self.stats.failed,
1097
+ )
1098
+ message = (
1099
+ f"{dt.now().isoformat(sep=' ', timespec='milliseconds')}: "
1100
+ f"Batch of {len(tasks)} users processed in {duration:.2f} seconds. - "
1101
+ f"Users deleted: {self.stats.deleted}"
1102
+ f" - Users failed: {self.stats.failed}"
1103
+ )
1104
+ else:
987
1105
  self.reporter.update_task(
988
1106
  task_id,
989
1107
  advance=len(tasks),
@@ -993,30 +1111,10 @@ class UserImporter: # noqa: R0902
993
1111
  )
994
1112
  message = (
995
1113
  f"{dt.now().isoformat(sep=' ', timespec='milliseconds')}: "
996
- f"Batch of {self.config.batch_size} users processed in {duration:.2f} "
997
- f"seconds. - Users created: {self.stats.created} - Users updated: "
1114
+ f"Batch of {len(tasks)} users processed in {duration:.2f} seconds. - "
1115
+ f"Users created: {self.stats.created} - Users updated: "
998
1116
  f"{self.stats.updated} - Users failed: {self.stats.failed}"
999
1117
  )
1000
- logger.info(message)
1001
- tasks = []
1002
- if tasks:
1003
- start = time.time()
1004
- await asyncio.gather(*tasks)
1005
- duration = time.time() - start
1006
- async with self.lock:
1007
- self.reporter.update_task(
1008
- task_id,
1009
- advance=len(tasks),
1010
- created=self.stats.created,
1011
- updated=self.stats.updated,
1012
- failed=self.stats.failed,
1013
- )
1014
- message = (
1015
- f"{dt.now().isoformat(sep=' ', timespec='milliseconds')}: "
1016
- f"Batch of {len(tasks)} users processed in {duration:.2f} seconds. - "
1017
- f"Users created: {self.stats.created} - Users updated: "
1018
- f"{self.stats.updated} - Users failed: {self.stats.failed}"
1019
- )
1020
1118
  logger.info(message)
1021
1119
 
1022
1120
  def get_stats(self) -> UserImporterStats:
@@ -1087,6 +1185,14 @@ def main(
1087
1185
  group="FOLIO Connection Parameters",
1088
1186
  ),
1089
1187
  ] = None,
1188
+ delete_all: Annotated[
1189
+ bool,
1190
+ cyclopts.Parameter(
1191
+ env_var="FOLIO_DELETE_ALL_USERS",
1192
+ show_env_var=True,
1193
+ group="Job Configuration Parameters",
1194
+ ),
1195
+ ] = False,
1090
1196
  fields_to_protect: Annotated[
1091
1197
  str | None,
1092
1198
  cyclopts.Parameter(
@@ -1126,6 +1232,14 @@ def main(
1126
1232
  cyclopts.Parameter(group="Job Configuration Parameters"),
1127
1233
  ] = "email",
1128
1234
  no_progress: Annotated[bool, cyclopts.Parameter(group="Job Configuration Parameters")] = False,
1235
+ yes: Annotated[
1236
+ bool,
1237
+ cyclopts.Parameter(
1238
+ name=["--yes", "-y"],
1239
+ group="Job Configuration Parameters",
1240
+ help="Skip confirmation prompt for destructive operations (e.g. --delete-all).",
1241
+ ),
1242
+ ] = False,
1129
1243
  debug: Annotated[
1130
1244
  bool,
1131
1245
  cyclopts.Parameter(
@@ -1146,6 +1260,7 @@ def main(
1146
1260
  user_file_paths (Tuple[Path, ...]): Path(s) to the user data file(s). Use
1147
1261
  --user-file-paths or --user-file-path (deprecated, will be removed in future versions).
1148
1262
  member_tenant_id (str): The FOLIO ECS member tenant id (if applicable).
1263
+ delete_all (bool): Whether to delete existing users, rather than create/update.
1149
1264
  fields_to_protect (str): Comma-separated list of fields to protect during update.
1150
1265
  update_only_present_fields (bool): Whether to update only fields present in the input.
1151
1266
  limit_async_requests (int): The maximum number of concurrent async HTTP requests.
@@ -1154,6 +1269,7 @@ def main(
1154
1269
  user_match_key (str): The key to match users (externalSystemId, username, barcode).
1155
1270
  default_preferred_contact_type (str): The default preferred contact type for users
1156
1271
  no_progress (bool): Whether to disable the progress bar.
1272
+ yes (bool): Skip confirmation prompt for destructive operations (e.g. --delete-all).
1157
1273
  debug (bool): Enable debug logging.
1158
1274
  """ # noqa: E501
1159
1275
  set_up_cli_logging(logger, "folio_user_import", debug, stream_level=logging.WARNING)
@@ -1174,11 +1290,24 @@ def main(
1174
1290
  report_file_base_path / f"failed_user_import_{dt.now(utc).strftime('%Y%m%d_%H%M%S')}.txt"
1175
1291
  )
1176
1292
 
1293
+ if delete_all:
1294
+ logger.warning(
1295
+ "--delete-all flag is set. Users present in the provided file(s) will be "
1296
+ "deleted rather than created or updated. Proceed with caution."
1297
+ )
1298
+ if not yes:
1299
+ if not sys.stdin.isatty():
1300
+ logger.critical("--delete-all requires --yes/-y flag in non-interactive mode.")
1301
+ sys.exit(1)
1302
+ input("Press Enter to proceed with deletions, or Ctrl+C to abort...")
1303
+
1177
1304
  config_data = {}
1178
1305
  if config_file:
1179
1306
  try:
1180
1307
  with open(config_file, "r") as f:
1181
1308
  config_data = json.load(f)
1309
+ # CLI flags override config file values
1310
+ config_data["delete_all"] = delete_all
1182
1311
  config = UserImporter.Config(**config_data)
1183
1312
  except Exception as e:
1184
1313
  logger.critical(f"Failed to load configuration file {config_file}: {e}")
@@ -1200,6 +1329,7 @@ def main(
1200
1329
  limit_simultaneous_requests=limit_async_requests,
1201
1330
  user_file_paths=file_paths_list,
1202
1331
  no_progress=no_progress,
1332
+ delete_all=delete_all,
1203
1333
  )
1204
1334
  try:
1205
1335
  importer = UserImporter(folio_client, config)
@@ -267,6 +267,7 @@ class GenericStatsColumn(ProgressColumn):
267
267
  ("posted", "Posted", "bright_green"),
268
268
  ("created", "Created", "green"),
269
269
  ("updated", "Updated", "cyan"),
270
+ ("deleted", "Deleted", "yellow"),
270
271
  ("failed", "Failed", "red"),
271
272
  ("processed", "Processed", "blue"),
272
273
  ]