diff --git a/apps/react/src/.DS_Store b/apps/react/src/.DS_Store new file mode 100644 index 0000000..0156856 Binary files /dev/null and b/apps/react/src/.DS_Store differ diff --git a/apps/react/src/components/EpilogFormContainer.tsx b/apps/react/src/components/EpilogFormContainer.tsx index 962b02c..7643c46 100644 --- a/apps/react/src/components/EpilogFormContainer.tsx +++ b/apps/react/src/components/EpilogFormContainer.tsx @@ -2,7 +2,7 @@ import { useContext } from "react"; import { classNames } from "../utils/classNames"; import { Button } from "./Button"; import Container from "./Container"; -/* import FormDataSpy from "./FormDataSpy"; */ +import FormDataSpy from "./FormDataSpy"; import { ExistingClaimContext } from "../contexts/existingClaimContext"; type Input = { @@ -20,7 +20,7 @@ const EpilogFormContainer: React.FC = ({ onSave, isCovered, children, -/* __debugFormData, */ + __debugFormData }) => { const claimId = useContext(ExistingClaimContext); @@ -54,7 +54,7 @@ const EpilogFormContainer: React.FC = ({ Important Coverage Note: Cardinal Care only covers services received at
(a) Stanford Health Care, (b) Menlo Medical Clinic, or (c) Sutter Health {children} - {/*{__debugFormData && }*/} + {__debugFormData && } ); diff --git a/apps/react/src/components/InputDate.tsx b/apps/react/src/components/InputDate.tsx index f7e3024..6772aaf 100644 --- a/apps/react/src/components/InputDate.tsx +++ b/apps/react/src/components/InputDate.tsx @@ -1,116 +1,54 @@ -import { DateTime } from "luxon"; -import { useCallback, useMemo, useRef, useState } from "react"; -import { FaRegCalendarAlt } from "react-icons/fa"; -import Datepicker from "tailwind-datepicker-react"; +import { useCallback, useContext, useState } from "react"; +//import { InputContext } from "../contexts/inputContext"; import { COMMON_INPUT_CLASSES } from "../consts/classes.const"; -import { classNames } from "../utils/classNames"; -import { stringToDate } from "../utils/epilogUtils"; -import { getButtonClassNames } from "./Button"; -// https://github.com/OMikkel/tailwind-datepicker-react - -/* -------------------------------------------------------------------------- */ -/* Types */ -/* -------------------------------------------------------------------------- */ - -type InputDate_Input = Omit< - React.ComponentProps, - "show" | "setShow" -> & { onBlur?: () => void }; - -/* -------------------------------------------------------------------------- */ -/* Functions */ -/* -------------------------------------------------------------------------- */ - -// We have to override the stuff that comes from Datepicker -const buttonClassNames = classNames( - getButtonClassNames("gray"), - "rounded-none", -); +type InputDateProps = { + value: string; // ISO date string "YYYY-MM-DD" + onChange: (newDate: Date) => void; + onBlur?: () => void; +}; -const InputDate: React.FC = ({ - options, +const InputDate: React.FC = ({ value, onChange, - ...props + onBlur }) => { - const [show, setShow] = useState(false); - const datePickerWrapperRef = useRef(null); - - const onChangeCallback = useCallback( - (date) => { - const dateString = DateTime.fromJSDate(date).toISODate(); - setInputValue(dateString); - onChange?.(date); - // Keep the calendar open even after selecting a date - }, - [onChange], - ); - - const opts = useMemo( - () => ({ - ...options, - theme: { - selected: "bg-blue-500 hover:bg-blue-700 text-white", - }, - }), - [options], - ); - - const [inputValue, setInputValue] = useState( - DateTime.fromJSDate(value).toISODate(), - ); +// const inputContext = useContext(InputContext); +// if (!inputContext) { +// throw new Error("InputContext must be provided"); +// } + + const [inputValue, setInputValue] = useState(value); + console.log("inputValueinInputDate", inputValue); + console.log("valueinInputDate", value); + + + const handleChange = useCallback((e: React.ChangeEvent) => { + const newDateValue = e.target.value; // "YYYY-MM-DD" format + setInputValue(newDateValue); + if (newDateValue.match(/^\d{4}-\d{2}-\d{2}$/)) { + const parts = newDateValue.split('-'); + const year = parts[0] || '1970'; // Default to 1970 if undefined + const month = parts[1] || '01'; // Default to January if undefined + const day = parts[2] || '01'; // Default to the first day if undefined + onChange(new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10))); + } + }, [onChange]); return ( - <> -
- + ); }; diff --git a/apps/react/src/components/InputSelectButtons.tsx b/apps/react/src/components/InputSelectButtons.tsx index c1cae01..8824bd5 100644 --- a/apps/react/src/components/InputSelectButtons.tsx +++ b/apps/react/src/components/InputSelectButtons.tsx @@ -29,43 +29,51 @@ export default function InputSelectButtons< canDeselect = true, options, }: InputSelectButtons_Input) { - const isSelected = (opt: TOptions[number]) => - Array.isArray(value) - ? value.some((v) => v.id === opt.id) - : value && value.id === opt.id; + const isSelected = (opt: TOptions[number]) => { + const optionKey = opt.id || opt.value; // Assuming all options have either an id or value + return Array.isArray(value) + ? value.some((v) => v.id === optionKey || v.label === optionKey) + : value && (value.id === optionKey || value.label === optionKey); + }; + + console.log("Current value in InputSelectButtons: ", value); + + return (
- {options.map((opt) => ( - - ))} + : opt; + onChange?.(newValue as unknown as TValue); + } + onBlur?.(); + }} + > + {opt.label} + + ); + })}
); } diff --git a/apps/react/src/components/RequiresExistingClaim.tsx b/apps/react/src/components/RequiresExistingClaim.tsx index dd4d664..02a7aef 100644 --- a/apps/react/src/components/RequiresExistingClaim.tsx +++ b/apps/react/src/components/RequiresExistingClaim.tsx @@ -13,7 +13,9 @@ export default function RequiresExistingClaim({ }) { /* ------------------------ Environmental conditions ------------------------ */ + const userDataset = useContext(UserDatasetContext); + console.log("userDatasetContext", UserDatasetContext); if (!userDataset) throw new Error( @@ -22,8 +24,11 @@ export default function RequiresExistingClaim({ /* ------------------------------ Actual check ------------------------------ */ + console.log("userDataset in RequiresExistingClaim", userDataset); const existingClaimIds = getExistingIds("claim", userDataset); + console.log("existingClaimIds In RequiresExistingClaim", existingClaimIds); + if (!existingClaimIds.includes(claimId)) { return ( diff --git a/apps/react/src/components/ResourceList.tsx b/apps/react/src/components/ResourceList.tsx index 776fe8a..a1e85b4 100644 --- a/apps/react/src/components/ResourceList.tsx +++ b/apps/react/src/components/ResourceList.tsx @@ -6,22 +6,24 @@ import { classNames } from "../utils/classNames"; import Container from "./Container"; import Heading from "./Heading"; -export default function ResourceList({ - heading, - items = [], - linkToListPage, - linkToAddNew, - expanded = false, - onClickRemove, -}: { +type ResourceListProps = { heading?: string; items?: ResourceListItem[]; linkToListPage: string; linkToAddNew?: string; expanded?: boolean; onClickRemove?: (resourceId: string) => void; -}) { - return ( +}; + +export default function ResourceList({ + heading, + items = [], + linkToListPage, + linkToAddNew, + expanded = false, + onClickRemove, + }: ResourceListProps) { + return ( {!expanded && (
@@ -60,26 +62,28 @@ export default function ResourceList({ ); } -function ResourceCard({ - isAddNewCard = false, - label = "Unnamed", - item, - linkTo = "#", - onClickRemove, -}: { - isAddNewCard?: boolean; - label?: string; - item?: any; - linkTo?: string; - onClickRemove?: () => void; -}) { +type ResourceCardProps = { + isAddNewCard?: boolean; + label?: string; + item?: any; // Specify a more specific type based on the actual structure of `item` + linkTo?: string; + onClickRemove?: () => void; + }; + + function ResourceCard({ + isAddNewCard = false, + label = "Unnamed", + item, + linkTo = "#", + onClickRemove, + }: ResourceCardProps) { const isPersonItem = item && "dob" in item; const isClaimItem = item && "policyId" in item; // Assuming 'policyId' indicates a claim item const navigate = useNavigate(); // Existing functions for formatting DOB and occupation - const formatDOB = (dob: any) => { + const formatDOB = (dob: string) => { // Split the dob string by "_" and rearrange it to "YYYY-MM-DD" format const [day, month, year] = dob.split("_"); const formattedDate = `${year}-${month}-${day}`; @@ -95,35 +99,39 @@ function ResourceCard({ }); }; - const formatClaimTime = (time: any) => { - const [datePart, timePart] = time.split(" "); - const [day, month, year] = datePart.split("_").map(Number); - const [hours, minutes] = timePart.split("_").map(Number); + const formatClaimTime = (time: string): string => { + const parts = time.split(" "); + if (parts.length < 2) { + return "Invalid time format"; // Appropriately handle cases where there's no space. + } + + const [datePart = "", timePart = ""] = parts; + const [day = 1, month = 1, year = 1970] = datePart.split("_").map(num => num ? Number(num) : 1); + const [hours = 0, minutes = 0] = timePart.split("_").map(num => num ? Number(num) : 0); + const date = new Date(year, month - 1, day, hours, minutes); - return format(date, "PPPp"); // Formats datetime to something like "April 5, 2024, 12:00 AM" + return format(date, "PPPp"); // 'date-fns' format }; + - const detailStyle = { + const detailStyle: React.CSSProperties = { color: "#555", fontSize: "0.9rem", marginTop: "0.3rem", - textAlign: "left" + textAlign: "left" as "left" // Ensuring textAlign is correctly typed }; + - const capitalizeOccupation = (occupation: any) => - occupation.replace(/(?:^|\s)\S/g, (a: any) => a.toUpperCase()); + const capitalizeOccupation = (occupation: string) => + occupation.replace(/(?:^|\s)\S/g, (a: string) => a.toUpperCase()); // Function to generate friendly ID for claims - const getFriendlyId = (id: any) => {return "Claim " + (parseInt(id.substring(5))+1)}; - - function formatLabel(label: any) { - // Split the label by underscores, capitalize the first letter of each word, and join them back with spaces - return label - .split("_") - .map((word: any) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(" "); - } + const getFriendlyId = (id: string) => "Claim " + (parseInt(id.substring(5))+1); + const formatLabel = (label: string) => label.split("_") + .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" "); + return ( <> +
+ )} + /> + ))} + + + ); + } else { + return ( + + + renderField(controlField, field) || + } + /> + + ); + } + })} + + + ); +}; + +function renderField( + field: ControllerRenderProps, + config: FormFieldConfig, +) { + switch (config.type) { + case "date": + const formattedDate = formatDate(field.value); // Ensure field.value is a Date object or similar + return ; + case "select": + return ; + case "text": + return ; + case "checkbox": + return ; + case "number": + return ; + default: + return ; + } +} + +export default GeneralPolicyForm; diff --git a/apps/react/src/consts/options.const.ts b/apps/react/src/consts/options.const.ts index b4051dc..6148250 100644 --- a/apps/react/src/consts/options.const.ts +++ b/apps/react/src/consts/options.const.ts @@ -24,3 +24,19 @@ export const YES_OR_NO = [ { id: "yes", label: "Yes" }, { id: "no", label: "No" }, ] satisfies BasicOption[]; + + +export const VACCINE_OPTIONS: BasicOption[] = [ + { id: 'moderna', label: 'Moderna' }, + { id: 'pfizer', label: 'Pfizer' }, + { id: 'other', label: 'Other' } + ]; + + export const VACCINE_HISTORY_OPTIONS: BasicOption[] = [ + { id: 'moderna', label: 'Moderna' }, + { id: 'pfizer', label: 'Pfizer' }, + { id: 'other', label: 'Other' }, + { id: 'new_formulation', label: 'Since September 11, 2023' } + ]; + + \ No newline at end of file diff --git a/apps/react/src/contexts/inputContext.ts b/apps/react/src/contexts/inputContext.ts new file mode 100644 index 0000000..0ec4d9b --- /dev/null +++ b/apps/react/src/contexts/inputContext.ts @@ -0,0 +1,9 @@ +import React from "react"; + +export type InputContext_Data = { + isLocked: boolean; +}; + +export const InputContext = React.createContext( + undefined, +); \ No newline at end of file diff --git a/apps/react/src/epilog/form-adapters/contraceptivesAdapter.ts b/apps/react/src/epilog/form-adapters/contraceptivesAdapter.ts index 48153ce..0e13cbe 100644 --- a/apps/react/src/epilog/form-adapters/contraceptivesAdapter.ts +++ b/apps/react/src/epilog/form-adapters/contraceptivesAdapter.ts @@ -61,8 +61,11 @@ export const formAdapter: FormAdapter = { claimId = undefined; } } + console.log("epilogDataset in contraceptives adapter before getNextId", epilogDataset); if (!claimId) claimId = getNextId("claim", epilogDataset); + console.log("nextId", claimId); + /* --------------------------------- Person --------------------------------- */ @@ -131,18 +134,32 @@ export const formAdapter: FormAdapter = { return formValues; }, + + formValuesToEpilog: (values) => { + console.log("values",values); /* --------------------------------- Person --------------------------------- */ + if (!values.person) { + throw new Error('person data is missing in form values.'); + } + const personId = values.person.id; /* --------------------------------- Policy --------------------------------- */ + if (!values.policy) { + throw new Error('policy data is missing in form values.'); + } + const policyId = values.policy.id; const policyType = values.policyType?.id || "nil"; /* ---------------------------------- Claim --------------------------------- */ + if (!values.claim) { + throw new Error('Claim data is missing in form values.'); + } const claimId = values.claim.id; const whenDate = values.when; diff --git a/apps/react/src/epilog/form-adapters/covid19VaccineAdapter.ts b/apps/react/src/epilog/form-adapters/covid19VaccineAdapter.ts index febbf2d..c24c418 100644 --- a/apps/react/src/epilog/form-adapters/covid19VaccineAdapter.ts +++ b/apps/react/src/epilog/form-adapters/covid19VaccineAdapter.ts @@ -177,7 +177,7 @@ export const formAdapter: FormAdapter = { ) as string[]; const [dateTimeResult] = compfinds( - read("time(Date, Time)"), + read("time(Date, Time)"), // ["time", "24_05_13", "22_50"] read(`claim.time(${claimId}, Date, Time)`), epilogDataset, [], @@ -267,16 +267,13 @@ export const formAdapter: FormAdapter = { person(${personId}) policy(${policyId}) claim(${claimId}) - person.dob(${personId}, ${dob}) person.occupation(${personId}, other) person.immunocompromised(${personId}, ${isPersonImmunocompromised}) - policy.type(${policyId}, ${policyType}) policy.insuree(${policyId}, ${personId}) policy.startdate(${policyId}, ${personId}, 01_08_2023) policy.enddate(${policyId}, ${personId}, 30_06_2024) - claim.policy(${claimId}, ${policyId}) claim.service_type(${claimId}, "covidVaccine") claim.claimant(${claimId}, ${personId}) diff --git a/apps/react/src/epilog/form-adapters/formConfigs.ts b/apps/react/src/epilog/form-adapters/formConfigs.ts new file mode 100644 index 0000000..7abe011 --- /dev/null +++ b/apps/react/src/epilog/form-adapters/formConfigs.ts @@ -0,0 +1,103 @@ +import { CONTRACEPTIVE_OPTIONS, LOCATIONS, VACCINE_OPTIONS, VACCINE_HISTORY_OPTIONS } from "../../consts/options.const"; + +export interface FormFieldConfig { + id: string; + label: string; + type: 'text' | 'select' | 'date' | 'checkbox' | 'number' | 'array'; + options?: Array<{ label: string; value: any }>; + defaultValue?: any; + mapping: string; + additionalText?: string; +} + + + export interface FormConfig { + fields: FormFieldConfig[]; + } + +export const configs = { + covidVaccine: { + fields: [ + { + id: 'dob', + label: 'Date of Birth', + type: 'date', + mapping: 'person.dob', + }, + { + id: 'isPersonImmunocompromised', + label: 'Are you immunocompromised?', + type: 'select', + options: [ + { label: 'Yes', value: 'yes' }, + { label: 'No', value: 'no' } + ], + mapping: 'person.immunocompromised' + }, + { + id: 'vaccinationHistory_vaccineTypes', + label: 'Vaccination History', + type: 'array', + options: VACCINE_HISTORY_OPTIONS, + mapping: 'claim.vaccination_history', + additionalText: "Add an entry for each Covid vaccine you've received. If you received it before September 11, 2023, indicate its type. If it was the most recent formulation (i.e. received since September 11, 2023), indicate that instead." + }, + { + id: 'vaccineBrand', + label: 'What brand of vaccine did you receive?', + type: 'select', + options: VACCINE_OPTIONS, + mapping: 'claim.vaccine_brand' + }, + { + id: 'when', + label: 'When was the vaccination performed?', + type: 'date', + mapping: 'claim.when' + }, + { + id: 'where', + label: 'Where was the vaccine administered?', + type: 'select', + options: LOCATIONS, + mapping: 'claim.where' + } + ] + }, + contraceptives: { + fields: [ + //{ + // id: 'policyType', + // label: 'Policy Type', + // type: 'select', + // options: [ + // { label: 'Cardinal Care', value: 'cardinal' }, + // { label: 'Kaiser HMO', value: 'kaiser' } + // ], + // mapping: 'policy.type' + //}, + { + id: 'contraceptiveService', + label: 'What contraceptive service did you have performed?', + type: 'select', + options: CONTRACEPTIVE_OPTIONS, + mapping: 'claim.contraceptive_service' + }, + { + id: 'when', + label: 'When was the service performed?', + type: 'date', + mapping: 'claim.time' + }, + { + id: 'where', + label: 'Where was the service performed?', + type: 'select', + options: LOCATIONS.map(loc => ({ label: loc.label, value: loc.id })), + mapping: 'claim.location' + } + ] + } +} as { [key: string]: FormConfig }; + +export default configs; diff --git a/apps/react/src/epilog/form-adapters/generalFormAdapter.ts b/apps/react/src/epilog/form-adapters/generalFormAdapter.ts new file mode 100644 index 0000000..4aa1a8d --- /dev/null +++ b/apps/react/src/epilog/form-adapters/generalFormAdapter.ts @@ -0,0 +1,340 @@ +import { + dateToString, + stringToDate, + timeOfDateToString, + getFirstOrNextId, + getNextId, + getPolicyOfClaim, + getExistingIds, +} from "../../utils/epilogUtils"; +import { configs, FormConfig } from "./formConfigs"; +import { CONTRACEPTIVE_OPTIONS, LOCATIONS, VACCINE_OPTIONS, VACCINE_HISTORY_OPTIONS } from "../../consts/options.const"; + +type Dataset = ReturnType; + +interface BasicOption { + id: string; + label: string; +} + +interface FormValues { + person: BasicOption; + policy: BasicOption; + claim: BasicOption; + [key: string]: any; +} + + +class GeneralFormAdapter { + private policyType: string; + private dataset: Dataset; + private claimId: string; + private personId: string; + private policyId: string; + + constructor(policyType: string, dataset: Dataset, claimId?: string, forceNewClaimId: boolean = false) { + console.log(`Constructor called with claimId: ${claimId} and forceNewClaimId: ${forceNewClaimId}`); + this.policyType = policyType; + console.log("initial dataset", grindem(dataset)); + console.log("typeof dataset", typeof dataset); + this.dataset = dataset; // Assume dataset is properly formatted as an object of arrays + + if (claimId && !forceNewClaimId) { + this.claimId = claimId; + } else { + console.log("datasetArray before getnextId", grindem(dataset)); + console.log("existing ids check", getExistingIds("claim", dataset)); + this.claimId = getNextId("claim", dataset); + console.log("claim Id after getnextId", this.claimId); + } + console.log("Initialized Claim ID:", this.claimId); + this.personId = this.findOrAssignPersonId(dataset); + this.policyId = getPolicyOfClaim(this.claimId, dataset) || getFirstOrNextId("policy", dataset); +} + + +private findOrAssignPersonId(dataset: Dataset): string { + return getFirstOrNextId("person", dataset); + } + + public refreshClaimId(): void { + this.claimId = getNextId("claim", this.dataset); // Force new claim ID + } + + public epilogToFormValues(epilogDataset: Dataset, claimId?: string): FormValues { + console.log("datasetAtStartOfEpilogToFormValues", epilogDataset); + if (this.claimId) { + const claimExists = (compfinds("X", read(`claim(${claimId})`), epilogDataset, []) as string[]).length > 0; + if (!claimExists) { + console.debug("Claim ID not found in dataset, generating new ID"); + claimId = undefined; + } + } + + console.log("currentClaimId in epilogToFormValues", this.claimId); + + this.claimId = claimId || getNextId("claim", epilogDataset); + + console.log("currentClaimId in epilogToFormValues after recalling this.claimID", this.claimId); + + + let [personId] = compfinds("X", read(`claim.claimant(${this.claimId}, X)`), epilogDataset, []) as string[]; + if (!personId) personId = getFirstOrNextId("person", epilogDataset); + console.log("personIdInEpilogToFormValues", personId); + + let [dobString] = compfinds("X", read(`person.dob(${personId}, X)`), epilogDataset, []) as string[]; + const dob = dobString && dobString !== "nil" ? stringToDate(dobString) : null; + console.log("dobInEpilogToFormAdapter", dob); + + //let [isPersonImmunocompromised] = compfinds("X", read(`person.immunocompromised(${personId}, X)`), epilogDataset, []) as string[]; + + let policyId = getPolicyOfClaim(this.claimId, epilogDataset); + if (!policyId) policyId = getFirstOrNextId("policy", epilogDataset); + + const formConfig: FormConfig | undefined = configs[this.policyType]; + console.log("formConfig", formConfig); + if (!formConfig) { + throw new Error(`Form configuration not found for policy type '${this.policyType}'`); + } + + const fields = formConfig.fields; + console.log("fieldsInFormConfigs", fields); + + //console.log("isPersonImmunocompromisedInEpilogToFormValues", isPersonImmunocompromised); + + let formValues: FormValues = { + person: { id: personId, label: personId }, + policy: { id: policyId, label: policyId }, + claim: { id: this.claimId, label: this.claimId }, + dob: dob, + // isPersonImmunocompromised: isPersonImmunocompromised ? { id: isPersonImmunocompromised, label: isPersonImmunocompromised } : null + }; + + console.log('formValuesBeforeForEachLoop', formValues); + + fields.forEach(field => { + console.log("field.id", field.id); + const mapping = field.mapping + console.log("mapping", mapping); + const mapping_array = mapping.split("."); + console.log("mapping_array", mapping_array); + const mapping_label = mapping_array[1]; + let value = null; + let compfinds_value = null; + + if(field.type === "date") { + console.log("epilogDataset", epilogDataset); + const [dateTimeResult] = compfinds( + read("time(Date, Time)"), // ["time", "24_05_13", "22_50"] + read(`claim.time(${this.claimId}, Date, Time)`), + epilogDataset, + [], + ) as [string, string, string][]; + + console.log("dateTimeResult", dateTimeResult); + + value = dateTimeResult?.length === 3 && dateTimeResult[1] !== "nil" && dateTimeResult[2] !== "nil" + ? stringToDate(dateTimeResult[1], dateTimeResult[2]) + : null; + console.log("value after being converted", value); + + } + else { + const mapping_type = mapping_array[0]; + let value_compfinds = null + console.log("mapping type", mapping_type); + if (mapping_type == "person") { + let results = compfinds( + "X", + read(`person.${mapping_label}(${personId}, X)`), + epilogDataset, [] + ); + value_compfinds = results.length > 0 ? results[0] : "null"; + console.log("value_compfinds in person", value_compfinds); + } + if (mapping_type == "claim") { + console.log("enter claim mapping type"); + console.log("mapping_label", mapping_label); + let results = compfinds( + "X", + read(`claim.${mapping_label}(${claimId}, X)`), + epilogDataset, + [], + ); + value_compfinds = results.length > 0 ? results[0] : "null"; + console.log("value_compfinds in brackets", value_compfinds); + } + console.log("value_compfinds outside of brackets", value_compfinds); + value = { id: field.id, label: value_compfinds }; + console.log("value after set in else clause", value); + } + console.log('what is being added - formValues[field.id], value', formValues[field.id], value); + formValues[field.id] = value; + console.log("formValues[field.id] after being set", formValues[field.id]); + }); + + console.log("Form Values on Initialization with New Claim ID:", formValues); + return formValues; + } + + + + public formValuesToEpilog(values: FormValues): string[][] { + const formConfig: FormConfig | undefined = configs[this.policyType]; + if (!formConfig) { + throw new Error(`Form configuration not found for policy type '${this.policyType}'`); + } + + const personId = values.person.id; + const dob = dateToString(values.dob); + const isPersonImmunocompromised = + values.isPersonImmunocompromised?.id || "nil"; + + /* --------------------------------- Policy --------------------------------- */ + + const policyId = values.policy.id; + const policyType = values.policyType?.id || "nil"; + const fields = formConfig.fields; + + const claimId = values.claim.id; + let epilogString = `person(${personId})`; + + epilogString += `policy(${policyId})`; + epilogString += `claim(${claimId})`; + epilogString += `person.occupation(${personId}, other)`; + epilogString += `policy.type(${policyId}, ${policyType})`; + epilogString += `policy.insuree(${policyId}, ${personId})`; + epilogString += `policy.startdate(${policyId}, ${personId}, 01_08_2023)`; + epilogString += `policy.enddate(${policyId}, ${personId}, 30_06_2024)`; + epilogString += `claim.policy(${claimId}, ${policyId})`; + + console.log("formEpilogString after first adding something", epilogString); + + console.log("VALUESbeforeFIELDS", values); + console.log("fields", fields); + + + fields.forEach(field => { + let value = values[field.id]; + const mapping = field.mapping + console.log("mapping", mapping); + const mapping_array = mapping.split("."); + console.log("mapping_array", mapping_array); + + switch (field.type) { + case 'date': + console.log("entered date case", value); + const whenDate = value; + const whenDateStr = dateToString(whenDate); + const whenTimeStr = timeOfDateToString(whenDate); + console.log("entered date case", value, field.type); + value = value instanceof Date ? dateToString(value) : (value ? timeOfDateToString(value) : "nil"); + console.log("valueAfterSetting", value); + epilogString += `${field.mapping}(${claimId}, ${whenDateStr}, ${whenTimeStr})\n`; + break; + case 'select': + console.log("entered select case", value); + if (Array.isArray(value) ? value.length > 0 : value && (value.label || value.value)) { + console.log("valueInSelectCase", value); + let selectedValue = Array.isArray(value) ? value[0] : value; + let key_search = selectedValue.value ? "value" : "label"; + value = selectedValue[key_search]; + console.log("selected value:", value); + const mapping_type = mapping_array[0]; + if (mapping_type == "person") { + epilogString += `${field.mapping}(${personId}, ${value})\n`; + console.log("addedPersonSelectType", epilogString); + } + if (mapping_type == "claim") { + epilogString += `${field.mapping}(${claimId}, ${value})\n`; + console.log("addedClaimSelectType", epilogString); + } + if (mapping_type == "policy") { + epilogString += `${field.mapping}(${policyId}, ${value})\n`; + console.log("addedPolicySelectType", epilogString); + } + } else { + value = "nil" + } + break; + case 'array': + console.log("entered array case", value, field.type); + value = (value.id || value); + console.log("valIdExists", (value.id || value)); + if (value.length > 0) { + console.log("enters val exist case", field.label); + if (field.label == "Vaccination History") { + console.log("enters Vaccination History field.label", field.label); + const getCount = ( + typesArray: BasicOption[] | any, // Updated type to include any to handle different types + vaccine: "pfizer" | "moderna" | "other" | "new_formulation", + ) => { + if (!Array.isArray(typesArray)) { + console.error("Expected typesArray to be an array, received:", typesArray); + return 0; // Return 0 or handle the error appropriately + } + return typesArray.filter((v) => v.id === vaccine).length; + }; + + const vaccinationHistory_vaccineTypes_pfizer = getCount( + values.vaccinationHistory_vaccineTypes, + "pfizer", + ); + + const vaccinationHistory_vaccineTypes_moderna = getCount( + values.vaccinationHistory_vaccineTypes, + "moderna", + ); + const vaccinationHistory_vaccineTypes_other = getCount( + values.vaccinationHistory_vaccineTypes, + "other", + ); + + const vaccinationHistory_vaccineTypes_new_formulation = getCount( + values.vaccinationHistory_vaccineTypes, + "new_formulation", + ); + + epilogString += `claim.vaccine_dose_count(${claimId}, ${vaccinationHistory_vaccineTypes_new_formulation})\n`; + epilogString += `claim.previous_vaccines_pfizer(${claimId}, ${vaccinationHistory_vaccineTypes_pfizer})\n`; + epilogString += `claim.previous_vaccines_moderna(${claimId}, ${vaccinationHistory_vaccineTypes_moderna})\n`; + epilogString += `claim.previous_vaccines_other(${claimId}, ${vaccinationHistory_vaccineTypes_other})\n`; + + } else { + value = value.map(item => item.id || "nil").join(", ") + epilogString += `${field.mapping}(${claimId}, ${value})\n`; + } + } else { + value = "nil"; + } + //value = (value && value.length > 0) ? value.map(item => item.id || "nil").join(", ") : "nil"; + //console.log("valueAfterSetting", value); + //epilogString += `${field.mapping}(${this.claimId}, ${value})\n`; + break; + case 'text': + case 'number': + case 'checkbox': + console.log("entered checkbox case", value, field.type); + value = (value !== null && value !== undefined) ? value.toString() : "nil"; + console.log("valueAfterSetting", value); + epilogString += `${field.mapping}(${claimId}, ${value})\n`; + break; + default: + console.log("entered nil case", value, field.type); + value = "nil"; + epilogString += `${field.mapping}(${claimId}, ${value})\n`; + } + }); + + console.log("epilogStringAfterAddingEverything", epilogString); + + + const formDataset = readdata(epilogString); + console.log("Parsed Dataset:", formDataset); + + + return formDataset; +} +} + +export default GeneralFormAdapter; diff --git a/apps/react/src/epilog/plain-js/epilog.js b/apps/react/src/epilog/plain-js/epilog.js index 973fd1b..f804a9a 100644 --- a/apps/react/src/epilog/plain-js/epilog.js +++ b/apps/react/src/epilog/plain-js/epilog.js @@ -1,5 +1,6 @@ //============================================================================== -// Epilog //============================================================================== +// Epilog +//============================================================================== // Copyright (c) 2020 The Board of Trustees of the Leland Stanford Junior // University. All nonprofit research institutions may use this Software for // any non-profit purpose, including sponsored research and collaboration. All @@ -21,104 +22,593 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================== -// Sentential Representation //============================================================================== - function symbolp (x) {return typeof x==='string'} function varp (x) {return (typeof(x)==='string' && x.length!==0 && - (x.charCodeAt(0)===95 || x[0]!==x[0].toLowerCase()))} - function constantp (x) {return typeof x==='string' && x.length!==0 && x[0]===x[0].toLowerCase()} function numberp (x) +// Sentential Representation +//============================================================================== + +function symbolp (x) + {return typeof x==='string'} + +function varp (x) + {return (typeof(x)==='string' && x.length!==0 && + (x.charCodeAt(0)===95 || x[0]!==x[0].toLowerCase()))} + +function constantp (x) + {return typeof x==='string' && x.length!==0 && x[0]===x[0].toLowerCase()} + +function numberp (x) {return !isNaN(Number(x))} - function stringp (x) {return typeof x==='string' && x.length>1 && x[0]==='"' && x[x.length-1]==='"'} var counter = 0 function newvar () {counter++; return 'V' + counter} function newsym () {counter++; return 'c' + counter} function seq () {var exp=new Array(arguments.length); for (var i=0; i1 && x[0]==='"' && x[x.length-1]==='"'} + +var counter = 0 + +function newvar () + {counter++; return 'V' + counter} + +function newsym () + {counter++; return 'c' + counter} + +function seq () + {var exp=new Array(arguments.length); + for (var i=0; i 0) {return pseudogroundp(dum[0],dum[1])}; + return false}; + if (symbolp(exp)) {return true}; + for (var i=0; i 0) {return pseudogroundp(dum[0],dum[1])}; return false}; if (symbolp(exp)) {return true}; for (var i=0; i0; i--) {exp=cons(arguments[i-1],exp)}; return exp} function len (l) {var n = 0; for (var m=l; m!==nil; m = cdr(m)) {n = n+1}; return n} function memberp (x,l) {if (nullp(l)) {return false}; if (equalp(car(l),x)) {return true}; if (memberp(x,cdr(l))) {return true}; return false} + +function list () + {var exp=nil; + for (var i=arguments.length; i>0; i--) + {exp=cons(arguments[i-1],exp)}; + return exp} + +function len (l) + {var n = 0; + for (var m=l; m!==nil; m = cdr(m)) {n = n+1}; + return n} + +function memberp (x,l) + {if (nullp(l)) {return false}; + if (equalp(car(l),x)) {return true}; + if (memberp(x,cdr(l))) {return true}; + return false} function amongp (x,y) {if (symbolp(y)) {return x==y}; for (var i=0; i 0) {return maatchify(dum[0],dum[1],y,bl,ol)}; ol.push(setbdg(x,al,y,bl)); return true} function maatchexp(x,al,y,bl,ol) {if (symbolp(y)) {return false}; var m = x.length; var n = y.length; if (m!==n) {return false}; for (var i=0; i 0) {return vnify(dum[0],dum[1],y,bl,ol)}; if (vident(x,al,y,bl)) {return true}; if (occurcheck && vccurs(x,al,y,bl)) {return false}; ol.push(setbdg(x,al,y,bl)); return true} +function standardizeit (x) + {if (varp(x)) {return standardizevar(x)}; + if (symbolp(x)) {return x}; + return standardizeexp(x)} + +function standardizevar (x) + {var dum = assoc(x,alist); + if (dum!==false) {return cdr(dum)}; + var rep = newvar(); + alist = acons(x,rep,alist); + return rep} + +function standardizeexp (x) + {var exp = new Array(x.length); + for (var i=0; i 0) {return maatchify(dum[0],dum[1],y,bl,ol)}; + ol.push(setbdg(x,al,y,bl)); + return true} + +function maatchexp(x,al,y,bl,ol) + {if (symbolp(y)) {return false}; + var m = x.length; + var n = y.length; + if (m!==n) {return false}; + for (var i=0; i 0) {return vnify(dum[0],dum[1],y,bl,ol)}; + if (vident(x,al,y,bl)) {return true}; + if (occurcheck && vccurs(x,al,y,bl)) {return false}; + ol.push(setbdg(x,al,y,bl)); + return true} function vident (x,al,y,bl) - {if (x===y && al===bl) {return true}; if (varp(y)) - {var dum = bl[y]; if (dum && dum.length > 0) {return vident(x,al,dum[0],dum[1])}}; + {if (x===y && al===bl) {return true}; + if (varp(y)) + {var dum = bl[y]; + if (dum && dum.length > 0) {return vident(x,al,dum[0],dum[1])}}; return false} - function vccurs (x,al,y,bl) + +function vccurs (x,al,y,bl) {if (varp(y)) - {if (x===y && al===bl) {return true}; var dum = bl[y]; if (dum && dum.length > 0) {return vccurs(x,al,dum[0],dum[1])}; - return false}; + {if (x===y && al===bl) {return true}; + var dum = bl[y]; + if (dum && dum.length > 0) {return vccurs(x,al,dum[0],dum[1])}; + return false}; if (symbolp(y)) {return false}; - for (var i=0; i 0) {return pluug(dum[0],dum[1],bl)}; if (al===bl) {return x}; var rep = newvar(); al[x] = seq(rep,bl); return rep}; + return pluugexp(x,al,bl)} + +function pluugvar (x,al,bl) + {var dum = al[x]; + if (dum && dum.length > 0) {return pluug(dum[0],dum[1],bl)}; + if (al===bl) {return x}; + var rep = newvar(); + al[x] = seq(rep,bl); + return rep}; function pluugquantifier (x,al,bl) {var result = seq('setofall',x[1]); for (var i=2; i0) {return fullvndexps(dum[0],dum[1],facts)}; + return facts}; + if (symbolp(p)) {return indexees(p,facts)}; + var best = indexees(p[0],facts); + for (var i=1; i0) {return fullvndexps(dum[0],dum[1],facts)}; - return facts}; if (symbolp(p)) {return indexees(p,facts)}; - var best = indexees(p[0],facts); for (var i=1; i0) {return basevndexps(dum[0],dum[1],theory)}; - return false}; if (symbolp(p)) {return baseindexees(p,theory)}; - var best = baseindexees(p[0],theory); for (var i=1; i0) {return basevndexps(dum[0],dum[1],theory)}; + return false}; + if (symbolp(p)) {return baseindexees(p,theory)}; + var best = baseindexees(p[0],theory); + for (var i=1; i=n) {return results.slice(m,n)}; if (results.length>=m) {return results.slice(m)}; return seq()} -function viewfacts (relation,facts,rules) {var pattern = makepattern(relation,getrulearity(relation,rules)); +function viewfacts (relation,facts,rules) + {var pattern = makepattern(relation,getrulearity(relation,rules)); return sortfinds(pattern,pattern,facts,rules)} //============================================================================== // Accessing datasets without inference // base always indexed -// data depends on dataindexing //============================================================================== +// data depends on dataindexing +//============================================================================== function baseanswerx (query,al,facts,rules) {var data = basevndexps(query,al,facts); @@ -321,7 +1099,8 @@ function baseanswers (query,al,facts,rules) backup(ol)}}; return answers} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + function dataanswerx (query,al,facts,rules) {var data = dataindexing ? fullvndexps(query,al,facts) : facts; var answers = []; @@ -343,7 +1122,8 @@ function dataanswers (query,al,facts,rules) backup(ol)}}; return answers} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + function companswerx (query,al,facts,rules) {var arg = pluug(query[1],al,al); var val = compvalue(arg,facts,rules); @@ -365,11 +1145,30 @@ function companswers (query,al,facts,rules) return false} //============================================================================== -// Inference without built-in relations //============================================================================== -//------------------------------------------------------------------------------ // basefindp // basefindx // basefinds // basefindn // basefindg // basevalue //------------------------------------------------------------------------------ var inferences = 0; var instantiations = 0; function basefindp (query,facts,rules) {return (basefindx('true',query,facts,rules)==='true')} function basefindx (result,query,facts,rules) {var answers = basefindn(1,result,query,facts,rules); +// Inference without built-in relations +//============================================================================== +//------------------------------------------------------------------------------ +// basefindp +// basefindx +// basefinds +// basefindn +// basefindg +// basevalue +//------------------------------------------------------------------------------ + +var inferences = 0; +var instantiations = 0; + +function basefindp (query,facts,rules) + {return (basefindx('true',query,facts,rules)==='true')} + +function basefindx (result,query,facts,rules) + {var answers = basefindn(1,result,query,facts,rules); if (answers.length>0) {return answers[0]}; - return false} -function basefinds (result,query,facts,rules) {return zniquify(basefindn(true,result,query,facts,rules))} + return false} + +function basefinds (result,query,facts,rules) + {return zniquify(basefindn(true,result,query,facts,rules))} function basefindn (n,result,query,facts,rules) {var results = []; @@ -378,46 +1177,108 @@ function basefindn (n,result,query,facts,rules) return results} function basefindg (result,query,facts,rules) - {return compgen(result,query,facts,rules)} - -//------------------------------------------------------------------------------ function basesome (n,x,p,pl,al,cont,results,facts,rules) {inferences = inferences + 1; if (symbolp(p)) - {return basesomeatom(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='same') - {return basesomesame(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='distinct') - {return basesomedistinct(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='not') - {return basesomenot(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='and') - {return basesomeand(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='or') + {return compgen(result,query,facts,rules)} + +//------------------------------------------------------------------------------ + +function basesome (n,x,p,pl,al,cont,results,facts,rules) + {inferences = inferences + 1; + if (symbolp(p)) + {return basesomeatom(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='same') + {return basesomesame(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='distinct') + {return basesomedistinct(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='not') + {return basesomenot(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='and') + {return basesomeand(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='or') {return basesomeor(n,x,p,pl,al,cont,results,facts,rules)}; if (basep(p[0],rules)) - {return basesomebase(n,x,p,pl,al,cont,results,facts,rules)}; return basesomeview(n,x,p,pl,al,cont,results,facts,rules)} - function basesomeatom (n,x,p,pl,al,cont,results,facts,rules) {if (p==='true') {return basesomeexit(n,x,pl,al,cont,results,facts,rules)}; if (p==='false') {return false}; + {return basesomebase(n,x,p,pl,al,cont,results,facts,rules)}; + return basesomeview(n,x,p,pl,al,cont,results,facts,rules)} + +function basesomeatom (n,x,p,pl,al,cont,results,facts,rules) + {if (p==='true') {return basesomeexit(n,x,pl,al,cont,results,facts,rules)}; + if (p==='false') {return false}; if (basep(p,rules)) - {return basesomebase(n,x,p,pl,al,cont,results,facts,rules)}; return basesomeground(n,x,p,pl,al,cont,results,facts,rules)} - function basesomesame (n,x,p,pl,al,cont,results,facts,rules) {var ol = seq(); - if (vnifyp(p[1],al,p[2],al,ol)) {var answer = basesomeexit(n,x,pl,al,cont,results,facts,rules); + {return basesomebase(n,x,p,pl,al,cont,results,facts,rules)}; + return basesomeground(n,x,p,pl,al,cont,results,facts,rules)} + +function basesomesame (n,x,p,pl,al,cont,results,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) + {var answer = basesomeexit(n,x,pl,al,cont,results,facts,rules); backup(ol); return answer}; - return false} function basesomedistinct (n,x,p,pl,al,cont,results,facts,rules) {var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; return basesomeexit(n,x,pl,al,cont,results,facts,rules)} function basesomenot (n,x,p,pl,al,cont,results,facts,rules) {if (basesome(1,x,p[1],seq(),al,nil,[],facts,rules)===false) + return false} + +function basesomedistinct (n,x,p,pl,al,cont,results,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; + return basesomeexit(n,x,pl,al,cont,results,facts,rules)} + +function basesomenot (n,x,p,pl,al,cont,results,facts,rules) + {if (basesome(1,x,p[1],seq(),al,nil,[],facts,rules)===false) {return basesomeexit(n,x,pl,al,cont,results,facts,rules)}; - return false} function basesomeand (n,x,p,pl,al,cont,results,facts,rules) {return basesomeexit(n,x,concatenate(tail(p),pl),al,cont,results,facts,rules)} function basesomeor (n,x,p,pl,al,cont,results,facts,rules) {var answer; - for (var i=1; i=n) {return results}; - return false}; return basesomeexit(n,x,cont[0],cont[1],cont[2],results,facts,rules)} + return false}; + return basesomeexit(n,x,cont[0],cont[1],cont[2],results,facts,rules)} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function basevalue (p,facts,rules) {if (varp(p)) {return false}; @@ -430,11 +1291,14 @@ function basevalue (p,facts,rules) if (arg!==false) {args[i-1] = arg} else {return false}}; return baseapply(p[0],args,facts,rules)} -function basevaluesetofall (p,facts,rules) {return listify(basefinds(p[1],p[2],facts,rules))} +function basevaluesetofall (p,facts,rules) + {return listify(basefinds(p[1],p[2],facts,rules))} -function basevaluecountofall (p,facts,rules) {return basefinds(p[1],p[2],facts,rules).length.toString()} +function basevaluecountofall (p,facts,rules) + {return basefinds(p[1],p[2],facts,rules).length.toString()} -function basevaluechoose (p,facts,rules) {var possibilities = basefinds(p[1],p[2],facts,rules); +function basevaluechoose (p,facts,rules) + {var possibilities = basefinds(p[1],p[2],facts,rules); var n = Math.floor(Math.random()*possibilities.length); return possibilities[n]} @@ -450,9 +1314,11 @@ function baseapply (fun,args,facts,rules) function baseapplybuiltin (fun,args,facts,rules) {return eval(fun).apply(null,args)} -function baseapplymath (fun,args,facts,rules) {return stringize(Math[fun].apply(null,args))} +function baseapplymath (fun,args,facts,rules) + {return stringize(Math[fun].apply(null,args))} -function baseapplylist (fun,args,facts,rules) {var args = numlistify(args[0]); +function baseapplylist (fun,args,facts,rules) + {var args = numlistify(args[0]); return stringize(eval(fun).call(null,args))} function baseapplyrs (fun,args,facts,rules) @@ -460,9 +1326,13 @@ function baseapplyrs (fun,args,facts,rules) //var data = indexees('definition',rules); var data = lookuprules(fun,rules); var flag = false; - for (var i=0; i0) {return answers[0]}; - return false} -function compfinds (result,query,facts,rules) {return zniquify(compfindn(true,result,query,facts,rules))} + return false} + +function compfinds (result,query,facts,rules) + {return zniquify(compfindn(true,result,query,facts,rules))} function compfindn (n,result,query,facts,rules) {var results = []; @@ -486,46 +1372,78 @@ function compfindn (n,result,query,facts,rules) function compfindg (result,query,facts,rules) {return compgen(result,query,facts,rules)} -function sortfinds (result,query,facts,rules) {return vniquify(compfindn(true,result,query,facts,rules))} +function sortfinds (result,query,facts,rules) + {return vniquify(compfindn(true,result,query,facts,rules))} -//------------------------------------------------------------------------------ function compsome (n,x,p,pl,al,cont,results,facts,rules) {//inferences = inferences + 1; var answer = false; +//------------------------------------------------------------------------------ + +function compsome (n,x,p,pl,al,cont,results,facts,rules) + {//inferences = inferences + 1; + var answer = false; if (symbolp(p)) - {return compsomeatom(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='same') - {return compsomesame(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='distinct') - {return compsomedistinct(n,x,p,pl,al,cont,results,facts,rules)} if (specialp(p[0])) - {return compsomeeval(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='matches') - {return compsomematches(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='submatches') + {return compsomeatom(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='same') + {return compsomesame(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='distinct') + {return compsomedistinct(n,x,p,pl,al,cont,results,facts,rules)} + if (specialp(p[0])) + {return compsomeeval(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='matches') + {return compsomematches(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='submatches') {return compsomesubmatches(n,x,p,pl,al,cont,results,facts,rules)} if (builtinp(p[0])) - {return compsomecall(n,x,p,pl,al,cont,results,facts,rules)} if (mathp(p[0])) + {return compsomecall(n,x,p,pl,al,cont,results,facts,rules)} + if (mathp(p[0])) {return compsomemath(n,x,p,pl,al,cont,results,facts,rules)} if (listop(p[0])) - {return compsomelist(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='map') - {return compsomemap(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='setofall') - {return compsomesetofall(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='countofall') - {return compsomecountofall(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='evaluate') - {return compsomeevaluate(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='member') - {return compsomemember(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='not') - {return compsomenot(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='and') - {return compsomeand(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='or') - {return compsomeor(n,x,p,pl,al,cont,results,facts,rules)} if (p[0]==='true') + {return compsomelist(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='map') + {return compsomemap(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='setofall') + {return compsomesetofall(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='countofall') + {return compsomecountofall(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='evaluate') + {return compsomeevaluate(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='member') + {return compsomemember(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='not') + {return compsomenot(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='and') + {return compsomeand(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='or') + {return compsomeor(n,x,p,pl,al,cont,results,facts,rules)} + if (p[0]==='true') {return compsometrue(n,x,p,pl,al,cont,results,facts,rules)} if (basep(p[0],rules)) {return compsomebase(n,x,p,pl,al,cont,results,facts,rules)}; return compsomeview(n,x,p,pl,al,cont,results,facts,rules)} -function compsomeatom (n,x,p,pl,al,cont,results,facts,rules) {if (p==='true') - {return compsomeexit(n,x,pl,al,cont,results,facts,rules)}; if (p==='false') +function compsomeatom (n,x,p,pl,al,cont,results,facts,rules) + {if (p==='true') + {return compsomeexit(n,x,pl,al,cont,results,facts,rules)}; + if (p==='false') {return false}; if (basep(p,rules)) {return compsomebase(n,x,p,pl,al,cont,results,facts,rules)}; - return compsomeground(n,x,p,pl,al,cont,results,facts,rules)} function compsomesame (n,x,p,pl,al,cont,results,facts,rules) {var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) + return compsomeground(n,x,p,pl,al,cont,results,facts,rules)} + +function compsomesame (n,x,p,pl,al,cont,results,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {var answer = compsomeexit(n,x,pl,al,cont,results,facts,rules); backup(ol); return answer}; - return false} function compsomedistinct (n,x,p,pl,al,cont,results,facts,rules) {var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; return compsomeexit(n,x,pl,al,cont,results,facts,rules)} + return false} -function compsomematches (n,x,p,pl,al,cont,results,facts,rules) {var str = pluug(p[1],al,al); +function compsomedistinct (n,x,p,pl,al,cont,results,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; + return compsomeexit(n,x,pl,al,cont,results,facts,rules)} + +function compsomematches (n,x,p,pl,al,cont,results,facts,rules) + {var str = pluug(p[1],al,al); if (!stringp(str)) {return false}; str = str.substring(1,str.length-1); var pat = pluug(p[2],al,al); @@ -533,29 +1451,46 @@ function compsomematches (n,x,p,pl,al,cont,results,facts,rules) {var str = pluu pat = pat.substring(1,pat.length-1); var re=new RegExp(pat,'g'); var fragments = re.exec(str); - if (fragments!=null) {var ol = seq(); - for (var i=3; i=n) {return results}; - return false}; return compsomeexit(n,x,cont[0],cont[1],cont[2],results,facts,rules)} //------------------------------------------------------------------------------ // compgen -//------------------------------------------------------------------------------ + return false}; + return compsomeexit(n,x,cont[0],cont[1],cont[2],results,facts,rules)} + +//------------------------------------------------------------------------------ +// compgen +//------------------------------------------------------------------------------ + function compgen (x,p,facts,rules) {var type = gettype(p,rules); var al = {}; @@ -682,7 +1669,7 @@ function compgen (x,p,facts,rules) toplevel.alist = al; return makeframe(type,p,al,facts,rules,'call',toplevel)} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function compvalue (p,facts,rules) {if (varp(p)) {return false}; @@ -698,7 +1685,8 @@ function compvalue (p,facts,rules) if (arg!==false) {args[i-1] = arg} else {return false}}; return compapply(p[0],args,facts,rules)} -function compvaluemap (p,facts,rules) {var fun = compvalue(p[1],facts,rules); +function compvaluemap (p,facts,rules) + {var fun = compvalue(p[1],facts,rules); var arglist = compvalue(p[2],facts,rules); return compval(fun,arglist,facts,rules)} @@ -711,11 +1699,14 @@ function compval (fun,arglist,facts,rules) if (results===false) {return false}; return seq('cons',result,results)} -function compvaluesetofall (p,facts,rules) {return listify(compfinds(p[1],p[2],facts,rules))} +function compvaluesetofall (p,facts,rules) + {return listify(compfinds(p[1],p[2],facts,rules))} -function compvaluecountofall (p,facts,rules) {return compfinds(p[1],p[2],facts,rules).length.toString()} +function compvaluecountofall (p,facts,rules) + {return compfinds(p[1],p[2],facts,rules).length.toString()} -function compvaluechoose (p,facts,rules) {var possibilities = compfinds(p[1],p[2],facts,rules); +function compvaluechoose (p,facts,rules) + {var possibilities = compfinds(p[1],p[2],facts,rules); if (possibilities.length===0) {return false}; var n = Math.floor(Math.random()*possibilities.length); return possibilities[n]} @@ -735,9 +1726,11 @@ function compapply (fun,args,facts,rules) function compapplybuiltin (fun,args,facts,rules) {return eval(fun).apply(null,args)} -function compapplymath (fun,args,facts,rules) {return stringize(Math[fun].apply(null,args))} +function compapplymath (fun,args,facts,rules) + {return stringize(Math[fun].apply(null,args))} -function compapplylist (fun,args,facts,rules) {var args = numlistify(args[0]); +function compapplylist (fun,args,facts,rules) + {var args = numlistify(args[0]); return stringize(eval(fun).call(null,args))} function compapplyrs (fun,args,facts,rules) @@ -745,9 +1738,13 @@ function compapplyrs (fun,args,facts,rules) //var data = indexees('definition',rules); var data = lookuprules(fun,rules); var flag = false; - for (var i=0; i0) {return answers[0]}; - return false} + return false} + function heapfinds (result,query,facts,rules) {return zniquify(calls(heapgen(result,query,facts,rules)))} @@ -957,7 +1958,9 @@ function makeframe (type,p,al,facts,rules,task,caller) frame.caller = caller; return frame} -//------------------------------------------------------------------------------ var framelimit = 100000; +//------------------------------------------------------------------------------ + +var framelimit = 100000; function callx (gen) {return call(gen)} @@ -983,7 +1986,7 @@ function calls (gen) if (!(ind in resultmap)) {results.push(answer); resultmap[ind] = 1}} return results} - + function call (frame) {if (frame.caller.task) {frame.task = 'redo'}; return loop(frame)} @@ -999,7 +2002,9 @@ function loop (frame) return false}; frame = processframe(frame)}} -//------------------------------------------------------------------------------ function processframe (frame) +//------------------------------------------------------------------------------ + +function processframe (frame) {var task = frame.task; if (task==='call') {return callframe(frame)}; if (task==='redo') {return redoframe(frame)}; @@ -1057,7 +2062,7 @@ function backframe (frame) if (frame.type==='rule') {return backrule(frame)}; return false} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callatom (frame) {var query = frame.query; @@ -1082,7 +2087,7 @@ function backatom (frame) {frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callsame (frame) {var query = frame.query; @@ -1101,7 +2106,7 @@ function redosame (frame) frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function calldistinct (frame) {var query = frame.query; @@ -1118,7 +2123,7 @@ function redodistinct (frame) {frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function calleval (frame) {var query = frame.query; @@ -1138,7 +2143,7 @@ function redoeval (frame) {frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callevaluation (frame) {var query = frame.query; @@ -1160,7 +2165,7 @@ function redoevaluation (frame) frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callmember (frame) {var query = frame.query; @@ -1183,10 +2188,11 @@ function redomember (frame) frame.caller.task = 'next'; return frame.caller}; list = list[2]}; - frame.list = list; frame.caller.task = 'back'; + frame.list = list; + frame.caller.task = 'back'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callnegation (frame) {var query = frame.query; @@ -1209,7 +2215,7 @@ function backnegation (frame) {frame.caller.task = 'next'; return frame.caller} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callconjunction (frame) {frame.index = 0; @@ -1252,7 +2258,7 @@ function backconjunction (frame) frame.generators[index].task = 'redo'; return frame.generators[index]} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function calldisjunction (frame) {var query = frame.query; @@ -1293,7 +2299,7 @@ function backdisjunction (frame) frame.generator = subframe; return subframe} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function callbase (frame) {var query = frame.query; @@ -1311,8 +2317,10 @@ function redobase (frame) var index = frame.index; var ol = frame.ol; backup(ol); - while (index0) {return answers[0]}; - return false} -function hypofinds (result,query,adds,dels,facts,rules) {return zniquify(hypofindn(true,result,query,adds,dels,facts,rules))} + return false} + +function hypofinds (result,query,adds,dels,facts,rules) + {return zniquify(hypofindn(true,result,query,adds,dels,facts,rules))} function hypofindn (n,result,query,adds,dels,facts,rules) {var results = []; @@ -1528,44 +2562,75 @@ function hypofindn (n,result,query,adds,dels,facts,rules) hyposome(n,result,query,seq(),{},nil,results,adds,dels,facts,rules); return results} -//------------------------------------------------------------------------------ function hyposome (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {inferences = inferences + 1; var answer = false; +//------------------------------------------------------------------------------ + +function hyposome (n,x,p,pl,al,cont,results,adds,dels,facts,rules) + {inferences = inferences + 1; + var answer = false; if (symbolp(p)) - {return hyposomeatom(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='same') - {return hyposomesame(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='distinct') - {return hyposomedistinct(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='matches') - {return hyposomematches(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='submatches') + {return hyposomeatom(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='same') + {return hyposomesame(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='distinct') + {return hyposomedistinct(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='matches') + {return hyposomematches(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='submatches') {return hyposomesubmatches(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (specialp(p[0])) - {return hyposomeeval(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (builtinp(p[0])) - {return hyposomecall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (mathp(p[0])) + {return hyposomeeval(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (builtinp(p[0])) + {return hyposomecall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (mathp(p[0])) {return hyposomemath(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (listop(p[0])) - {return hyposomelist(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='map') - {return hyposomemap(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='setofall') - {return hyposomesetofall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='countofall') - {return hyposomecountofall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='evaluate') - {return hyposomeevaluate(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='member') - {return hyposomemember(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='not') - {return hyposomenot(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='and') - {return hyposomeand(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='or') - {return hyposomeor(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (p[0]==='true') + {return hyposomelist(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='map') + {return hyposomemap(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='setofall') + {return hyposomesetofall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='countofall') + {return hyposomecountofall(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='evaluate') + {return hyposomeevaluate(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='member') + {return hyposomemember(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='not') + {return hyposomenot(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='and') + {return hyposomeand(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='or') + {return hyposomeor(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + if (p[0]==='true') {return hyposometrue(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} if (basep(p[0],rules)) {return hyposomebase(n,x,p,pl,al,cont,results,adds,dels,facts,rules)}; return hyposomeview(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} -function hyposomeatom (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {if (p==='true') - {return hyposomeexit(n,x,pl,al,cont,results,adds,dels,facts,rules)}; if (p==='false') +function hyposomeatom (n,x,p,pl,al,cont,results,adds,dels,facts,rules) + {if (p==='true') + {return hyposomeexit(n,x,pl,al,cont,results,adds,dels,facts,rules)}; + if (p==='false') {return false}; if (basep(p,rules)) {return hyposomebase(n,x,p,pl,al,cont,results,adds,dels,facts,rules)}; - return hyposomeground(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} function hyposomesame (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) + return hyposomeground(n,x,p,pl,al,cont,results,adds,dels,facts,rules)} + +function hyposomesame (n,x,p,pl,al,cont,results,adds,dels,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {var answer = hyposomeexit(n,x,pl,al,cont,results,adds,dels,facts,rules); backup(ol); return answer}; - return false} function hyposomedistinct (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; return hyposomeexit(n,x,pl,al,cont,results,adds,dels,facts,rules)} + return false} -function hyposomematches (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {var str = pluug(p[1],al,al); +function hyposomedistinct (n,x,p,pl,al,cont,results,adds,dels,facts,rules) + {var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); return false}; + return hyposomeexit(n,x,pl,al,cont,results,adds,dels,facts,rules)} + +function hyposomematches (n,x,p,pl,al,cont,results,adds,dels,facts,rules) + {var str = pluug(p[1],al,al); if (!stringp(str)) {return false}; str = str.substring(1,str.length-1); var pat = pluug(p[2],al,al); @@ -1573,30 +2638,46 @@ function hyposomematches (n,x,p,pl,al,cont,results,adds,dels,facts,rules) {var pat = pat.substring(1,pat.length-1); var re=new RegExp(pat,'g'); var fragments = re.exec(str); - if (fragments!=null) {var ol = seq(); - for (var i=3; i=n) {return results}; - return false}; return hyposomeexit(n,x,cont[0],cont[1],cont[2],results,adds,dels,facts,rules)} //------------------------------------------------------------------------------ + return false}; + return hyposomeexit(n,x,cont[0],cont[1],cont[2],results,adds,dels,facts,rules)} + +//------------------------------------------------------------------------------ function hypovalue (p,adds,dels,facts,rules) {if (varp(p)) {return false}; @@ -1731,7 +2868,8 @@ function hypovalue (p,adds,dels,facts,rules) if (arg!==false) {args[i-1] = arg} else {return false}}; return hypoapply(p[0],args,adds,dels,facts,rules)} -function hypovaluemap (p,adds,dels,facts,rules) {var fun = hypovalue(p[1],adds,dels,facts,rules); +function hypovaluemap (p,adds,dels,facts,rules) + {var fun = hypovalue(p[1],adds,dels,facts,rules); var arglist = hypovalue(p[2],adds,dels,facts,rules); return hypoval(fun,arglist,adds,dels,facts,rules)} @@ -1744,9 +2882,11 @@ function hypoval (fun,arglist,adds,dels,facts,rules) if (results===false) {return false}; return seq('cons',result,results)} -function hypovaluesetofall (p,adds,dels,facts,rules) {return listify(hypofinds(p[1],p[2],adds,dels,facts,rules))} +function hypovaluesetofall (p,adds,dels,facts,rules) + {return listify(hypofinds(p[1],p[2],adds,dels,facts,rules))} -function hypovaluecountofall (p,adds,dels,facts,rules) {return hypofinds(p[1],p[2],adds,dels,facts,rules).length.toString()} +function hypovaluecountofall (p,adds,dels,facts,rules) + {return hypofinds(p[1],p[2],adds,dels,facts,rules).length.toString()} function hypovaluechoose(p,adds,dels,facts,rules) {var possibilities = hypofinds(p[1],p[2],adds,dels,facts,rules); @@ -1769,9 +2909,11 @@ function hypoapply (fun,args,adds,dels,facts,rules) function hypoapplybuiltin (fun,args,adds,dels,facts,rules) {return eval(fun).apply(null,args)} -function hypoapplymath (fun,args,adds,dels,facts,rules) {return stringize(Math[fun].apply(null,args))} +function hypoapplymath (fun,args,adds,dels,facts,rules) + {return stringize(Math[fun].apply(null,args))} -function hypoapplylist (fun,args,adds,dels,facts,rules) {var args = numlistify(args[0]); +function hypoapplylist (fun,args,adds,dels,facts,rules) + {var args = numlistify(args[0]); return stringize(eval(fun).call(null,args))} function hypoapplyrs (fun,args,adds,dels,facts,rules) @@ -1779,9 +2921,13 @@ function hypoapplyrs (fun,args,adds,dels,facts,rules) //var data = indexees('definition',rules); var data = lookuprules(fun,rules); var flag = false; - for (var i=0; i0) {return answers[0]}; - return false} -function debugfinds (result,query,facts,rules) {return zniquify(debugfindn(true,result,query,facts,rules))} + return false} + +function debugfinds (result,query,facts,rules) + {return zniquify(debugfindn(true,result,query,facts,rules))} function debugfindn (n,result,query,facts,rules) {var xl = {}; @@ -2013,28 +3204,49 @@ function debugfindn (n,result,query,facts,rules) debugsome(n,result,xl,query,seq(),xl,nil,answers,facts,rules); return answers} -function debugdepth (cont) {var n = 0; for (var c=cont; c!==nil; c = c[3]) {n++}; return n} +function debugdepth (cont) + {var n = 0; + for (var c=cont; c!==nil; c = c[3]) {n++}; + return n} //------------------------------------------------------------------------------ -function debugsome (n,x,xl,p,pl,al,cont,results,facts,rules) {inferences = inferences + 1; if (debugdepth(cont)>depth) {return false}; +function debugsome (n,x,xl,p,pl,al,cont,results,facts,rules) + {inferences = inferences + 1; + if (debugdepth(cont)>depth) {return false}; if (symbolp(p)) - {return debugsomeatom(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='same') - {return debugsomesame(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='distinct') - {return debugsomedistinct(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='matches') - {return debugsomematches(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='submatches') - {return debugsomesubmatches(n,x,xl,p,pl,al,cont,results,facts,rules)} if (specialp(p[0])) - {return debugsomeeval(n,x,xl,p,pl,al,cont,results,facts,rules)} if (builtinp(p[0])) - {return debugsomecall(n,x,xl,p,pl,al,cont,results,facts,rules)} if (mathp(p[0])) - {return debugsomemath(n,x,xl,p,pl,al,cont,results,facts,rules)} if (listop(p[0])) - {return debugsomelist(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='map') - {return debugsomemap(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='setofall') - {return debugsomesetofall(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='countofall') - {return debugsomecountofall(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='evaluate') - {return debugsomeevaluate(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='member') - {return debugsomemember(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='not') - {return debugsomenot(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='and') - {return debugsomeand(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='or') + {return debugsomeatom(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='same') + {return debugsomesame(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='distinct') + {return debugsomedistinct(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='matches') + {return debugsomematches(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='submatches') + {return debugsomesubmatches(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (specialp(p[0])) + {return debugsomeeval(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (builtinp(p[0])) + {return debugsomecall(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (mathp(p[0])) + {return debugsomemath(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (listop(p[0])) + {return debugsomelist(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='map') + {return debugsomemap(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='setofall') + {return debugsomesetofall(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='countofall') + {return debugsomecountofall(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='evaluate') + {return debugsomeevaluate(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='member') + {return debugsomemember(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='not') + {return debugsomenot(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='and') + {return debugsomeand(n,x,xl,p,pl,al,cont,results,facts,rules)} + if (p[0]==='or') {return debugsomeor(n,x,xl,p,pl,al,cont,results,facts,rules)} if (p[0]==='true') {return debugsometrue(n,x,xl,p,pl,al,cont,results,facts,rules)} @@ -2042,10 +3254,12 @@ function debugsome (n,x,xl,p,pl,al,cont,results,facts,rules) {inferences = infe {return debugsomebase(n,x,xl,p,pl,al,cont,results,facts,rules)}; return debugsomeview(n,x,xl,p,pl,al,cont,results,facts,rules)} -function debugsomeatom (n,x,xl,p,pl,al,cont,results,facts,rules) {if (p==='true') +function debugsomeatom (n,x,xl,p,pl,al,cont,results,facts,rules) + {if (p==='true') {tracecall(p,cont); traceexit(p,cont); - return debugsomeexit(n,x,xl,p,pl,al,cont,results,facts,rules)}; if (p==='false') + return debugsomeexit(n,x,xl,p,pl,al,cont,results,facts,rules)}; + if (p==='false') {tracecall(p,cont); tracefail(p,cont); return false}; @@ -2053,22 +3267,31 @@ function debugsomeatom (n,x,xl,p,pl,al,cont,results,facts,rules) {if (p==='true {return debugsomebase(n,x,xl,p,pl,al,cont,results,facts,rules)}; return debugsomeview(n,x,xl,p,pl,al,cont,results,facts,rules)} -function debugsomesame (n,x,xl,p,pl,al,cont,results,facts,rules) {var goal = pluug(p,al,xl); +function debugsomesame (n,x,xl,p,pl,al,cont,results,facts,rules) + {var goal = pluug(p,al,xl); tracecall(goal,cont); - var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) {traceexit(pluug(p,al,xl),cont); + var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) + {traceexit(pluug(p,al,xl),cont); var answer = debugsomeexit(n,x,xl,goal,pl,al,cont,results,facts,rules); backup(ol); return answer}; tracefail(goal,cont); - return false} function debugsomedistinct (n,x,xl,p,pl,al,cont,results,facts,rules) {var goal = pluug(p,al,xl); + return false} + +function debugsomedistinct (n,x,xl,p,pl,al,cont,results,facts,rules) + {var goal = pluug(p,al,xl); tracecall(goal,cont); - var ol = seq(); if (vnifyp(p[1],al,p[2],al,ol)) + var ol = seq(); + if (vnifyp(p[1],al,p[2],al,ol)) {backup(ol); tracefail(p,cont); - return false}; traceexit(goal,cont); + return false}; + traceexit(goal,cont); return debugsomeexit(n,x,xl,goal,pl,al,cont,results,facts,rules)} -function debugsomematches (n,x,xl,p,pl,al,cont,results,facts,rules) {var goal = pluug(p,al,xl); +function debugsomematches (n,x,xl,p,pl,al,cont,results,facts,rules) + {var goal = pluug(p,al,xl); tracecall(goal,cont); var str = pluug(p[1],al,al); if (!stringp(str)) {return false}; @@ -2078,29 +3301,42 @@ function debugsomematches (n,x,xl,p,pl,al,cont,results,facts,rules) {var goal = pat = pat.substring(1,pat.length-1); var re=new RegExp(pat,'g'); var fragments = re.exec(str); - if (fragments!=null) {var ol = seq(); - for (var i=3; i=n) {return results}; - return false}; return debugsomegoals(n,x,xl,cont[0],cont[1],cont[2],cont[3],results,facts,rules)} + return false}; + return debugsomegoals(n,x,xl,cont[0],cont[1],cont[2],cont[3],results,facts,rules)} //============================================================================== // special relations and operators @@ -2294,9 +3588,14 @@ function updateop (x) {return findq(x,["pos", "neg"])} function specialp (x) {return findq(x,specials)} function builtinp (x) {return findq(x,builtins)} function mathp (x) {return (typeof Math[x]==='function')} -function listop (x) {return findq(x,listoperators)} function aggregatep (x) {return findq(x,aggregates)} +function listop (x) {return findq(x,listoperators)} +function aggregatep (x) {return findq(x,aggregates)} + +//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ var datasets = {} function putfact (p,d) +var datasets = {} + +function putfact (p,d) {return savefact(p,getdataset(d))} function remfact (p,d) @@ -2307,8 +3606,11 @@ function getdataset (id) if (dum) {return dum}; return seq()} -//------------------------------------------------------------------------------ function mutex () - {var exp=new Array(arguments.length); for (var i=0; i=0; i--) {exp = seq('cons',s[i],exp)}; - return exp} function numlistify (c) + return exp} + +function numlistify (c) {var s = seq(); while (true) {if (c===nil) {return s}; @@ -2600,7 +3918,9 @@ function listify (s) if (isNaN(arg)) {return false}; s[s.length] = arg; c = c[2]}; - return false} function delistify (c) + return false} + +function delistify (c) {var s = seq(); while (true) {if (c===nil) {return s}; @@ -2608,8 +3928,9 @@ function listify (s) if (c[0]!=='cons') {return false}; s[s.length] = c[1]; c = c[2]}; - return false} -//------------------------------------------------------------------------------ + return false} + +//------------------------------------------------------------------------------ function timestamp () {return stringize(Date.now())} @@ -2642,34 +3963,204 @@ function getsecond (stamp) {return stringize(new Date(numberize(stamp)).getSeconds())} //============================================================================== -// reading //============================================================================== - function read (str) {try {return fastread(str)} catch (err) {return 'error'}} function readdata (str) {try {return fastreaddata(str)} catch (err) {return seq()}} - function readitems (str) {try {return fastreaditems(str)} catch (err) {return seq()}} - function fastread (str) {return parse(scan(str))} function fastreaddata (str) {return parsedata(scan(str))} function fastreaditems (str) {return parseitems(scan(str))} //------------------------------------------------------------------------------ var input = ''; var output = ''; var current = 0; function scan (str) {input = str; output = new Array(0); var cur = 0; var len = input.length; while (cur < len) {var charcode = input.charCodeAt(cur); if (charcode<=32) {cur++} else if (charcode===33) {output[output.length] = '!'; cur++} else if (charcode===34) {cur = scanstring(cur)} else if (charcode===35) {output[output.length] = '#'; cur++} else if (charcode===37) {cur = scancomment(cur)} else if (charcode===38) {output[output.length] = '&'; cur++} else if (charcode===40) {output[output.length] = 'lparen'; cur++} else if (charcode===41) {output[output.length] = 'rparen'; cur++} else if (charcode===42) {output[output.length] = '*'; cur++} else if (charcode===43) {output[output.length] = '+'; cur++} else if (charcode===44) {output[output.length] = 'comma'; cur++} else if (charcode===45) {output[output.length] = '-'; cur++} else if (charcode===58) {cur = scanrulesym(cur)} else if (charcode===61) {cur = scanthussym(cur)} else if (charcode===91) {output[output.length] = '['; cur++} +// reading +//============================================================================== + +function read (str) + {try {return fastread(str)} catch (err) {return 'error'}} + +function readdata (str) + {try {return fastreaddata(str)} catch (err) {return seq()}} + +function readitems (str) + {try {return fastreaditems(str)} catch (err) {return seq()}} + +function fastread (str) + {return parse(scan(str))} + +function fastreaddata (str) + {return parsedata(scan(str))} + +function fastreaditems (str) + {return parseitems(scan(str))} + +//------------------------------------------------------------------------------ + +var input = ''; +var output = ''; +var current = 0; + +function scan (str) + {input = str; + output = new Array(0); + var cur = 0; + var len = input.length; + while (cur < len) + {var charcode = input.charCodeAt(cur); + if (charcode<=32) {cur++} + else if (charcode===33) {output[output.length] = '!'; cur++} + else if (charcode===34) {cur = scanstring(cur)} + else if (charcode===35) {output[output.length] = '#'; cur++} + else if (charcode===37) {cur = scancomment(cur)} + else if (charcode===38) {output[output.length] = '&'; cur++} + else if (charcode===40) {output[output.length] = 'lparen'; cur++} + else if (charcode===41) {output[output.length] = 'rparen'; cur++} + else if (charcode===42) {output[output.length] = '*'; cur++} + else if (charcode===43) {output[output.length] = '+'; cur++} + else if (charcode===44) {output[output.length] = 'comma'; cur++} + else if (charcode===45) {output[output.length] = '-'; cur++} + else if (charcode===58) {cur = scanrulesym(cur)} + else if (charcode===61) {cur = scanthussym(cur)} + else if (charcode===91) {output[output.length] = '['; cur++} else if (charcode===93) {output[output.length] = ']'; cur++} else if (charcode===95) {output[output.length] = '_'; cur++} - else if (charcode===124) {output[output.length] = '|'; cur++} else if (charcode===126) {output[output.length] = '~'; cur++} else if (idcharp(charcode)) {cur = scansymbol(cur)} else {throw 'error'}}; return output} function scanrulesym (cur) {if (input.length<=cur+1) {throw 'error'}; + else if (charcode===124) {output[output.length] = '|'; cur++} + else if (charcode===126) {output[output.length] = '~'; cur++} + else if (idcharp(charcode)) {cur = scansymbol(cur)} + else {throw 'error'}}; + return output} + +function scanrulesym (cur) + {if (input.length<=cur+1) {throw 'error'}; if (input.charCodeAt(cur+1)===45) {output[output.length] = ':-'; return cur+2}; if (input.charCodeAt(cur+1)===58) {output[output.length] = '::'; return cur+2}; if (input.charCodeAt(cur+1)===61) - {output[output.length] = ':='; return cur+2}; throw 'error'} function scanthussym (cur) {if (input.length>cur+2 && input.charCodeAt(cur+1)===61 - && input.charCodeAt(cur+2)===62) {output[output.length] = '==>'; return cur+3}; throw 'error'} function scansymbol (cur) {var n = input.length; var exp = ''; while (cur < n) {if (idcharp(input.charCodeAt(cur))) {exp = exp + input.charAt(cur); cur++} else break}; if (exp!=='') {output[output.length] = exp}; return cur} function scanstring (cur) {var exp = '"'; cur++; while (cur < input.length) {exp = exp + input.charAt(cur); if (input.charCodeAt(cur)===34) {cur++; break}; cur++}; output[output.length] = exp; return cur} + {output[output.length] = ':='; return cur+2}; + throw 'error'} + +function scanthussym (cur) + {if (input.length>cur+2 && input.charCodeAt(cur+1)===61 + && input.charCodeAt(cur+2)===62) + {output[output.length] = '==>'; return cur+3}; + throw 'error'} -function scancomment (cur) {while (cur= 65 && charcode <= 90) || (charcode >= 97 && charcode <= 122))} function digitp (charcode) {return (charcode >= 48 && charcode <= 57)} function idcharp (charcode) {if (charcode===42) {return true}; if (charcode===43) {return true}; if (charcode===45) {return true}; if (charcode===46) {return true}; if (charcode===47) {return true}; if (charcode >= 48 && charcode <= 57) {return true}; if (charcode >= 65 && charcode <= 90) {return true}; if (charcode >= 97 && charcode <= 122) {return true}; if (charcode===95) {return true}; return false} //------------------------------------------------------------------------------ function parse (str) {input = str; current = 0; return parsexp('lparen','rparen')} function parsedata (str) {input = str; current = 0; var exp = seq(); while (current=input.length) {throw 'error'}; - var left = parseprefix(rop); while (current= 65 && charcode <= 90) || + (charcode >= 97 && charcode <= 122))} + +function digitp (charcode) + {return (charcode >= 48 && charcode <= 57)} + +function idcharp (charcode) + {if (charcode===42) {return true}; + if (charcode===43) {return true}; + if (charcode===45) {return true}; + if (charcode===46) {return true}; + if (charcode===47) {return true}; + if (charcode >= 48 && charcode <= 57) {return true}; + if (charcode >= 65 && charcode <= 90) {return true}; + if (charcode >= 97 && charcode <= 122) {return true}; + if (charcode===95) {return true}; + return false} + +//------------------------------------------------------------------------------ + +function parse (str) + {input = str; + current = 0; + return parsexp('lparen','rparen')} + +function parsedata (str) + {input = str; + current = 0; + var exp = seq(); + while (current=input.length) {throw 'error'}; + var left = parseprefix(rop); + while (current') {return parsetransition(left,rop)}; if (op===':=') {return parsedefinition(left,rop)}; if (op===':-') {return parserule(left,rop)}; if (op==='::') {return parsehandler(left,rop)}; throw 'error'} - -function parsecons (left,rop) {current++; return seq('cons',left,parsexp('!',rop))} function parseand (left,rop) {current++; +function parseinfix (left,op,rop) + {if (op==='!') {return parsecons(left,rop)}; + if (op==='&') {return parseand(left,rop)}; + if (op==='|') {return parseor(left,rop)}; + if (op==='==>') {return parsetransition(left,rop)}; + if (op===':=') {return parsedefinition(left,rop)}; + if (op===':-') {return parserule(left,rop)}; + if (op==='::') {return parsehandler(left,rop)}; + throw 'error'} + +function parsecons (left,rop) + {current++; + return seq('cons',left,parsexp('!',rop))} + +function parseand (left,rop) + {current++; var right = parsexp('&',rop); - var result; if (symbolp(left) || left[0]!=='and') {result = seq('and',left)} + var result; + if (symbolp(left) || left[0]!=='and') {result = seq('and',left)} else {result = left}; if (symbolp(right) || right[0]!=='and') {result.push(right)} else {result = result.concat(right.slice(1))} return result} - function parseor (left,rop) {current++; + +function parseor (left,rop) + {current++; var right = parsexp('|',rop); - var result; if (symbolp(left) || left[0]!=='or') {result = seq('or',left)} + var result; + if (symbolp(left) || left[0]!=='or') {result = seq('or',left)} else {result = left}; if (symbolp(right) || right[0]!=='or') {result.push(right)} else {result = result.concat(right.slice(1))} return result} - function parsedefinition (left,rop) {current++; return makedefinition(left,parsexp(':=',rop))} function parserule (left,rop) {current++; return makerule(left,parsexp(':-',rop))} function parsetransition (left,rop) {current++; return maketransition(left,parsexp('==>',rop))} function parsehandler (left,rop) {current++; return makehandler(left,parsexp('::',rop))} -function makehandler (head,body) {return seq('handler',head,body)} - var infixes = ['!','&','|','==>',':=',':-','::'] +function parsedefinition (left,rop) + {current++; + return makedefinition(left,parsexp(':=',rop))} + +function parserule (left,rop) + {current++; + return makerule(left,parsexp(':-',rop))} + +function parsetransition (left,rop) + {current++; + return maketransition(left,parsexp('==>',rop))} + +function parsehandler (left,rop) + {current++; + return makehandler(left,parsexp('::',rop))} + +function makehandler (head,body) + {return seq('handler',head,body)} + + +var infixes = ['!','&','|','==>',':=',':-','::'] var tokens = ['!','#','~','&','|','==>',':=',':-','::','[',']','lparen','rparen','comma','.'] function identifierp (x) {return !find(x,tokens)} - var precedence = ['!','#','~','&','|','==>',':=',':-','::'] - function precedencep (lop,rop) {for (var i=0; i',':=',':-','::'] + +function precedencep (lop,rop) + {for (var i=0; i= 48 && charcode <= 57) {return true}; if (charcode >= 65 && charcode <= 90) {return true}; if (charcode >= 97 && charcode <= 122) {return true}; if (charcode===95) {return true}; return false} function kifdata (str) {str.push('eof'); input = str; current = 0; exp = new Array(0); while (current < input.length && input[current]!=='eof') {exp[exp.length] = kifexp()}; return exp} function kif (str) {str.push('eof'); input = str; current = 0; return kifexp()} function kifexp () {var lexeme = input[current]; if (lexeme==='eof') {return nil}; if (lexeme==='<=') {current++; return 'rule'}; if (lexeme==='lparen') {return kifparenlist()}; current++; return lexeme} function kifparenlist () {var exp = new Array(0); current++; if (input[current]==='rparen') {current++; return exp}; while (current < input.length) {exp.push(kifexp()); if (input[current]==='rparen') {current++; return exp}}; return exp} //============================================================================== -// writing //============================================================================== -function printseq (p) {if (p===true) {return 'true'}; +function parenp (lop,op,rop) + {return precedencep(lop,op) || !precedencep(op,rop)} + +//------------------------------------------------------------------------------ +// readkifdata +// readkif +//------------------------------------------------------------------------------ + +function readkifdata (str) + {return kifdata(kifscan(str))} + +function readkif (str) + {return kif(kifscan(str))} + +function kifscan (str) + {input = str; + output = new Array(0); + var cur = 0; + var len = input.length; + while (cur < len) + {var charcode = input.charCodeAt(cur); + if (charcode===32 || charcode===13) {cur++} + else if (charcode===34) {cur = scanstring(cur)} + else if (charcode===40) {output[output.length] = 'lparen'; cur++} + else if (charcode===41) {output[output.length] = 'rparen'; cur++} + else if (charcode===59) {cur = kifscancomment(cur)} + else if (charcode===63) {cur = kifscanvariable(cur)} + else if (kifidcharp(charcode)) {cur = kifscansymbol(cur)} + else cur++}; + return output} + +function kifscansymbol (cur) + {var exp = ''; + while (cur < input.length) + {if (kifidcharp(input.charCodeAt(cur))) {exp = exp + input[cur]; cur++} + else break}; + if (exp!=='') {output[output.length] = exp}; + return cur} + +function kifscanvariable (cur) + {cur++; + var exp = ''; + if (letterp(input.charCodeAt(cur))) + {exp=input.slice(cur,cur+1).toUpperCase(); cur++} + else {exp = 'VV'}; + while (cur < input.length) + {if (kifidcharp(input.charCodeAt(cur))) {exp = exp + input[cur]; cur++} + else break}; + if (exp!=='') {output[output.length] = exp}; + return cur} + +function kifscanstring (cur) + {var exp = ''; + cur++ + while (cur < input.length && input.charCodeAt(cur)!==34) + {exp = exp + input[cur]; cur++}; + cur++; + output[output.length] = exp + return cur} + +function kifscancomment (cur) + {while (cur < input.length && input.charCodeAt(cur)!==10 && input.charCodeAt(cur)!==13) {cur++}; + return cur} + +function kifidcharp (charcode) + {if (charcode===45) {return true}; + if (charcode===46) {return true}; + if (charcode===60) {return true}; + if (charcode===61) {return true}; + if (charcode >= 48 && charcode <= 57) {return true}; + if (charcode >= 65 && charcode <= 90) {return true}; + if (charcode >= 97 && charcode <= 122) {return true}; + if (charcode===95) {return true}; + return false} + +function kifdata (str) + {str.push('eof'); + input = str; + current = 0; + exp = new Array(0); + while (current < input.length && input[current]!=='eof') + {exp[exp.length] = kifexp()}; + return exp} + +function kif (str) + {str.push('eof'); + input = str; + current = 0; + return kifexp()} + +function kifexp () + {var lexeme = input[current]; + if (lexeme==='eof') {return nil}; + if (lexeme==='<=') {current++; return 'rule'}; + if (lexeme==='lparen') {return kifparenlist()}; + current++; return lexeme} + +function kifparenlist () + {var exp = new Array(0); + current++; + if (input[current]==='rparen') {current++; return exp}; + while (current < input.length) + {exp.push(kifexp()); + if (input[current]==='rparen') {current++; return exp}}; + return exp} + +//============================================================================== +// writing +//============================================================================== + +function printseq (p) + {if (p===true) {return 'true'}; if (p===false) {return 'false'}; - if (typeof p==='number') {return p}; if (typeof p==='string') {return '"' + p + '"'}; var n = p.length; var exp = '('; if (n>0) {exp += printseq(p[0])}; for (var i=1; i0) {exp += printseq(p[0])}; + for (var i=1; i'} return exp} function printem (data) {var exp = ''; var n = data.length; for (var i=0; i0) {exp += printit(p[0])}; for (var i=1; i\n'); win.document.writeln('<?xml-stylesheet type="text/xsl" href="../stylesheets/proof.xsl"?>
\n'); win.document.write(xmlproof()); win.document.close()} function xmlproof () {var exp = ''; exp += '<proof>
\n'; for (var i=1; i\n'; exp += ' <sentence>' + grind(proof[i][1]) + '</sentence>
\n'; exp += ' <justification>' + prettify(proof[i][2]) + '</justification>
\n'; for (var j=3; j\n'}; exp += ' </step>
\n'}; exp += '</proof>
\n'; return exp} function xmlify (str) {str = str.replace('&','&'); str = str.replace('<=>','<=>'); return str} //------------------------------------------------------------------------------ function smoothdata (data) {var exp = ''; var n = data.length; for (var i=0; i'} return exp} function smooth (p) {if (symbolp(p)) {return p}; var exp = p[0] + '('; if (p.length > 1) {exp += smooth(p[1])}; for (var i=2; i'; exp = exp + ''; exp = exp + ' '; //exp = exp + ''; exp = exp + 'StepProofJustification'; exp = exp + ''; for (var i=0; i'; exp = exp + ''; exp = exp + '' + (i/3 + 1) + ''; exp = exp + '' + grind(proof[i+1]) + ''; exp = exp + '' + proof[i+2] + ''; exp = exp + ''}; exp = exp + ''; return exp} //------------------------------------------------------------------------------ function grinddata (data) {var exp = ''; var n = data.length; for (var i=0; i'} return exp} function grindem (data) {var exp = ''; var n = data.length; for (var i=0; i'} + return exp} + +function printem (data) + {var exp = ''; + var n = data.length; + for (var i=0; i0) {exp += printit(p[0])}; + for (var i=1; i\n'); + win.document.writeln('<?xml-stylesheet type="text/xsl" href="../stylesheets/proof.xsl"?>
\n'); + win.document.write(xmlproof()); + win.document.close()} + +function xmlproof () + {var exp = ''; + exp += '<proof>
\n'; + for (var i=1; i\n'; + exp += ' <sentence>' + grind(proof[i][1]) + '</sentence>
\n'; + exp += ' <justification>' + prettify(proof[i][2]) + '</justification>
\n'; + for (var j=3; j\n'}; + exp += ' </step>
\n'}; + exp += '</proof>
\n'; + return exp} + +function xmlify (str) + {str = str.replace('&','&'); + str = str.replace('<=>','<=>'); + return str} + +//------------------------------------------------------------------------------ + +function smoothdata (data) + {var exp = ''; + var n = data.length; + for (var i=0; i'} + return exp} + +function smooth (p) + {if (symbolp(p)) {return p}; + var exp = p[0] + '('; + if (p.length > 1) {exp += smooth(p[1])}; + for (var i=2; i'; + exp = exp + ''; + exp = exp + ' '; //exp = exp + ''; + exp = exp + 'StepProofJustification'; + exp = exp + ''; + for (var i=0; i'; + exp = exp + ''; + exp = exp + '' + (i/3 + 1) + ''; + exp = exp + '' + grind(proof[i+1]) + ''; + exp = exp + '' + proof[i+2] + ''; + exp = exp + ''}; + exp = exp + ''; + return exp} + +//------------------------------------------------------------------------------ + +function grinddata (data) + {var exp = ''; + var n = data.length; + for (var i=0; i'} + return exp} + +function grindem (data) + {var exp = ''; + var n = data.length; + for (var i=0; i1) {exp += grind(p[1])}; for (var i=2; i',rop); if (parens) {lop = 'lparen'; rop = 'rparen'}; if (parens) {exp = '('}; exp = exp + grindit(p[1],lop,'==>') + ' ==> ' + grindit(p[2],'==>',rop); if (parens) {exp = exp + ')'}; return exp} + return out} + +function grindatom (p) + {var n = p.length; + var exp = p[0] + '('; + if (n>1) {exp += grind(p[1])}; + for (var i=2; i',rop); + if (parens) {lop = 'lparen'; rop = 'rparen'}; + if (parens) {exp = '('}; + exp = exp + grindit(p[1],lop,'==>') + ' ==> ' + grindit(p[2],'==>',rop); + if (parens) {exp = exp + ')'}; + return exp} + +function grinddefinition (p,lop,rop) + {var exp = ''; + var parens = parenp(lop,':=',rop); + if (parens) {lop = 'lparen'; rop = 'rparen'}; + if (parens) {exp = '('}; + exp = exp + grindit(p[1],lop,':=') + ' := ' + grindit(p[2],':=',rop); + if (parens) {exp = exp + ')'}; + return exp} + +function grindrule (p,lop,rop) + {var exp = grind(p[1]) + ' :- '; + if (p.length===2) {exp += 'true'} + else if (p.length===3) {exp += grindit(p[2],':-',rop)} + else {exp += grindit(p[2],lop,'&'); + for (var i=3; i'} + return exp} -function grindrule (p,lop,rop) {var exp = grind(p[1]) + ' :- '; if (p.length===2) {exp += 'true'} else if (p.length===3) {exp += grindit(p[2],':-',rop)} else {exp += grindit(p[2],lop,'&'); for (var i=3; i'} return exp} //------------------------------------------------------------------------------ function displayrules (rules) +function displayrules (rules) {exp = ''; for (var i=0; i ' + grind(p[2]) + '\n'}; if (p[2].length<4) {return grind(p[1]) + ' ==>\n ' + grind(p[2]) + '\n'}; - var exp = grind(p[1]) + ' ==>\n'; for (var i=1; i\n'; + for (var i=1; i'; + exp = exp + ''; + exp = exp + ''; + exp = exp + 'StepProofJustification'; + exp = exp + ''; + for (var i=1; i'; + exp = exp + ''; + exp = exp + '' + i + ''; + exp = exp + '' + grind(proof[i][1]) + ''; + exp += ''; + exp += prettify(proof[i][2]); + if (proof[i].length > 3) + {exp += ': ' + proof[i][3]; + for (var j=4; j'}; + exp = exp + ''; + return exp} -function disphandler (p) {return grind(p[1]) + ' :: ' + grind(p[2]) + '\n'} +function prettify (str) + {return str.replace('_',' ')} -//------------------------------------------------------------------------------ function displayproof (proof) {var exp = ''; exp = exp + ''; exp = exp + ''; exp = exp + ''; exp = exp + ''; exp = exp + ''; for (var i=1; i'; exp = exp + ''; exp = exp + ''; exp = exp + ''; exp += '
StepProofJustification
' + i + '' + grind(proof[i][1]) + ''; exp += prettify(proof[i][2]); if (proof[i].length > 3) {exp += ': ' + proof[i][3]; for (var j=4; j'}; exp = exp + '
'; return exp} function prettify (str) {return str.replace('_',' ')} //------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // morefacts // morerules // loadfacts @@ -2830,7 +4743,8 @@ function showfacts (source) {output += grind(facts[j]) + '\n'}; output += '\n'}; return output} - function dumprules (source,filename) + +function dumprules (source,filename) {fs.writeFileSync(filename,showrules(source)); return true} @@ -2845,15 +4759,16 @@ function showrules (source) return output} //============================================================================== -// Error checking //============================================================================== - +// Error checking +//============================================================================== + function finderrors (data) {var errors = findarityerrors(data); errors = errors.concat(findsafetyerrors(data)); errors = errors.concat(findstratificationerrors(data)); return errors} -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ function findarityerrors (data) {arities = seq(); @@ -2891,28 +4806,47 @@ function findsafetyerrors (data) {errors[errors.length] = 'Unsafe rule: ' + grind(data[i])}}; return errors} -function safep (exp) {if (symbolp(exp)) {return true}; if (exp[0]==='rule') {return saferulep(exp)}; if (exp[0]==='transition') {return safetransitionp(exp)}; return groundp(exp)} function groundp (exp) {if (varp(exp)) {return false}; if (symbolp(exp)) {return true}; for (var i=0; i debugfinds(query, query, mergedDataset, EPILOG_RULESET) as string[][], + () => compfinds(query, query, mergedDataset, EPILOG_RULESET) as string[][], + //() => debugfinds(query, query, mergedDataset, EPILOG_RULESET) as string[][], [query, mergedDataset], ); diff --git a/apps/react/src/pages/ClaimSingle.tsx b/apps/react/src/pages/ClaimSingle.tsx index b8a30a0..8f7d807 100644 --- a/apps/react/src/pages/ClaimSingle.tsx +++ b/apps/react/src/pages/ClaimSingle.tsx @@ -1,14 +1,16 @@ import { ROUTES } from "common"; -import { useCallback, useContext, useEffect } from "react"; +import { useCallback, useContext, useEffect, useMemo } from "react"; import { useNavigate } from "react-router-dom"; import RequiresExistingClaim from "../components/RequiresExistingClaim"; import RequiresLogin from "../components/RequiresLogin"; import RequiresUserDataset from "../components/RequiresUserDataset"; -import Covid19VaccineForm from "../components/forms/Covid19VaccineForm"; -import ContraceptivesForm from "../components/forms/ContraceptivesForm"; +//import Covid19VaccineForm from "../components/forms/Covid19VaccineForm"; +//import ContraceptivesForm from "../components/forms/ContraceptivesForm"; +import GeneralPolicyForm from "../components/forms/GeneralPolicyForm"; import { ExistingClaimContext } from "../contexts/existingClaimContext"; import { UserDatasetContext } from "../contexts/userDatasetContext"; -import { Covid19Vaccine, Contraceptives } from "../epilog/form-adapters/_formAdapter"; +//import { Covid19Vaccine, Contraceptives } from "../epilog/form-adapters/_formAdapter"; +import GeneralFormAdapter from "../epilog/form-adapters/generalFormAdapter"; import useIdParam from "../hooks/useClaimIdParam"; import { useUserDataset } from "../api/userDataset"; import { LoginContext } from "../contexts/loginContext"; @@ -21,6 +23,7 @@ import Container from "../components/Container"; export default function ClaimPage() { const claimId = useIdParam("claim"); const navigate = useNavigate(); + console.log("claimIdOnClaimSinglePage", claimId); useEffect(() => { if (!claimId) navigate(ROUTES.INDEX); @@ -50,6 +53,8 @@ function RenderClaimForm() { const sessionUser = useContext(LoginContext); const userDataset = useContext(UserDatasetContext); const existingClaimId = useContext(ExistingClaimContext); + const navigate = useNavigate(); + if (!sessionUser || !userDataset || !existingClaimId) throw new Error( @@ -60,66 +65,109 @@ function RenderClaimForm() { // TODO Infer the correct form from the claim reason etc. If not enough info is available in the dataset, show the corrupted callout below. - const service = compfinds("X", read(`claim.service_type(${existingClaimId}, X)`), definemorefacts([], userDataset), [])[0]?.slice(1, -1); + const service = useMemo(() => { + console.log("userDatasetInUseMemo()", userDataset); + const rawService = compfinds("X", read(`claim.service_type(${existingClaimId}, X)`), definemorefacts([], userDataset), [])[0]; + console.log("rawService", rawService); + return (typeof rawService === 'string' ? rawService.slice(1, -1) : "contraceptives"); // Default if undefined or not string + }, [existingClaimId, userDataset]); - const { formAdapter } = service === "contraceptives" ? Contraceptives : - service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; + const formAdapter = useMemo(() => new GeneralFormAdapter(service, userDataset, existingClaimId, true), [service, userDataset, existingClaimId]); + + console.log("userDatasetBeforeInitialFormValues", userDataset); const initialFormValues = formAdapter.epilogToFormValues( userDataset, existingClaimId, ); + console.log("initialFormValuesInClaimSingle", initialFormValues); +// const { formAdapter } = service === "contraceptives" ? Contraceptives : +// service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; - const { mutation } = useUserDataset(sessionUser.id); +// const initialFormValues = formAdapter.epilogToFormValues( +// userDataset, +// existingClaimId, +// ); - const covid19OnClickSave = useCallback( - (formValues: Covid19Vaccine.FormValues) => { - const formDataset = formAdapter.formValuesToEpilog(formValues); - const mergedDataset = definemorefacts(formDataset, userDataset); - mutation.mutate(mergedDataset); - // TODO Test if, because of this mutation, a re-render of RequiresUserDataset is triggered. - }, - [formAdapter, mutation], - ); - const contraceptivesOnClickSave = useCallback( - (formValues: Contraceptives.FormValues) => { - const formDataset = formAdapter.formValuesToEpilog(formValues); - const mergedDataset = definemorefacts(formDataset, userDataset); - mutation.mutate(mergedDataset); - // TODO Test if, because of this mutation, a re-render of RequiresUserDataset is triggered. - }, - [formAdapter, mutation], - ); + const { mutation } = useUserDataset(sessionUser.id); - const onClickSave = - service === "contraceptives" ? contraceptivesOnClickSave : - service === "covidVaccine" ? covid19OnClickSave : covid19OnClickSave; +// const covid19OnClickSave = useCallback( +// (formValues: Covid19Vaccine.FormValues) => { +// const formDataset = formAdapter.formValuesToEpilog(formValues); +// const mergedDataset = definemorefacts(formDataset, userDataset); +// mutation.mutate(mergedDataset); +// // TODO Test if, because of this mutation, a re-render of RequiresUserDataset is triggered. +// }, +// [formAdapter, mutation], +// ); + +// const contraceptivesOnClickSave = useCallback( +// (formValues: Contraceptives.FormValues) => { +// const formDataset = formAdapter.formValuesToEpilog(formValues); +// const mergedDataset = definemorefacts(formDataset, userDataset); +// mutation.mutate(mergedDataset); +// // TODO Test if, because of this mutation, a re-render of RequiresUserDataset is triggered. +// }, +// [formAdapter, mutation], +// ); + +// const onClickSave = +// service === "contraceptives" ? contraceptivesOnClickSave : +// service === "covidVaccine" ? covid19OnClickSave : covid19OnClickSave; // console.log("SERVICE:", service); - if (service === "covidVaccine") { - return ( - - - - ); - } else if (service === "contraceptives") { - return ( - - - - ); - } else { - return
Service not recognized.
; - } + const onClickSave = useCallback( + (formValues: any) => { // Adjust the type here as needed + console.log("currentformValues in ClaimSingle", formValues); + const dataset = formAdapter.formValuesToEpilog(formValues); + console.log("current dataset", dataset); + const mergedDataset = definemorefacts(dataset, userDataset); + console.log("current mergedDataset", mergedDataset); + mutation.mutateAsync(mergedDataset) + .then(() => navigate(ROUTES.getClaimUrl(formValues.claim.id.toString()))) + .catch((error: any) => console.error("Failed to submit claim:", error)); + }, + [formAdapter, mutation, navigate, userDataset] + ); + + return ( + + + + ); + + + + +// if (service === "covidVaccine") { +// return ( +// +// +// +// ); +// } else if (service === "contraceptives") { +// return ( +// +// +// +// ); +// } else { +// console.log("service not recognized in ClaimSingle"); +// return
Service not recognized.
; +// } } /* diff --git a/apps/react/src/pages/Dashboard.tsx b/apps/react/src/pages/Dashboard.tsx index 9d30ccf..7ccba21 100644 --- a/apps/react/src/pages/Dashboard.tsx +++ b/apps/react/src/pages/Dashboard.tsx @@ -61,6 +61,7 @@ export default function Dashboard() { } const details = getClaimDetailsById(id, dataset); // Use getClaimDetailsById + console.log("getClaimDetailsById(id, dataset) in Dashboard", details); return details ? { id: details.id, label: serviceTypeToLabel(details.serviceType) || 'Unknown Service Type', diff --git a/apps/react/src/pages/Explore.tsx b/apps/react/src/pages/Explore.tsx index 3cb437e..86b2831 100644 --- a/apps/react/src/pages/Explore.tsx +++ b/apps/react/src/pages/Explore.tsx @@ -1,15 +1,17 @@ import { ROUTES } from "common"; import { getClaimUrl } from "common/src/routes"; -import { useCallback, useContext } from "react"; +import { useCallback, useContext, useMemo } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { useUserDataset } from "../api/userDataset"; import RequiresLogin from "../components/RequiresLogin"; import RequiresUserDataset from "../components/RequiresUserDataset"; -import Covid19VaccineForm from "../components/forms/Covid19VaccineForm"; -import ContraceptivesForm from "../components/forms/ContraceptivesForm"; +//import Covid19VaccineForm from "../components/forms/Covid19VaccineForm"; +//import ContraceptivesForm from "../components/forms/ContraceptivesForm"; +import GeneralPolicyForm from "../components/forms/GeneralPolicyForm"; import { LoginContext } from "../contexts/loginContext"; import { UserDatasetContext } from "../contexts/userDatasetContext"; -import { Covid19Vaccine, Contraceptives } from "../epilog/form-adapters/_formAdapter"; +//import { Covid19Vaccine, Contraceptives } from "../epilog/form-adapters/_formAdapter"; +import GeneralFormAdapter from "../epilog/form-adapters/generalFormAdapter"; import useSessionUser from "../hooks/useSessionUser"; import { setAfterLoginAction } from "../utils/storage"; import Container from "../components/Container"; @@ -37,43 +39,82 @@ export default function ExplorePage() { ); } - const { formAdapter } = service === "contraceptives" ? Contraceptives : - service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; +// const { formAdapter } = service === "contraceptives" ? Contraceptives : +// service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; +if (!service) { + return
Service type is required.
; + } - const initialFormValues = formAdapter.epilogToFormValues([]); + const formAdapter = useMemo(() => new GeneralFormAdapter(service, definemorefacts([], []), undefined, true), [service]); + const initialFormValues = useMemo(() => formAdapter.epilogToFormValues(definemorefacts([], [])), [formAdapter]); const onClickSave = useCallback( - (formValues: Covid19Vaccine.FormValues) => { - const formDataset = formAdapter.formValuesToEpilog(formValues); - setAfterLoginAction({ - saveToUserDataset: formDataset, - redirectPath: ROUTES.getClaimUrl(formValues.claim.id + ""), - }); - navigate(ROUTES.LOGIN); + (formValues: any) => { + try { + console.log("entered try in OnClickSave"); + const dataset = formAdapter.formValuesToEpilog(formValues); + const claimId = formValues.claim?.id; + if (!claimId) { + console.error("Claim ID is undefined."); + return; + } + setAfterLoginAction({ + saveToUserDataset: dataset, + redirectPath: ROUTES.getClaimUrl(claimId.toString()), + }); + navigate(ROUTES.LOGIN); + } catch (error) { + console.error("Error processing form data:", error); + } }, - [formAdapter, navigate], + [formAdapter, navigate] ); - // console.log("initialFormValues", initialFormValues); - // console.log("service", service); - - - if (service === "covidVaccine") { - return ( - { +// const formDataset = formAdapter.formValuesToEpilog(formValues); +// setAfterLoginAction({ +// saveToUserDataset: formDataset, +// redirectPath: ROUTES.getClaimUrl(formValues.claim.id + ""), +// }); +// navigate(ROUTES.LOGIN); +// }, +// [formAdapter, navigate], +// ); + + console.log("initialFormValues", initialFormValues); + console.log("service", service); + + return ( + + - ); - } else if (service === "contraceptives") { - return ( - - ); - } else { - return
Service not recognized.
; - } +
+ ); + + + +// if (service === "covidVaccine") { +// return ( +// +// ); +// } else if (service === "contraceptives") { +// return ( +// +// ); +// } else { +// return
Service not recognized.
; +// } } function RenderNewClaimFormLoggedIn() { @@ -95,52 +136,100 @@ function RenderNewClaimFormLoggedIn() { // 1. The onClickSave function is different. It navigates to the claim page. // 2. The initialFormValues are generated differently. The second argument to epilogToFormValues is undefined, which makes the function generate a new distinct claimId. - const { formAdapter } = service === "contraceptives" ? Contraceptives : - service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; +// const { formAdapter } = service === "contraceptives" ? Contraceptives : +// service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; +if (!service) { + return
Service type is required.
; + } + + const formAdapter = useMemo(() => new GeneralFormAdapter(service, userDataset, undefined, true), [service, userDataset]); + const initialFormValues = useMemo(() => {const values = formAdapter.epilogToFormValues(userDataset); console.log("values in useMemo", values); return values}, [formAdapter, userDataset]); + // Passing undefined as the second argument to epilogToFormValues will // make the function generate a new distinct claimId // TODO If the user opens the form two times, both will assume the same claimId. If one then gets saved, and then the other, the latter will overwrite the first claim. - const initialFormValues = formAdapter.epilogToFormValues( - userDataset, - undefined, - ); + const { mutation } = useUserDataset(sessionUser.id); const navigate = useNavigate(); const onClickSave = useCallback( - (formValues: Covid19Vaccine.FormValues) => { - const formDataset = formAdapter.formValuesToEpilog(formValues); - const mergedDataset = definemorefacts(formDataset, userDataset); - mutation - .mutateAsync(mergedDataset) - .then(() => navigate(getClaimUrl(formValues.claim.id + ""))); + (formValues: any) => { + console.log("Received Form Values in Explore:", formValues); + + if (!formValues || !formValues.claim || typeof formValues.claim.id !== 'string') { + console.error("Claim ID is undefined or not properly formatted. Received form values:", formValues); + return; + } + + const claimId = formValues.claim.id; + console.log("claimId in onClickSave", claimId); + + const dataset = formAdapter.formValuesToEpilog(formValues); + console.log("dataset in onClickSave", JSON.stringify(dataset)); + + const mergedDataset = definemorefacts(dataset, userDataset); + + console.log("merged dataset in onClickSave", JSON.stringify(mergedDataset)); + + + mutation.mutateAsync(mergedDataset) + .then(() => { + console.log("Navigating to claim with ID:", claimId); + navigate(getClaimUrl(claimId)); + }) + .catch(error => console.error("Failed to submit claim:", error)); }, - [formAdapter, mutation], + [formAdapter, navigate, userDataset, mutation] ); - - if (service === "covidVaccine") { - return ( - - - - ); - } else if (service === "contraceptives") { - return ( - - - - ); - } else { - return
Service not recognized.
; - } + + + +// const onClickSave = useCallback( +// (formValues: Covid19Vaccine.FormValues) => { +// const formDataset = formAdapter.formValuesToEpilog(formValues); +// const mergedDataset = definemorefacts(formDataset, userDataset); +// mutation +// .mutateAsync(mergedDataset) +// .then(() => navigate(getClaimUrl(formValues.claim.id + ""))); +// }, +// [formAdapter, mutation], +// ); + + + return ( + + + + ); + + +// if (service === "covidVaccine") { +// return ( +// +// +// +// ); +// } else if (service === "contraceptives") { +// return ( +// +// +// +// ); +// } else { +// return
Service not recognized.
; +// } } diff --git a/apps/react/src/pages/Explore_old.tsx b/apps/react/src/pages/Explore_old.tsx new file mode 100644 index 0000000..bd28371 --- /dev/null +++ b/apps/react/src/pages/Explore_old.tsx @@ -0,0 +1,159 @@ +import { ROUTES } from "common"; +import { getClaimUrl } from "common/src/routes"; +import { useCallback, useContext } from "react"; +import { useNavigate, useParams } from "react-router-dom"; +import { useUserDataset } from "../api/userDataset"; +import RequiresLogin from "../components/RequiresLogin"; +import RequiresUserDataset from "../components/RequiresUserDataset"; +import Covid19VaccineForm from "../components/forms/Covid19VaccineForm"; +import ContraceptivesForm from "../components/forms/ContraceptivesForm"; +import { LoginContext } from "../contexts/loginContext"; +import { UserDatasetContext } from "../contexts/userDatasetContext"; +import { Covid19Vaccine, Contraceptives } from "../epilog/form-adapters/_formAdapter"; +import useSessionUser from "../hooks/useSessionUser"; +import { setAfterLoginAction } from "../utils/storage"; +import Container from "../components/Container"; + +export default function ExplorePage() { + // TODO Infer the correct form from service param. + + // The challenge is that this page may be accessed by both, logged in and logged out users. + // Thus, first, the generation of the default values is done two ways. Either with or without the user dataset. + // Second, the save action differs. Either we merge with the exisitng user dataset and upload it + // or we save the form values to the local storage and send to user to the login. + // In any case, we then need to redirect the user to the /claim/(claimId) page. + const { service } = useParams(); + const sessionUser = useSessionUser(); + + const navigate = useNavigate(); + + if (sessionUser) { + return ( + + + + + + ); + } + + const { formAdapter } = service === "contraceptives" ? Contraceptives : + service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; + + const initialFormValues = formAdapter.epilogToFormValues([]); + + const onClickSave = useCallback( + (formValues: Covid19Vaccine.FormValues) => { + const formDataset = formAdapter.formValuesToEpilog(formValues); + setAfterLoginAction({ + saveToUserDataset: formDataset, + redirectPath: ROUTES.getClaimUrl(formValues.claim.id + ""), + }); + navigate(ROUTES.LOGIN); + }, + [formAdapter, navigate], + ); + console.log("initialFormValues", initialFormValues); + console.log("service", service); + + + if (service === "covidVaccine") { + return ( + + ); + } else if (service === "contraceptives") { + return ( + + ); + } else { + return
Service not recognized.
; + } +} + +function RenderNewClaimFormLoggedIn() { + /* ------------------------ Environmental conditions ------------------------ */ + const sessionUser = useContext(LoginContext); + const { service } = useParams(); + const userDataset = useContext(UserDatasetContext); + + if (!sessionUser || !userDataset) + throw new Error( + "LoginContext and ExistingClaimContext are required. Please wrap this component in RequiresLogin and RequiresUserDataset.", + ); + + /* --------------------------------- Render --------------------------------- */ + + // TODO Infer the correct form from the claim reason etc. If not enough info is available in the dataset, show the corrupted callout below. + + // TODO The code below is a copy of the code in apps/react/src/pages/Claim.tsx. Find a way to abstract away this code duplication. But note that there are two modifications here: + // 1. The onClickSave function is different. It navigates to the claim page. + // 2. The initialFormValues are generated differently. The second argument to epilogToFormValues is undefined, which makes the function generate a new distinct claimId. + + const { formAdapter } = service === "contraceptives" ? Contraceptives : + service === "covidVaccine" ? Covid19Vaccine : Covid19Vaccine; + + // Passing undefined as the second argument to epilogToFormValues will + // make the function generate a new distinct claimId + + // TODO If the user opens the form two times, both will assume the same claimId. If one then gets saved, and then the other, the latter will overwrite the first claim. + + const initialFormValues = formAdapter.epilogToFormValues( + userDataset, + undefined, + ); + + const { mutation } = useUserDataset(sessionUser.id); + const navigate = useNavigate(); + + const onClickSave = useCallback( + (formValues: any) => { + console.log("Received Form Values:", formValues); + + if (!formValues || !formValues.claim || typeof formValues.claim.id !== 'string') { + console.error("Claim ID is undefined or not properly formatted. Received form values:", formValues); + return; + } + + const claimId = formValues.claim.id; // This assumes claim.id is directly accessible and properly formatted + const { dataset } = formAdapter.formValuesToEpilog(formValues); + + const mergedDataset = definemorefacts(dataset, userDataset); + mutation.mutateAsync(mergedDataset) + .then(() => { + console.log("Navigating to claim with ID:", claimId); + navigate(getClaimUrl(claimId)); // Ensure this URL construction is correct + }) + .catch(error => console.error("Failed to submit claim:", error)); + }, + [formAdapter, navigate, userDataset, mutation] + ); + + + if (service === "covidVaccine") { + return ( + + + + ); + } else if (service === "contraceptives") { + return ( + + + + ); + } else { + return
Service not recognized.
; + } +} diff --git a/apps/react/src/pages/WaiveCardinalCare.tsx b/apps/react/src/pages/WaiveCardinalCare.tsx index 4214958..d869615 100644 --- a/apps/react/src/pages/WaiveCardinalCare.tsx +++ b/apps/react/src/pages/WaiveCardinalCare.tsx @@ -219,10 +219,10 @@ const WaiveCardinalCare = () => { }; const titleStyle = { - fontSize: '32px', // Adjusted for a larger banner + fontSize: '36px', // Adjusted for a larger banner fontWeight: 'bold', flex: '1', - marginLeft: '20px', + marginLeft: '530px', }; const infoButtonStyle = { diff --git a/apps/react/src/utils/epilogUtils.ts b/apps/react/src/utils/epilogUtils.ts index c4fe9f5..8c64e4c 100644 --- a/apps/react/src/utils/epilogUtils.ts +++ b/apps/react/src/utils/epilogUtils.ts @@ -1,5 +1,4 @@ import { BasicOption } from "../types/basicOption"; -import { Person } from '../types/Person'; import { Claim } from '../types/Claim'; @@ -20,7 +19,7 @@ export type ID_PREFIX = /* Read */ /* -------------------------------------------------------------------------- */ -export const removeEscapedDoubleQoutes = (str: string) => str.replace(/"/g, ""); +export const removeEscapedDoubleQuotes = (str: string) => str.replace(/"/g, ""); export const compfindsReturnToBasicOptions = ( compfindsReturn: ReturnType, @@ -44,7 +43,7 @@ export const compfindsReturnToBasicOptions = ( JSON.stringify(entry), ); - return { id, label: removeEscapedDoubleQoutes(label) }; + return { id, label: removeEscapedDoubleQuotes(label) }; } throw new Error( @@ -150,7 +149,7 @@ export const getClaimDetailsById = (claimId: string, dataset: ReturnType { const X = "X"; const query = read(`${idPrefix}(${X})`); + console.log("get existing ids query:", query); const existingIds = compfinds(X, query, userDataset, []) as string[]; return existingIds.sort(); }; @@ -279,13 +279,13 @@ export const getFirstOrNextId = ( /* --------------------------------- Person --------------------------------- */ -export const getPersonDetailsById = (userId, dataset) => { +export const getPersonDetailsById = (userId: string, dataset: ReturnType) => { // Initialize an object to hold the person's details let personDetails = { id: userId, dob: '', occupation: '', - immunocompromised: '' + immunocompromised: false }; // Filter dataset for entries related to the person @@ -293,10 +293,10 @@ export const getPersonDetailsById = (userId, dataset) => { if (entry[1] === userId) { switch (entry[0]) { case 'person.dob': - personDetails.dob = entry[2]; + personDetails.dob = entry[2] || ''; break; case 'person.occupation': - personDetails.occupation = entry[2]; + personDetails.occupation = entry[2] || ''; break; case 'person.immunocompromised': personDetails.immunocompromised = entry[2] === 'yes' ? true : false; diff --git a/apps/server/var/sessions.db b/apps/server/var/sessions.db index 4ed9d3e..61e459a 100644 Binary files a/apps/server/var/sessions.db and b/apps/server/var/sessions.db differ diff --git a/apps/server/var/sqlite.db b/apps/server/var/sqlite.db index ade4e21..dc9c46e 100644 Binary files a/apps/server/var/sqlite.db and b/apps/server/var/sqlite.db differ diff --git a/package.json b/package.json index e3ddab4..351217e 100644 --- a/package.json +++ b/package.json @@ -21,14 +21,6 @@ "typescript": "^5.4.2" }, "dependencies": { - "@emotion/react": "^11.11.4", - "@emotion/styled": "^11.11.5", - "@mui/icons-material": "^5.15.15", - "@mui/material": "^5.15.15", - "@mui/x-date-pickers": "^7.1.1", - "AdapterDayjs": "link:@mui/x-date-pickers/AdapterDayjs", - "date-fns": "^3.6.0", - "react-datepicker": "^6.6.0", - "react-icons": "^5.0.1" + "date-fns": "^3.6.0" } }