Commit Graph

183 Commits

Author SHA1 Message Date
985d476bc1 ABDM: finalize ABHA verify persistence, M2 routes/workflows, and location masters seeding 2026-06-24 03:15:22 +05:30
386055a0cd fix(discharge): unify history panel behavior and form nav sync 2026-06-22 02:40:50 +05:30
96c030b72d chore: checkpoint before discharge history panel refactor 2026-06-22 02:05:24 +05:30
1bac1f6e04 feat: update storestock flow and ABDM bridge handling 2026-06-18 17:38:20 +05:30
5a1a87ebe1 Adjust IPD bill print signature spacing 2026-06-14 14:38:59 +05:30
d4b4c95cbc Fix IPD discharge and bill print issues 2026-06-14 14:34:33 +05:30
4e8c5c691f Update OPD history profile view 2026-06-11 19:38:55 +05:30
cad5a477bf Sync OPD history flow and discharge UI refinements 2026-06-11 19:30:02 +05:30
0c2e1385cb Refine IPD discharge summary layout 2026-06-11 11:53:39 +05:30
c437652b79 Add IPD status management with strict ipd_status check
- Update isIpdDischargedInvoice to check ONLY ipd_status field (remove fallback checks)
- Add IPD status toggle UI in discharge panel (Active/Discharged control)
- Create toggleIpdStatus controller method with permission check
- Add billing.ipd.status.manage permission for controlling bill edit lock
- Allows editing bills when needed by toggling status independently of discharge_date
- Auto-releases bed when setting status to discharged
2026-06-10 12:55:47 +05:30
15458715a8 Fix bill print summary rows colspan - align amounts to Amount column
- Change colspan from 3 to 4 (normal mode) and 4 to 5 (discount mode)
- Ensures Gross Total, Net Amount, Payment Recd., Balance amounts appear in Amount column
- Fixes blank cells in Rate column by properly spanning Description through Rate columns
2026-06-10 12:00:08 +05:30
bb95756700 Fix IPD Discharge medicine section: dose labels, Rx-Groups, and substitutes
- Fix dose columns showing IDs instead of labels (OD, BID, TDS, etc.)
- Add Rx-Group functionality with modal, search, and bulk add
- Add substitute medicine suggestions with one-click use
- Improve medicine autocomplete with debouncing and scope=all
- Load dose master maps in controller and pass to view
- Match OPD Consult UI/UX patterns for consistency
2026-06-09 17:23:34 +05:30
0568851783 Add Print Header checkbox for IPD bill printing - allows printing on letterhead 2026-06-08 17:18:02 +05:30
c4932601f1 Fix: Re-initialize CKEditor after Save Discharge Advice button
ISSUE 2: After clicking 'Save Discharge Advice', CKEditor turns into plain textarea

ROOT CAUSE: initInstructionTools() was not re-initializing CKEditor after AJAX section reload
- When user clicks button with data-reload-section='section-instructions'
- Form submits via AJAX, returns updated HTML
- Section content replaced with new HTML
- initInstructionTools() called but did NOT restore CKEditor
- Fields remain as plain textareas

SOLUTION: Added CKEditor re-initialization to initInstructionTools()

Changes to discharge_create.php initInstructionTools():
1. Check if CKEDITOR is available
2. Destroy existing instances first (instruction_other, instruction_remark)
3. Re-create CKEditor for both fields with same config
4. Prevents duplicate instances and ensures editors work after reload

TESTING:
- Type in instruction_remark or instruction_other
- Click 'Save Discharge Advice'
- After reload, both fields should still be CKEditor (not textarea)
- Can continue editing with toolbar

NOTE: Issue 1 (data mixing between fields) requires separate investigation
User can test with: php check_instruction_data.php to see actual DB values
2026-06-07 19:48:33 +05:30
ea07063675 Fix: Prevent duplicate medicine saves on 'Save Discharge Advice' button
ISSUE: Medicines were being saved twice - once via Add button AJAX, and again when clicking 'Save Discharge Advice' button.

ROOT CAUSE:
1. Legacy code in save_main handler (lines 5489-5538) read 'discharge_medicine_json' POST field
2. JavaScript serializeDischargeMedicineTable() collected all medicine table rows into JSON
3. On form submit (Save Discharge Advice), JSON was sent and controller re-inserted all medicines
4. Result: duplicate entries in ipd_discharge_prescrption_prescribed table

SOLUTION:
- DISABLED controller code that processes discharge_medicine_json in save_main handler
- DISABLED JavaScript call to serializeDischargeMedicineTable() on form submit
- Medicines now saved ONLY via Add button AJAX (action='add_drug')
- Save Discharge Advice button now only saves dietary advice, instructions, review after, etc.

TESTING:
1. Add medicines via Add button (saves immediately)
2. Click Save Discharge Advice (does NOT save medicines again)
3. No duplicate entries in database
2026-06-07 09:03:12 +05:30
fd70cc46cf Change medicine save to auto-save on Add button click (AJAX)
Medicine Save Behavior Change:
- Previously: Medicines added to table locally, saved on 'Save Discharge Advice' click
- Now: AJAX auto-save immediately when '+ADD / Update' button is clicked
- Matches OPD Consult Form workflow (instant save on add)

Implementation:
- Modified btn_discharge_med_add click handler to make AJAX POST
- POST parameters: action='add_drug', ajax_mode='json', new_drug_name, new_drug_type,
  new_drug_dose, new_drug_when, new_drug_freq, new_drug_day, new_drug_qty, new_drug_remark
- Controller add_drug action already existed - now returns JSON when ajax_mode='json'
- On success: adds row to table, clears form, shows 'Medicine saved successfully'
- On failure: shows error message from server
- CSRF token updated after each AJAX call

Remove Button Behavior:
- Remove button now shows confirmation dialog
- Warns user: 'This will only remove from current view. Reload to see saved medicines.'
- Note: Remove action is NOT yet AJAX - full page reload shows actual DB state
- Future enhancement: make Remove button also AJAX (action='remove_drug')

Technical Notes:
- Kept discharge_medicine_json serialization as backup (unused now, but harmless)
- Medicine data: med_id=0 marks client-added medicines
- Success check: data.update === 1
- Error handling: network timeout 30s, shows xhr.status on fail
- Form fields cleared after successful save
- Focus returns to medicine name field for next entry

User Benefits:
- Instant feedback - no need to scroll down and click 'Save Discharge Advice'
- Medicines immediately persisted to database
- Can add multiple medicines in quick succession
- Consistent with OPD prescription workflow
- Reduced risk of data loss (saves immediately vs. waiting for form submit)
2026-06-06 21:00:30 +05:30
e731ef61e9 Fix discharge medicine save, add CKEditor, and Review After quick select
Medicine Saving Fix (MAJOR):
- Add hidden field 'discharge_medicine_json' to capture medicine table data
- Add serializeDischargeMedicineTable() function to convert DOM table to JSON before form submit
- Hook serialization into form submit event (before syncEditorValues)
- Update controller to process discharge_medicine_json in save_main action
- Insert medicines into ipd_discharge_prescrption_prescribed or ipd_discharge_prescription_prescribed table
- Medicine data now persists on page reload

CKEditor Integration:
- Initialize CKEditor for 'instruction_other' (Other Advice) field
- Initialize CKEditor for 'instruction_remark' (Discharge Summary) field
- Add simplified toolbar: Bold, Italic, Underline, Lists, Undo/Redo
- Properly destroy existing instances before re-initialization
- Height: 120px for Other Advice, 150px for Discharge Summary

Review After Quick Select Buttons:
- Add getNextVisitOptions() method to Ipd_discharge controller (copied from Opd_prescription)
- Add resolveFirstField() helper method
- Pass next_visit_options array to view
- Render quick select buttons: '3 Days (09-06-2026)', '1 Week (13-06-2026)', etc.
- Add JavaScript handler: click button → populate #discharge_review_after input
- Change Review After field from col-md-4 to col-md-6 for better layout
- Add col-md-12 wrapper for button row with flex-wrap gap-2 layout

Technical Details:
- Medicine JSON structure: {med_type, med_name, dosage, dosage_when, dosage_freq, no_of_days, qty, remark}
- JSON processing includes column existence checks for flexibility
- Quick select buttons use data-value attribute for value insertion
- Falls back to hardcoded date options if opd_nextvisit table missing
- Medicine insert uses med_id=0 to mark client-added medicines

User Workflow:
1. Add medicines → shown in table (Type, Medicine, Dose labels, Duration formatted)
2. Click 'Save Discharge Advice' → medicines serialize to JSON → POST to controller
3. Controller parses JSON → inserts to database → medicines persist on reload
4. Other Advice/Discharge Summary now have rich text editing (bold, lists, etc.)
5. Review After: click '1 Week (13-06-2026)' button → auto-fills input
2026-06-06 20:53:05 +05:30
e229ae3df2 Improve discharge medicine display and rename Instructions section
Medicine Table Improvements:
- Swap column order: Type column now appears before Medicine Name
- Display dose labels (text) instead of numeric IDs for Dose, When, Freq
- Auto-format duration: numeric values get 'days' suffix (e.g., '5' -> '5 days')
- Single day shows 'day' (singular), multiple days show 'days' (plural)
- Preserve custom duration formats like '1 month' or '3 doses'

Section Rename:
- Change 'Discharge Instructions / Advice' to 'Discharge Summary'
- Updated in card header, navigation menu, and form label
- Better reflects comprehensive discharge information

Technical:
- Use doseMasterCache to resolve ID->label for Dose/When/Freq/Route
- Regex check for numeric-only duration values before formatting
- Maintain backward compatibility with existing data
2026-06-06 20:42:15 +05:30
fdc6ae352b Remove duplicate old medicine form code causing null reference error
- Removed old code referencing non-existent field IDs (#new_drug_name, etc.)
- Fixed 'medInput is null' JavaScript error
- Kept only new implementation with correct IDs (#discharge_med_name, etc.)
- Cleaned up normalizeRxShortCode and unused event listeners
- Fix console error: Uncaught TypeError: can't access property addEventListener
2026-06-06 20:22:36 +05:30
66b5e1b6a5 Fix discharge medicine autocomplete and auto-fill - use OPD medicine_search endpoint
- Change from rx_group_medicine_suggest to Opd_prescription/medicine_search endpoint
- Match OPD Consult Form data source and behavior
- Auto-fill Type, Dose, When, Frequency, Route, Days, Qty, and Remark from medicine master
- Add ensureDoseOption helper to handle current values not in dropdown list
- Store medicine rows for auto-fill on selection
- Improved user experience with comprehensive auto-complete
2026-06-06 20:18:30 +05:30
ee5b29f688 Upgrade IPD Discharge Medicine form to OPD-style Rx prescription interface
- Replace simple text inputs with advanced prescription form
- Add medicine autocomplete with datalist suggestions
- Add dropdown selects for Dose, When, Frequency, and Route from dose masters
- Integrate with existing Opd_prescription/rx_group_dose_masters endpoint
- Add medicine type auto-fill from medicine database
- Add quick-fill buttons for common values (BF/AF/WF, OD/BD/TDS/HS, 3/5/7 Days)
- Improve UI with two-column layout: medicine list table (left) + add form (right)
- Add real-time medicine suggestions via rx_group_medicine_suggest endpoint
- Support Remove All functionality
- Dynamic table row add/remove with proper event binding
- Better UX matching OPD Consult Form prescription interface
2026-06-06 20:10:52 +05:30
d82078c9ed Convert patient search to DataTables with AJAX server-side processing
- Updated Patient::search() to only render view with search query
- Created Patient::search_ajax() method for DataTables AJAX endpoint
- Implemented server-side processing with pagination, sorting, and filtering
- Results ordered by Last Visit DESC by default
- Retrieves all patient data from patient_master table
- Added proper SQL escaping to prevent injection
- Updated Patient_Search_V.php to use DataTables with AJAX remote data
- Added DataTables configuration with 25 rows per page default
- Supports dynamic length menu (10, 25, 50, 100, All)
- Added route for billing/patient/search_ajax endpoint
- Improved user experience with loading spinner and customized messages
2026-06-06 14:52:10 +05:30
b5cfedec96 Make quick-add modal larger (modal-lg) for better UX
IMPROVEMENT: Increased modal size for better readability

Changed modal-dialog from default to modal-lg
- Provides more space for SNOMED CT and ICD code fields
- Better readability for field labels and help text
- More comfortable data entry experience
- Consistent with other modals in the system
2026-06-06 06:58:38 +05:30
38e06ed1d7 Add 'Save in Master' quick-add for Course/Treatment section
FEATURE: Quick-add functionality for Course/Treatment master terms

NEW COMPONENTS:
1. Course master table: ipd_discharge_course_master
   - term_name, term_code, icd_code, is_active
   - Auto-creates on first use
2. Controller endpoints in Ipd_discharge.php:
   - course_master_lookup() - AJAX autocomplete search
   - course_master_list() - Full list with filters
   - course_master_save() - Create/update records
   - course_master_delete() - Remove records
3. Routes added to Config/Routes.php:
   - Ipd_discharge/course_master_lookup (GET)
   - Ipd_discharge/course_master_list (GET)
   - Ipd_discharge/course_master_save (POST)
   - Ipd_discharge/course_master_delete (POST)

VIEW CHANGES (discharge_create.php):
- Course input now uses input-group layout
- Green 'Save in Master' button added
- Custom dropdown for autocomplete with code badges
- Hidden field: new_course_master_id
- JavaScript: initCourseAutocomplete() function
- Integrated with existing quickAddTermModal

QUICK-ADD MODAL ENHANCEMENT:
- Now supports 3 types: surgery, procedure, course
- Dynamic endpoint selection based on type
- Course type uses course_master_save endpoint
- Auto-populates course input and master_id on save

AUTOCOMPLETE FEATURES:
- Type 2+ characters → searches course_master table
- Dropdown shows: Name + SNOMED/ICD code badges
- Arrow key navigation (Up/Down/Enter/Escape)
- Click or Enter to select
- Hover highlighting with visual feedback
- 300ms debounce for performance

WORKFLOW:
1. Type course/treatment name
2. See dropdown with existing terms (if any)
3. Click 'Save in Master' to add new term
4. Modal opens with name pre-filled
5. Enter SNOMED/ICD codes (optional)
6. Save → Auto-populates input + master_id
7. Click '+ADD Row' to add to discharge

BENEFITS:
- Consistent UI across Surgery/Procedure/Course sections
- Fast term entry without leaving form
- Master library builds during workflow
- ABDM compliance with code support
- Reusable terms across discharges
2026-06-06 06:53:27 +05:30
b0b09bc2bf Add 'Save in Master' quick-add buttons for Surgery/Procedure
FEATURE: Quick-add functionality for Surgery and Procedure master terms

NEW COMPONENTS:
1. 'Save in Master' buttons next to Surgery/Procedure inputs
2. Quick-add modal with SNOMED CT and ICD code fields
3. Instant save without opening full Master CRUD modal
4. Auto-populate input and master_id after save

UI CHANGES:
- Surgery/Procedure inputs now use input-group layout
- Green 'Save in Master' button with plus-circle icon
- Quick-add modal opens when clicking button
- Name field auto-filled from input (read-only in modal)
- Optional SNOMED CT code and ICD code fields
- Success message shown before auto-close

WORKFLOW:
1. User types new surgery/procedure name in input
2. Click 'Save in Master' button
3. Modal opens with name pre-filled
4. Enter SNOMED/ICD codes (optional)
5. Click 'Save in Master' in modal
6. Record saves to ipd_discharge_surgery_master table
7. Input filled with saved name
8. master_id hidden field populated
9. Modal closes automatically
10. User can now click '+ADD Row' to add to discharge

BENEFITS:
- No need to open full Master CRUD modal for quick adds
- SNOMED/ICD codes can be added during workflow
- Faster data entry for new terms
- Master table stays organized and updated
- ABDM compliance maintained with code support
2026-06-06 06:38:49 +05:30
5dccbc8d12 Complete Surgery/Procedure autocomplete implementation and testing docs
COMPLETED ALL TODO ITEMS:

✅ Task 1: Enhanced Surgery autocomplete with SNOMED/ICD codes
✅ Task 2: Enhanced Procedure autocomplete with SNOMED/ICD codes
✅ Task 3: Verified Master CRUD integration (modal already working)
✅ Task 4: Created comprehensive testing documentation

KEY FIXES:
- Removed conflicting bindSurgeryTermLookup() calls from initSurgeryTools()
- Old datalist code no longer interferes with new custom dropdown
- Both autocompletes work independently with separate dropdown containers

TESTING DOCUMENT INCLUDES:
- 10 detailed test scenarios with expected results
- Database verification queries
- Troubleshooting guide
- Edge case handling
- Performance checks
- User acceptance checklist
- Future enhancement suggestions

FILE: SURGERY_PROCEDURE_AUTOCOMPLETE_TESTING.md

Ready for QA testing and user acceptance.
2026-06-06 06:35:32 +05:30
b6bca785a8 Add enhanced autocomplete for Surgery/Procedure with SNOMED/ICD codes
FEATURE: Enhanced Surgery and Procedure autocomplete with code display

IMPROVEMENTS:
1. Replaced basic datalist with custom dropdown
2. Display SNOMED codes (term_code) and ICD codes in dropdown items
3. Show codes as badges: blue for SNOMED, gray for ICD
4. Keyboard navigation (Arrow Up/Down, Enter, Escape)
5. Hover highlighting with visual feedback
6. Store master_id in hidden field for database linking

HOW IT WORKS:
- Type 2+ characters → searches ipd_discharge_surgery_master table
- Dropdown shows: Name + Code badges
- Click or Enter → selects item and fills input
- Arrow keys navigate through suggestions
- Escape closes dropdown

UI:
- Name displayed prominently (bold)
- Codes shown as colored badges below name
- Blue badge: SNOMED/term code
- Gray badge: ICD code
- Hover: light gray background
- Keyboard highlight: blue background, white text

Makes it easy to find and select surgeries/procedures from master
with their ABDM codes visible for verification.
2026-06-06 06:29:15 +05:30
e10ea540ba Remove 'Complaint added' status message
Remove the status message after adding complaint - table update
provides sufficient visual feedback.
2026-06-06 06:24:37 +05:30
6f5bacc723 Fix broken event listeners - properly close click handler and wrap keydown
BUGFIX: Uncaught SyntaxError expected expression, got ')'

PROBLEM: Event listeners were malformed - click handler and keydown handler
were merged into one broken block

ROOT CAUSE: The click event listener was missing its closing braces and
btnAdd.click() call. Instead, the keydown handler code was pasted directly
after it WITHOUT the proper addEventListener wrapper. This caused:
1. Missing closing brackets for click handler
2. Reference to undefined 'e' variable (e.key) outside function scope
3. Browser threw SyntaxError/ReferenceError

SOLUTION:
1. Properly closed click event listener:
   - Added btnAdd.click() call
   - Added closing braces for function and addEventListener
   - Added closing }); for forEach loop
   - Added closing }); for \$.get() AJAX call

2. Created separate keydown event listener:
   - Wrapped keyboard navigation code in lookup.addEventListener('keydown', function(e) {...})
   - Now 'e' variable is properly defined in function scope
   - Arrow keys, Enter, Escape all have access to event object

CODE STRUCTURE NOW:
- item.addEventListener('click', ...) - PROPERLY CLOSED
- }); // closes forEach
- }, 'json'); // closes AJAX
- }); // closes input event
- lookup.addEventListener('keydown', function(e) {...}) - NEW/PROPER

All event handlers are now independent and properly scoped.
2026-06-06 06:16:17 +05:30
1a592eda7c Add safer checks for \ variable
Add isset() and is_array() checks before using \ to prevent
PHP warnings/errors if variable is not set or not an array.

This ensures cleaner JavaScript output even if the variable is undefined.
2026-06-06 06:05:32 +05:30
d3e50174b5 Fix trailing comma in JavaScript array from PHP foreach
BUGFIX: Uncaught SyntaxError expected expression, got ')'

PROBLEM: Trailing comma after last array item caused JavaScript syntax error

ROOT CAUSE: PHP foreach loop always added comma after each object:
{...},
{...},  // <-- trailing comma before ]
];

While modern JS allows trailing commas, some parsers or contexts
(like when injected/evaluated) don't handle it well.

SOLUTION: Only add comma between items, not after last item:
1. Count total items before loop
2. Track current index in loop
3. Add comma only if currentIndex < itemCount

GENERATED JS NOW:
[
    {...},
    {...},
    {...}   // <-- no trailing comma
]

This eliminates the syntax error.
2026-06-06 06:00:25 +05:30
f6749d2664 Fix undefined variable - use \ not \
BUGFIX: Uncaught SyntaxError expected expression, got ')'

PROBLEM: JavaScript syntax error on page load caused by undefined PHP variable

ROOT CAUSE: Controller passes 'complaint_rows' to view but JavaScript code
tried to use \ (camelCase). PHP is case-sensitive, so:
- Controller: 'complaint_rows' => \
- View variable name: \ (snake_case)
- Used in view: \ (wrong!)

When \ was undefined, the !empty() check failed and PHP
tried to iterate over undefined variable, generating malformed JavaScript
that caused syntax errors.

SOLUTION: Changed \ to \ in foreach loop

Now the existing complaints will load correctly from database into
the selectedDischargeComplaints JavaScript array.
2026-06-06 05:58:04 +05:30
dde54ab80b Fix scope error - move complaint functions before initComplaintTools
BUGFIX: Uncaught SyntaxError expected expression, got ')'

PROBLEM: selectedDischargeComplaints was undefined when initComplaintTools
tried to use it, causing syntax/reference errors

ROOT CAUSE: JavaScript variable and function declarations were placed
AFTER the initComplaintTools function that used them. When btnAdd
click handler tried to access selectedDischargeComplaints at line 1841,
it was declared later at line 1964.

SOLUTION:
1. Moved selectedDischargeComplaints variable declaration to TOP
2. Moved initDischargeComplaintsTable() function before initComplaintTools
3. Moved renderDischargeComplaintTable() function before initComplaintTools
4. Removed duplicate declarations that were after initComplaintTools

ORDER NOW:
1. selectedDischargeComplaints = [] (global)
2. initDischargeComplaintsTable() function
3. renderDischargeComplaintTable() function
4. initComplaintTools() function (uses all above)

All functions/variables are now in proper scope when needed.
2026-06-06 05:55:12 +05:30
e6ccd6a408 Fix JavaScript syntax error - remove duplicate keydown handler
BUGFIX: Uncaught SyntaxError expected expression, got ')'

PROBLEM: Console error on page load due to malformed JavaScript

ROOT CAUSE: Previous replacement left duplicate code fragment:
- Closing brace of updateDropdownHighlight function was followed by
  'kup.addEventListener' (missing 'loo' prefix)
- This created invalid JavaScript syntax
- Old keydown handler wasn't fully removed

SOLUTION: Removed the duplicate/malformed keydown listener block

The proper keydown handler with arrow key navigation is earlier
in the code and works correctly.
2026-06-06 05:51:44 +05:30
bbaa6ae841 Add keyboard navigation to autocomplete dropdown
FEATURE: Arrow keys now work to navigate autocomplete suggestions

ADDED:
- highlightedIndex variable tracks current keyboard position
- ArrowDown/ArrowUp keys move through dropdown items
- Highlighted item shown with blue background and white text
- Enter key selects highlighted item (or adds typed text if none)
- Escape key closes dropdown
- Mouse hover updates highlightedIndex
- scrollIntoView keeps highlighted item visible in long lists

HOW TO USE:
1. Type complaint name → dropdown appears
2. Press ArrowDown → first item highlights (blue background)
3. Press ArrowDown/ArrowUp → navigate through items
4. Press Enter → selects highlighted item and adds to table
5. Press Escape → closes dropdown

Visual feedback:
- Mouse hover: light gray background
- Keyboard highlight: blue background, white text, bold
2026-06-06 05:49:03 +05:30
4fc64be2a2 Fix autocomplete selection - now adds to client-side array
BUGFIX: Autocomplete dropdown was showing but items weren't selectable

PROBLEM: Clicking autocomplete suggestions didn't add complaints to table

ROOT CAUSE: btnAdd click handler was using old database-submit logic
instead of new client-side array management

SOLUTION: Simplified btnAdd to:
1. Take value from lookup input
2. Check if already exists (prevent duplicates)
3. Add to selectedDischargeComplaints array
4. Call renderDischargeComplaintTable() to refresh
5. Clear input and show success message

HOW IT WORKS NOW:
- Type complaint name → autocomplete dropdown appears
- Click suggestion → sets lookup input value
- btnAdd triggered → adds to array → table refreshes
- Complaint appears in table with editable Frequency/Severity/Duration

All inline editing works without database calls!
2026-06-06 05:46:38 +05:30
58e79318fd Remove buggy database-save-on-blur, implement client-side complaint table
BUGFIX: Removed database errors by switching to OPD-style client-side management

PROBLEM: Every time user edited a complaint field, it tried to save
to database immediately, causing 'Database error' messages in console.

ROOT CAUSE: The inline save approach doesn't match how OPD works.
OPD uses client-side JavaScript array and saves everything on form
submit, not on every keystroke.

SOLUTION:
1. Removed attachComplaintFieldHandlers() with fetch() database calls
2. Created selectedDischargeComplaints JavaScript array
3. Load existing PHP complaints into array on init
4. renderDischargeComplaintTable() builds table from array
5. Input events update array in-memory (no database calls)
6. Table now has Frequency, Severity, Duration columns like OPD

BENEFITS:
- No more database errors
- Faster editing (no network calls)
- OPD-like interface with all columns
- Edit any field without errors
- Will save all changes on form submit

NOTE: Still need to wire up 'Add' button and form submission in next commit.
2026-06-06 05:41:23 +05:30
7f957bfb96 WIP: Redesign IPD complaints table structure to match OPD (Frequency/Severity/Duration columns)
WORK IN PROGRESS: Table structure updated, JavaScript needs complete rewrite

CHANGES:
1. Added Frequency, Severity, Duration columns (matching OPD)
2. Removed static PHP rendering of complaint rows
3. Added hidden discharge_complaints_json field for data storage
4. Added dropdown divs for frequency/severity/duration autocomplete5. Table now has OPD-like structure

NEXT STEPS NEEDED:
- Rewrite JavaScript to use client-side array (like OPD)
- Remove database-save-on-blur code (causing errors)
- Implement render function to build table from array
- Add inline editing with autocomplete
- Save JSON on form submit instead of individual updates

NOTE: This commit has the new table structure but old JavaScript.
The page may not work correctly until JavaScript is updated in next commit.
2026-06-06 05:40:23 +05:30
57691e6a7f Fix AJAX header for complaint field update to pass CI4 isAJAX() check
BUGFIX: HTTP 400 'Invalid request' when saving editable complaint fields

PROBLEM: After adding the route, the request still returned 400 Bad
Request with 'Invalid request' error. The controller's isAJAX() check
was failing and rejecting the request.

ROOT CAUSE: The fetch() API does not automatically add the
X-Requested-With header that CodeIgniter 4's isAJAX() method checks
for. Unlike jQuery.ajax() which adds this header by default, vanilla
fetch() requires explicit header configuration.

SOLUTION: Added 'X-Requested-With': 'XMLHttpRequest' header to the
fetch request in attachComplaintFieldHandlers() function. This is the
standard header that identifies AJAX requests and is what CI4's
Request::isAJAX() method validates.

Now the editable complaint fields save correctly:
- Type in complaint name/remark
- Press Tab or Enter
- Green border = saved successfully
- Changes persist in database
2026-06-06 05:30:20 +05:30
4740c622a8 Redesign IPD discharge complaints table to match OPD consult form interface
UX IMPROVEMENT: Unified table design across OPD and IPD modules

CHANGES:
1. TABLE REDESIGN:
   - Moved autocomplete input INTO table footer (like OPD form)
   - Added row numbers (#) column
   - Compact styling with smaller font sizes (.82rem)
   - Minimal delete button (× symbol) instead of full button
   - Removed separate 'Smart Complaints Picker' section above table
   - Clean, professional Healthplix-style interface

2. AUTOCOMPLETE IMPROVEMENTS:
   - Replaced datalist with custom dropdown menu
   - Better visual feedback with hover effects
   - Click to select from dropdown
   - Enter key to add complaint
   - Auto-close on selection

3. BUTTON REORGANIZATION:
   - AI Draft and Hinglish buttons moved below table
   - Emoji icons for better visual recognition
   - Compact size, less intrusive
   - Removed duplicate Hinglish button from 'Other Complaints' label

4. IMPROVED SPACING:
   - Tighter layout, less vertical space
   - More data visible on screen
   - Professional medical app look and feel

BENEFITS:
- Consistent interface between OPD and IPD modules
- Faster complaint entry with inline autocomplete
- Better use of screen space
- Cleaner, more modern appearance
- Familiar workflow for users switching between OPD/IPD
2026-06-06 05:25:11 +05:30
ddec3cec69 Fix editable complaint fields - attach handlers after section reload
BUGFIX: Event handlers were only attached on initial page load

PROBLEM: After implementing editable complaint fields, the inputs
wouldn't become editable when adding new complaints via the Smart
Complaints Picker. The event handlers were only attached once on
page load, not after the section was dynamically reloaded.

ROOT CAUSE: When clicking Add or AI Draft buttons, the form submits
and the section-complaints area is reloaded from server. The new
complaint rows had the input fields but no event handlers attached.

SOLUTION:
1. Moved event handler attachment logic into initComplaintTools()
   function as new attachComplaintFieldHandlers() helper
2. This function is automatically called after section reload
3. Clone-and-replace pattern to prevent duplicate event handlers
4. Fixed table name: ipd_discharge_complaint (not ipd_discharge_comp)

FLOW:
- Add complaint → section reloads → initComplaintTools() runs →
  attachComplaintFieldHandlers() attaches blur/keydown handlers →
  editable fields work

Now clicking on complaint name/remark inputs works for both:
- Existing complaints (on page load)
- Newly added complaints (after section reload)
2026-06-06 05:18:35 +05:30
2e6bff35a0 Make IPD discharge complaint names and remarks editable like OPD form
FEATURE: Inline editing for discharge complaint table

PROBLEM: In IPD discharge form, complaint names and remarks were
read-only after adding. Unlike OPD consult form where you can edit
complaint names directly in the table.

SOLUTION:
1. VIEW Changes (discharge_create.php):
   - Changed complaint name and remark columns from static <td> to editable <input>
   - Added data attributes for complaint ID and original values
   - Added CSS classes: discharge-complaint-name-input, discharge-complaint-remark-input

2. JAVASCRIPT Changes:
   - Added saveComplaintField() function for AJAX updates
   - Event handlers on blur to save changes
   - Enter key support to blur and save
   - Visual feedback: green border on success, red on error
   - Auto-updates original value after successful save

3. CONTROLLER Changes (Ipd_discharge.php):
   - Added update_complaint_field() method for AJAX endpoint
   - Updates ipd_discharge_comp table (comp_report or comp_remark)
   - Returns JSON success/error response

BENEFITS:
- Same user experience as OPD consult form
- Edit complaints/remarks without page reload
- Immediate feedback on save success/failure
- Type correction and updates without removing and re-adding rows
2026-06-06 05:12:23 +05:30
5847f642d8 Make discharge preview top panel sticky and add action buttons
IMPROVEMENTS:
1. Sticky top panel - stays visible when scrolling
2. Action buttons moved to top panel for easy access
3. Compact layout with better button organization

CHANGES:
- Added .discharge-preview-sticky-header class with position: sticky
- Moved all action buttons to top panel:
  * Back to Edit button (with edit icon)
  * Print on Letter Head dropdown (PDF icon)
  * Print on Plain Paper dropdown (file icon)
- Added icons to buttons for better UX
- Made buttons smaller (btn-sm) to fit in top panel
- Reduced margins and padding for compact layout
- Removed duplicate buttons from bottom
- Top panel now includes: header, patient info, action buttons, template selector

BENEFITS:
- Buttons always visible even when scrolling long discharge summary
- No need to scroll up/down to access print functions
- Better workflow for reviewing and printing
2026-06-06 04:46:17 +05:30
3de14194a7 Add Preview button at top of IPD discharge form
IMPROVEMENT: Preview button now always visible at top of page

PROBLEM: Preview button was at bottom in sidebar, often hidden
and users had to scroll to find it.

SOLUTION:
- Added Preview button at top right after patient header
- Button labeled 'Preview Discharge Summary' with eye icon
- Original sidebar button still present for convenience
- Top button uses same onclick handler as sidebar button

Now users can easily preview discharge summary without scrolling.
2026-06-06 04:42:00 +05:30
3e21ab57b0 Make diagnosis column editable in OPD consult form
- Convert diagnosis name from static text to editable input field
- Add event handlers for diagnosis name editing (input, blur, keydown)
- Users can now edit diagnosis text after adding it to the table
- Duration and Date remain editable as before
- Enter key moves focus from diagnosis to duration field
- Auto-sync with selectedDiagnosisItems and SNOMED JSON on edit
- Apply proper SNOMED styling (blue text) only when concept_id exists
2026-06-06 02:57:54 +05:30
09c3be0755 Fix jQuery CSS error in complaint name input
- Fix 'can't access property toUpperCase' error when rendering complaint table
- Apply SNOMED styling conditionally only when complaint has concept_id
- Use proper jQuery css() object notation instead of string
2026-06-06 02:54:00 +05:30
d156e26ac1 Make complaint column editable in OPD consult form
- Convert complaint name from static text to editable input field
- Add event handlers for complaint name editing (input, blur, keydown)
- Users can now edit complaint text after adding it to the table
- Frequency, Severity, Duration remain editable as before
- Enter key moves focus from complaint to frequency field
- Auto-sync with selectedComplaintItems and SNOMED JSON on edit
2026-06-06 02:50:44 +05:30
8ef46cddb1 Add permission for Admin to edit patient name anytime
- Add billing.patient.edit-name-anytime permission to AuthGroups
- Update patient edit time restriction from 12 hours to 24 hours
- Modify Person_Edit_V to check for edit-name-anytime permission
- Admin can now edit patient name field (input_name) even after 24-hour window
2026-06-05 17:33:31 +05:30
6f6286f427 Add {{Tadvise_test_list}} placeholder for investigation test names
Created new OPD template placeholder to display investigation test names
as a formatted HTML list, separate from the textarea {{investigation}}.

Changes:
- app/Controllers/Opd.php:
  * Added $rxInvestigationTestList variable in buildLegacyDashboardTemplateVars()
  * Builds HTML <ul> list from rx_investigations test names
  * Added 'Tadvise_test_list' token to return array

- app/Views/billing/opd_template_builder.php:
  * Added 'Tadvise_test_list' to $opdConsultSet placeholder list
  * Now appears in "OPD Consult" group in template builder

Usage in OPD templates:
- {{investigation}} = comma-separated test names (for textarea)
- {{Tadvise_test_list}} = formatted HTML bullet list of test names (for print/display)

Example output:
<ul style="margin:3px 0 0 16px;padding:0;list-style-type:disc;">
  <li>CBC (Complete Blood Count)</li>
  <li>USG WHOLE ABDOMEN</li>
  <li>ECG (Electrocardiogram)</li>
</ul>
2026-06-05 15:15:15 +05:30
55e56176aa fix(discharge-ui): simplify preview and remove ABDM sandbox panel 2026-06-05 09:40:30 +05:30