feat: MH claim 15-digit claim number check, procedure code retry, copy/paste appointment

- MassHealth claim: pick the visible typeahead option for procedure codes,
  verify the code stuck (retry), re-check all lines before submit
- MassHealth claim: only an exact 15-digit claim number counts as submitted;
  otherwise fail with ERROR:CLAIM_NOT_SUBMITTED
- Appointments: right-click "Copy the appointment" and "Paste the appointment"
  on an empty slot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 17:38:12 -05:00
co-authored by Claude Opus 5.5
parent 4cd780e9b2
commit 1968e3bfcc
2 changed files with 159 additions and 31 deletions
@@ -21,6 +21,8 @@ import {
Trash2,
CreditCard,
ClipboardList,
ClipboardPaste,
Copy,
StickyNote,
Shield,
FileCheck,
@@ -168,6 +170,7 @@ function resolveAppointmentBadgeStatus(apt: ScheduledAppointment): PatientStatus
// Define a unique ID for the appointment context menu
const APPOINTMENT_CONTEXT_MENU_ID = "appointment-context-menu";
const SLOT_CONTEXT_MENU_ID = "slot-context-menu";
// 🔑 exported base key
const SCHEDULE_DATE_KEY = "schedule_selected_date";
@@ -277,6 +280,14 @@ export default function AppointmentsPage() {
staffId: number;
} | null>(null);
const [newApptPrefill, setNewApptPrefill] = useState<NewAppointmentPrefill | null>(null);
// Appointment copied via right-click "Copy the appointment", pasted onto an empty slot
const [copiedAppointment, setCopiedAppointment] = useState<{
patientId: number;
patientName: string;
title: string;
type: string;
notes?: string;
} | null>(null);
const toggleReminderColumn = (staffId: number) => {
setSelectedReminderColumns((prev) => {
@@ -329,6 +340,9 @@ export default function AppointmentsPage() {
const { show } = useContextMenu({
id: APPOINTMENT_CONTEXT_MENU_ID,
});
const { show: showSlotMenu } = useContextMenu({
id: SLOT_CONTEXT_MENU_ID,
});
// ----------------------
// Day-level fetch: appointments + patients for selectedDate (lightweight)
@@ -922,6 +936,39 @@ export default function AppointmentsPage() {
}
};
const handleCopyAppointment = (appointmentId: number) => {
const apt = appointments.find((a) => a.id === appointmentId) as any;
if (!apt) return;
const patientName =
processedAppointments.find((a) => a.id === appointmentId)?.patientName ?? "";
setCopiedAppointment({
patientId: apt.patientId,
patientName,
title: apt.title,
type: apt.type,
notes: apt.notes ?? undefined,
});
toast({
title: "Appointment Copied",
description: `${patientName} — right-click an empty slot to paste.`,
});
};
const handlePasteAppointment = (timeSlot: TimeSlot, staffId: number) => {
if (!copiedAppointment || !user) return;
createAppointmentMutation.mutate({
patientId: copiedAppointment.patientId,
userId: user.id,
staffId,
title: copiedAppointment.title,
date: formatLocalDate(selectedDate),
type: copiedAppointment.type,
startTime: timeSlot.time,
endTime: timeSlot.time, // backend sets the real end time
notes: copiedAppointment.notes,
} as unknown as InsertAppointment);
};
// Function to display context menu
const handleContextMenu = (e: React.MouseEvent, appointmentId: number) => {
// Prevent the default browser context menu
@@ -1160,6 +1207,10 @@ export default function AppointmentsPage() {
: "text-gray-400 hover:bg-gray-100"
}`}
onClick={handleClickEmpty}
onContextMenu={(e) => {
e.preventDefault();
showSlotMenu({ event: e, props: { timeSlot, staffId } });
}}
>
<Plus className="h-4 w-4" />
</button>
@@ -2245,6 +2296,12 @@ export default function AppointmentsPage() {
Edit Appointment
</span>
</Item>
<Item onClick={({ props }) => handleCopyAppointment(props.appointmentId)}>
<span className="flex items-center gap-2">
<Copy className="h-4 w-4" />
Copy the appointment
</span>
</Item>
<Item
onClick={({ props }) =>
handleDeleteAppointment(props.appointmentId)
@@ -2327,6 +2384,21 @@ export default function AppointmentsPage() {
</Item>
</Menu>
{/* Empty-slot Context Menu */}
<Menu id={SLOT_CONTEXT_MENU_ID} animation="fade">
<Item
disabled={!copiedAppointment}
onClick={({ props }) => handlePasteAppointment(props.timeSlot, props.staffId)}
>
<span className="flex items-center gap-2">
<ClipboardPaste className="h-4 w-4" />
{copiedAppointment
? `Paste the appointment (${copiedAppointment.patientName})`
: "Paste the appointment"}
</span>
</Item>
</Menu>
{/* Main Content */}
<div className="flex flex-col lg:flex-row gap-6">
{/* Schedule Grid */}
@@ -1059,17 +1059,13 @@ class AutomationMassHealthClaimsLogin:
text = element.text.strip()
print(f"DEBUG: Checking element with selector {selector}: {text[:100]}")
# Look for 15-digit claim number pattern (MassHealth format: YYYYMMDD + 7 digits)
match = re.search(r'(\d{15})', text)
# Only an exact 15-digit number counts - shorter numbers on the page
# (e.g. timestamps on the unsubmitted form) are not claim numbers
match = re.search(r'(?<!\d)(\d{15})(?!\d)', text)
if match:
claim_number = match.group(1)
print(f"DEBUG: Found 15-digit claim number: {claim_number}")
return claim_number
# Also try 9-14 digit patterns
match = re.search(r'(\d{9,14})', text)
if match:
claim_number = match.group(1)
print(f"DEBUG: Found claim number (9-14 digits): {claim_number}")
return claim_number
except Exception as e:
print(f"DEBUG: Selector {selector} failed: {e}")
continue
@@ -1082,15 +1078,10 @@ class AutomationMassHealthClaimsLogin:
for (var i = 0; i < allElements.length; i++) {
var text = allElements[i].textContent || '';
// MassHealth format: 15 digits (YYYYMMDD + 7 digits)
var match15 = text.match(/(\d{15})/);
var match15 = text.match(/(?:^|\D)(\d{15})(?!\d)/);
if (match15) {
return match15[1];
}
// Also check for 9-14 digit patterns
var match9to14 = text.match(/(\d{9,14})/);
if (match9to14) {
return match9to14[1];
}
}
return null;
""")
@@ -1185,6 +1176,72 @@ class AutomationMassHealthClaimsLogin:
"LR": "Lower Right",
}
def fill_procedure_input(self, procedure_input, procedure_code, row_number, attempts=3):
"""Type a procedure code into a typeahead input and pick it from the dropdown.
Returns True once the input holds the code. The portal clears unselected
typeahead text on blur, which leaves the line blank ("This is a required field")."""
for attempt in range(1, attempts + 1):
procedure_input.clear()
procedure_input.send_keys(procedure_code)
time.sleep(3) # Wait for typeahead
# Other rows' dropdowns stay in the DOM (hidden), so pick a *visible* option,
# preferring the one that shows this procedure code
option = None
deadline = time.time() + 10
while option is None and time.time() < deadline:
visible = []
for li in self.driver.find_elements(By.XPATH, "//ul[contains(@class,'dropdown-menu')]//li"):
try:
if li.is_displayed():
visible.append(li)
except Exception:
continue
option = next((li for li in visible if procedure_code.upper() in li.text.upper()), None)
if option is None and visible:
option = visible[0]
if option is None:
time.sleep(0.5)
try:
if option is not None:
option.click()
else:
procedure_input.send_keys(Keys.TAB)
except Exception as e:
print(f"DEBUG: Selecting procedure option failed on row {row_number}: {e}")
time.sleep(2)
value = (procedure_input.get_attribute("value") or "").strip()
if procedure_code.upper() in value.upper():
print(f"DEBUG: Procedure code set on row {row_number}: '{value}'")
return True
print(f"DEBUG: Procedure code not set on row {row_number} (value='{value}'), attempt {attempt}/{attempts}")
return False
def verify_service_lines(self):
"""Before submit, make sure every service line still has its procedure code; re-fill any that were cleared."""
expected = [sl.get("procedureCode", "") for sl in self.serviceLines] if self.serviceLines else [self.procedureCode]
try:
procedure_inputs = self.driver.find_elements(
By.XPATH, "//input[@ng-model='serviceLine.procedure' and @placeholder='Code']"
)
if len(procedure_inputs) < len(expected):
return f"ERROR:SERVICE_LINE_MISSING - found {len(procedure_inputs)} procedure rows, expected {len(expected)}"
for i, code in enumerate(expected):
if not code:
continue
value = (procedure_inputs[i].get_attribute("value") or "").strip()
if code.upper() in value.upper():
continue
print(f"DEBUG: Row {i + 1} procedure is '{value}', expected {code} - re-filling")
if not self.fill_procedure_input(procedure_inputs[i], code, i + 1):
return f"ERROR:PROCEDURE_CODE_MISSING - row {i + 1} ({code}) is blank"
return "Success"
except Exception as e:
print(f"Error verifying service lines: {e}")
return f"ERROR:VERIFY_SERVICE_LINES_FAILED - {e}"
def fill_service_line(self, row_number=1, procedure_code="", tooth_number="", tooth_surface="", quadrant="", arch="Entire Oral Cavity", auth_number="AUTH123456", billed_amount=""):
wait = WebDriverWait(self.driver, 30)
@@ -1207,24 +1264,8 @@ class AutomationMassHealthClaimsLogin:
procedure_input = procedure_inputs[row_number - 1] # Convert to 0-based index
time.sleep(1)
procedure_input.clear()
procedure_input.send_keys(procedure_code)
time.sleep(3) # Wait for typeahead
# Try to select from dropdown if available
try:
dropdown = wait.until(
EC.visibility_of_element_located(
(By.XPATH, "//ul[contains(@class,'dropdown-menu') and not(contains(@class,'ng-hide'))]")
)
)
first_option = dropdown.find_element(By.XPATH, ".//li")
if first_option:
first_option.click()
time.sleep(2)
except:
procedure_input.send_keys(Keys.TAB)
time.sleep(1)
if not self.fill_procedure_input(procedure_input, procedure_code, row_number):
raise Exception(f"Procedure code {procedure_code} did not stick on row {row_number}")
# Fill Tooth Number - only if provided in claim form
if tooth_number:
@@ -1448,6 +1489,11 @@ class AutomationMassHealthClaimsLogin:
else:
print("DEBUG: No files to attach, skipping attachment step")
# Make sure no procedure code was cleared before submitting
verify_result = self.verify_service_lines()
if verify_result != "Success":
return {"status": "error", "message": verify_result}
# Click SUBMIT button to submit the claim
submit_result = self.click_submit_button()
if submit_result != "Success":
@@ -1458,6 +1504,16 @@ class AutomationMassHealthClaimsLogin:
if pdf_result.get("status") == "error":
return {"status": "error", "message": pdf_result.get("message")}
# A MassHealth claim number is always 15 digits (e.g. 202631101915600).
# Anything else means the portal did not accept the claim.
claim_number = str(pdf_result.get("claimNumber") or "")
if not re.fullmatch(r"\d{15}", claim_number):
return {
"status": "error",
"message": f"ERROR:CLAIM_NOT_SUBMITTED - no valid 15-digit MassHealth claim number "
f"(got '{claim_number or 'none'}'). Check the form for missing fields: {pdf_result.get('pdf_path')}",
}
# Optional: wait a moment so you can see the confirmation page
time.sleep(3)