# Import pandas for reading and cleaning the receiving log.
import pandas as pd
# Read every CSV field as text to preserve receipt IDs and original entries.
raw = pd.read_csv("receiving_log.csv", dtype="string", keep_default_na=False)
# Record each source column’s data type before making changes.
raw_types = raw.dtypes.astype(str).to_dict()
# Count the original dock labels to spot spelling and spacing differences.
dock_counts = raw["dock"].value_counts().to_dict()
# Make a working copy so held rows can retain their original values.
work = raw.copy()
# Trim spaces and standardize capitalization in the dock labels.
work["dock"] = work["dock"].str.strip().str.title()
# Parse receiving dates and mark unparseable entries as missing.
work["received_on"] = pd.to_datetime(work["received_on"], format="%Y-%m-%d", errors="coerce")
# Convert units to numbers and mark nonnumeric entries as missing.
qty = pd.to_numeric(work["units"], errors="coerce")
# Accept only positive whole quantities, treating missing values as invalid.
valid_units = (qty.gt(0) & qty.mod(1).eq(0)).fillna(False)
# Check each dock against the three approved locations.
valid_dock = work["dock"].isin(["East", "North", "South"])
# Require a valid quantity, an approved dock, and a parsed date.
valid = valid_units & valid_dock & work["received_on"].notna()
# Keep the original entries that failed validation for follow-up.
held = raw.loc[~valid].copy()
# Select the standardized rows that passed every check.
accepted = work.loc[valid].copy()
# Store accepted quantities as nullable integers.
accepted["units"] = qty.loc[valid].astype("Int64")
# Store the accepted dock labels as categories.
accepted["dock"] = accepted["dock"].astype("category")
# Flag every exact repeat after its first occurrence.
repeat = accepted.duplicated(keep="first")
# Keep one copy of each distinct accepted row.
clean = accepted.drop_duplicates().copy()
# Check that no receipt ID remains on two distinct released rows.
assert clean["receipt_id"].is_unique, "Conflicting receipt IDs require review"
# Verify that held rows, repeats, and released rows account for every input row.
assert len(raw) == len(held) + int(repeat.sum()) + len(clean)
# Sum released units for each dock present in the cleaned data.
units_by_dock = clean.groupby("dock", observed=True)["units"].sum()
# Display the original column types.
print("Source types:", raw_types)
# Display the frequency of each original dock label.
print("Raw dock labels:", dock_counts)
# Display the column types after cleaning.
print("Clean types:", clean.dtypes.astype(str).to_dict())
# Report how many rows entered each stage of reconciliation.
print("Input / held / repeats / released:", len(raw), len(held), int(repeat.sum()), len(clean))
# Report each dock’s released units and the combined total.
print("Units by dock:", units_by_dock.to_dict(), "| Total:", int(units_by_dock.sum()))
